text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
#pragma once
#include <aws/clouddirectory/CloudDirectory_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/clouddirectory/model/IndexAttachment.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace CloudDirectory
{
namespace Model
{
class AWS_CLOUDDIRECTORY_API ListAttachedIndicesResult
{
public:
ListAttachedIndicesResult();
ListAttachedIndicesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
ListAttachedIndicesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The indices attached to the specified object.</p>
*/
inline const Aws::Vector<IndexAttachment>& GetIndexAttachments() const{ return m_indexAttachments; }
/**
* <p>The indices attached to the specified object.</p>
*/
inline void SetIndexAttachments(const Aws::Vector<IndexAttachment>& value) { m_indexAttachments = value; }
/**
* <p>The indices attached to the specified object.</p>
*/
inline void SetIndexAttachments(Aws::Vector<IndexAttachment>&& value) { m_indexAttachments = std::move(value); }
/**
* <p>The indices attached to the specified object.</p>
*/
inline ListAttachedIndicesResult& WithIndexAttachments(const Aws::Vector<IndexAttachment>& value) { SetIndexAttachments(value); return *this;}
/**
* <p>The indices attached to the specified object.</p>
*/
inline ListAttachedIndicesResult& WithIndexAttachments(Aws::Vector<IndexAttachment>&& value) { SetIndexAttachments(std::move(value)); return *this;}
/**
* <p>The indices attached to the specified object.</p>
*/
inline ListAttachedIndicesResult& AddIndexAttachments(const IndexAttachment& value) { m_indexAttachments.push_back(value); return *this; }
/**
* <p>The indices attached to the specified object.</p>
*/
inline ListAttachedIndicesResult& AddIndexAttachments(IndexAttachment&& value) { m_indexAttachments.push_back(std::move(value)); return *this; }
/**
* <p>The pagination token.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>The pagination token.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }
/**
* <p>The pagination token.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }
/**
* <p>The pagination token.</p>
*/
inline void SetNextToken(const char* value) { m_nextToken.assign(value); }
/**
* <p>The pagination token.</p>
*/
inline ListAttachedIndicesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>The pagination token.</p>
*/
inline ListAttachedIndicesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p>The pagination token.</p>
*/
inline ListAttachedIndicesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::Vector<IndexAttachment> m_indexAttachments;
Aws::String m_nextToken;
};
} // namespace Model
} // namespace CloudDirectory
} // namespace Aws
| {'content_hash': 'bbc50008418fedd7aeb96e5973bc9ab3', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 152, 'avg_line_length': 30.32456140350877, 'alnum_prop': 0.6846977147816026, 'repo_name': 'aws/aws-sdk-cpp', 'id': '69182226d6780b2c661d4437847db01f9b7ede9e', 'size': '3576', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'aws-cpp-sdk-clouddirectory/include/aws/clouddirectory/model/ListAttachedIndicesResult.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '309797'}, {'name': 'C++', 'bytes': '476866144'}, {'name': 'CMake', 'bytes': '1245180'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '8056'}, {'name': 'Java', 'bytes': '413602'}, {'name': 'Python', 'bytes': '79245'}, {'name': 'Shell', 'bytes': '9246'}]} |
Project: 2D OpenGL graphics engine
| {'content_hash': '473c23a142d9c46b713873380c2524c3', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 34, 'avg_line_length': 35.0, 'alnum_prop': 0.8285714285714286, 'repo_name': 'SirPidgin/Engin', 'id': 'b704a85ac0412f1fa3f21e0b17730ae106de0e5e', 'size': '43', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2410491'}, {'name': 'C++', 'bytes': '2848727'}, {'name': 'CMake', 'bytes': '1517'}]} |
include(bde_include_guard)
bde_include_guard()
bde_register_struct_type(
BDE_PACKAGELIBS_PACKAGE_TYPE
INHERIT BDE_PACKAGE_TYPE
# The dependencies on other packages are used for manual detection of
# unfulfilled inter-package dependencies (due to CMake's object library) deficiencies.
# If the object library is used, the sources will contain a generator
# expression expanding to list of object files of the OBJ_TARGET.
DEPENDS
# For the BDE style of building tests - i.e., build the package libraries first
# and then link tests with package libraries as opposed to package group library -
# an object library is created to avoid double-compiling the sources for package
# and package group libraries. In this case, the TARGET denotes the package library
# and contains the usage requirements of the package (i.e., INTERFACE part of the INTERFACE_TARGET),
# whereas the OBJ_TARGET denotes the object library and uses the build requirements
# of the package (i.e., PRIVATE part of the INTERFACE_TARGET). Note that the
# generator expressions (e.g., from the common interface target) are evaluated
# on the OBJ_TARGET in this case (see bde/bde repository for an example of use).
TARGET
OBJ_TARGET
# INTERFACE_TARGETS's INTERFACE linked to TARGET, and PRIVATE - to OBJ_TARGET
)
function(bde_package_create_target package)
bde_struct_get_field(packageTarget ${package} NAME)
bde_struct_get_field(headers ${package} HEADERS)
bde_struct_get_field(sources ${package} SOURCES)
bde_struct_get_field(packageInterface ${package} INTERFACE_TARGET)
bde_struct_get_field(depends ${package} DEPENDS)
if(sources)
# object library
set(packageObjTarget ${packageTarget}-obj)
add_library(
${packageObjTarget}
OBJECT EXCLUDE_FROM_ALL
${sources} ${headers}
)
set(packageObjects $<TARGET_OBJECTS:${packageObjTarget}>)
bde_struct_set_field(${package} SOURCES ${packageObjects})
bde_struct_set_field(${package} OBJ_TARGET ${packageObjTarget})
# CMake as of 3.10 does not allow calling target_link_libraries
# on OBJECT libraries. This command, however successfully imports
# the build requirements, such as compiler options and include
# directories
bde_interface_target_name(
privatePackageRequirements ${packageInterface} PRIVATE
)
set_target_properties(
${packageObjTarget}
PROPERTIES
LINK_LIBRARIES
"${depends};${privatePackageRequirements}"
)
# target for tests
add_library(${packageTarget} EXCLUDE_FROM_ALL ${packageObjects})
else()
# Add IDE target (https://gitlab.kitware.com/cmake/cmake/issues/15234)
add_custom_target(${packageTarget}-headers SOURCES ${headers})
# target for tests
add_library(${packageTarget} INTERFACE)
endif()
# Set up usage requirements for the package target
bde_interface_target_name(
interfacePackageRequirements ${packageInterface} INTERFACE
)
target_link_libraries(
${packageTarget} INTERFACE ${depends} ${interfacePackageRequirements}
)
bde_struct_set_field(${package} TARGET ${packageTarget})
bde_link_target_to_tests(${package})
foreach(field HEADERS SOURCES DEPENDS)
bde_struct_mark_field_const(${package} ${field})
endforeach()
endfunction() | {'content_hash': '2291716a5df0eeafa5cbefd4bafd8933', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 108, 'avg_line_length': 42.2, 'alnum_prop': 0.6724282129913577, 'repo_name': 'bloomberg/bde-tools', 'id': '7f51907b52f9a8d4e7f4e3e6ec862b7e5a32d2d0', 'size': '3587', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'cmake/bde_package_libraries.cmake', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '1280'}, {'name': 'C++', 'bytes': '8163'}, {'name': 'CMake', 'bytes': '320782'}, {'name': 'Emacs Lisp', 'bytes': '8245'}, {'name': 'Makefile', 'bytes': '288'}, {'name': 'Perl', 'bytes': '614447'}, {'name': 'Python', 'bytes': '284097'}, {'name': 'Shell', 'bytes': '27318'}]} |
package org.elasticsearch.indices.store;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.ImmutableShardRouting;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.Matchers.is;
/**
*/
public class IndicesStoreTests extends ElasticsearchTestCase {
private final static ShardRoutingState[] NOT_STARTED_STATES;
static {
Set<ShardRoutingState> set = new HashSet<>();
set.addAll(Arrays.asList(ShardRoutingState.values()));
set.remove(ShardRoutingState.STARTED);
NOT_STARTED_STATES = set.toArray(new ShardRoutingState[set.size()]);
}
private IndicesStore indicesStore;
private DiscoveryNode localNode;
@Before
public void before() {
localNode = new DiscoveryNode("abc", new LocalTransportAddress("abc"), Version.CURRENT);
indicesStore = new IndicesStore();
}
@Test
public void testShardCanBeDeleted_noShardRouting() throws Exception {
int numShards = randomIntBetween(1, 7);
int numReplicas = randomInt(2);
ClusterState.Builder clusterState = ClusterState.builder(new ClusterName("test"));
clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas)));
IndexShardRoutingTable.Builder routingTable = new IndexShardRoutingTable.Builder(new ShardId("test", 1), false);
assertFalse(indicesStore.shardCanBeDeleted(clusterState.build(), routingTable.build()));
}
@Test
public void testShardCanBeDeleted_noShardStarted() throws Exception {
int numShards = randomIntBetween(1, 7);
int numReplicas = randomInt(2);
ClusterState.Builder clusterState = ClusterState.builder(new ClusterName("test"));
clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas)));
IndexShardRoutingTable.Builder routingTable = new IndexShardRoutingTable.Builder(new ShardId("test", 1), false);
for (int i = 0; i < numShards; i++) {
int unStartedShard = randomInt(numReplicas);
for (int j=0; j <= numReplicas; j++) {
ShardRoutingState state;
if (j == unStartedShard) {
state = randomFrom(NOT_STARTED_STATES);
} else {
state = randomFrom(ShardRoutingState.values());
}
routingTable.addShard(new ImmutableShardRouting("test", i, "xyz", null, j == 0, state, 0));
}
}
assertFalse(indicesStore.shardCanBeDeleted(clusterState.build(), routingTable.build()));
}
@Test
public void testShardCanBeDeleted_shardExistsLocally() throws Exception {
int numShards = randomIntBetween(1, 7);
int numReplicas = randomInt(2);
ClusterState.Builder clusterState = ClusterState.builder(new ClusterName("test"));
clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas)));
clusterState.nodes(DiscoveryNodes.builder().localNodeId(localNode.id()).put(localNode).put(new DiscoveryNode("xyz", new LocalTransportAddress("xyz"), Version.CURRENT)));
IndexShardRoutingTable.Builder routingTable = new IndexShardRoutingTable.Builder(new ShardId("test", 1), false);
int localShardId = randomInt(numShards - 1);
for (int i = 0; i < numShards; i++) {
String nodeId = i == localShardId ? localNode.getId() : randomBoolean() ? "abc" : "xyz";
String relocationNodeId = randomBoolean() ? null : randomBoolean() ? localNode.getId() : "xyz";
routingTable.addShard(new ImmutableShardRouting("test", i, nodeId, relocationNodeId, true, ShardRoutingState.STARTED, 0));
for (int j = 0; j < numReplicas; j++) {
routingTable.addShard(new ImmutableShardRouting("test", i, nodeId, relocationNodeId, false, ShardRoutingState.STARTED, 0));
}
}
// Shard exists locally, can't delete shard
assertFalse(indicesStore.shardCanBeDeleted(clusterState.build(), routingTable.build()));
}
@Test
public void testShardCanBeDeleted_nodeNotInList() throws Exception {
int numShards = randomIntBetween(1, 7);
int numReplicas = randomInt(2);
ClusterState.Builder clusterState = ClusterState.builder(new ClusterName("test"));
clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas)));
clusterState.nodes(DiscoveryNodes.builder().localNodeId(localNode.id()).put(localNode));
IndexShardRoutingTable.Builder routingTable = new IndexShardRoutingTable.Builder(new ShardId("test", 1), false);
for (int i = 0; i < numShards; i++) {
String relocatingNodeId = randomBoolean() ? null : "def";
routingTable.addShard(new ImmutableShardRouting("test", i, "xyz", relocatingNodeId, true, ShardRoutingState.STARTED, 0));
for (int j = 0; j < numReplicas; j++) {
routingTable.addShard(new ImmutableShardRouting("test", i, "xyz", relocatingNodeId, false, ShardRoutingState.STARTED, 0));
}
}
// null node -> false
assertFalse(indicesStore.shardCanBeDeleted(clusterState.build(), routingTable.build()));
}
@Test
public void testShardCanBeDeleted_nodeVersion() throws Exception {
int numShards = randomIntBetween(1, 7);
int numReplicas = randomInt(2);
// Most of the times don't test bwc and use current version
final Version nodeVersion = randomBoolean() ? Version.CURRENT : randomVersion();
ClusterState.Builder clusterState = ClusterState.builder(new ClusterName("test"));
clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas)));
clusterState.nodes(DiscoveryNodes.builder().localNodeId(localNode.id()).put(localNode).put(new DiscoveryNode("xyz", new LocalTransportAddress("xyz"), nodeVersion)));
IndexShardRoutingTable.Builder routingTable = new IndexShardRoutingTable.Builder(new ShardId("test", 1), false);
for (int i = 0; i < numShards; i++) {
routingTable.addShard(new ImmutableShardRouting("test", i, "xyz", null, true, ShardRoutingState.STARTED, 0));
for (int j = 0; j < numReplicas; j++) {
routingTable.addShard(new ImmutableShardRouting("test", i, "xyz", null, false, ShardRoutingState.STARTED, 0));
}
}
// shard exist on other node (abc)
assertTrue(indicesStore.shardCanBeDeleted(clusterState.build(), routingTable.build()));
}
@Test
public void testShardCanBeDeleted_relocatingNode() throws Exception {
int numShards = randomIntBetween(1, 7);
int numReplicas = randomInt(2);
ClusterState.Builder clusterState = ClusterState.builder(new ClusterName("test"));
clusterState.metaData(MetaData.builder().put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(numShards).numberOfReplicas(numReplicas)));
final Version nodeVersion = randomBoolean() ? Version.CURRENT : randomVersion();
clusterState.nodes(DiscoveryNodes.builder().localNodeId(localNode.id())
.put(localNode)
.put(new DiscoveryNode("xyz", new LocalTransportAddress("xyz"), Version.CURRENT))
.put(new DiscoveryNode("def", new LocalTransportAddress("def"), nodeVersion) // <-- only set relocating, since we're testing that in this test
));
IndexShardRoutingTable.Builder routingTable = new IndexShardRoutingTable.Builder(new ShardId("test", 1), false);
for (int i = 0; i < numShards; i++) {
routingTable.addShard(new ImmutableShardRouting("test", i, "xyz", "def", true, ShardRoutingState.STARTED, 0));
for (int j = 0; j < numReplicas; j++) {
routingTable.addShard(new ImmutableShardRouting("test", i, "xyz", "def", false, ShardRoutingState.STARTED, 0));
}
}
// shard exist on other node (abc and def)
assertTrue(indicesStore.shardCanBeDeleted(clusterState.build(), routingTable.build()));
}
}
| {'content_hash': '22a7b15de143979112c73432cd4d62ac', 'timestamp': '', 'source': 'github', 'line_count': 177, 'max_line_length': 177, 'avg_line_length': 52.22598870056497, 'alnum_prop': 0.6923409779316313, 'repo_name': 'anti-social/elasticsearch', 'id': '0949033df1a865ac099707cdd760d998fcc1287b', 'size': '10032', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '451'}, {'name': 'HTML', 'bytes': '1212'}, {'name': 'Java', 'bytes': '26547935'}, {'name': 'Perl', 'bytes': '6949'}, {'name': 'Python', 'bytes': '67989'}, {'name': 'Ruby', 'bytes': '17776'}, {'name': 'Shell', 'bytes': '35283'}]} |
.. Lancet documentation master file, created by
sphinx-quickstart on Fri Dec 6 11:24:15 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
.. Differences to Topographica's conf.py
sys.path.insert(0, os.path.abspath('../external/param/'))
html_title = 'The Topographica Neural Map Simulator'
html_logo = 'images/topo-banner7.png'
html_static_path = ['_static','Reference_Manual']
html_domain_indices = True
|
|
.. figure:: _static/main_logo.png
:align: center
**Launch jobs, organize the output, and dissect the results.**
Introduction
____________
Lancet is designed to help you organize the output of your research
tools, store it, and dissect the data you have collected. The output
of a single simulation run or analysis rarely contains all the data
you need; Lancet helps you generate data from many runs and analyse it
using your own Python code.
Parameter spaces often need to be explored for the purpose of
plotting, tuning, or analysis. Lancet helps you extract the
information you care about from potentially enormous volumes of data
generated by such parameter exploration.
Features
________
Lancet is pure, platform-independent Python with minimal dependencies,
and supports both Python 2 and Python 3. It is designed to be
extremely flexible and lightweight, allowing researchers to use only
the components they need without having to understand the whole design
or all the component available.
* A simple, useful core with advanced functionality strictly
optional. Use what you need without learning all components.
* All components use a declarative style, helping to ensure
reproduciblity.
* Succinctly express the high dimensional parameter spaces, without
nested loops.
* Easily interface with external tools using ``ShellCommand`` or
quickly build a flexible, reusable interfaces to advanced simulators
or analysis tools. Currently, the Topographica neural simulator is
actively supported.
* Seamlessly switch from running jobs locally to launching jobs on a
compute cluster.
* Keep your output organized together with key metadata for
reproducibility.
* Quickly load your data and view the parameters from previous runs.
* Integrates well with other popular tools such as `IPython Notebook
<http://ipython.org/notebook>`_ and the `pandas
<http://pandas.pydata.org>`_ data analysis library.
* Actively used in scientific research and publication.
Quickstart Example
__________________
The following example demonstrates how Lancet can be used to specify,
launch and collate jobs (requires a factor command for factorizing
integers in the style of the command in `GNU coreutils
<http://www.gnu.org/software/coreutils/manual/coreutils.html>`_): ::
>>> import lancet
>>> example_name = 'prime_quintuplet'
>>> integers = lancet.Range('integer', 100, 115, steps=16, fp_precision=0)
>>> factor_cmd = lancet.ShellCommand(executable='factor', posargs=['integer'])
# Runs locally. A QLauncher could be used to launch jobs with Grid Engine.
>>> lancet.Launcher(example_name, integers, factor_cmd, output_directory='output')()
# Collate and print the the primes in the input range of integers
>>> def load_factors(filename):
... "Return output of 'factor' command as dictionary of factors."
... with open(filename, 'r') as f:
... factor_list = f.read().replace(':', '').split()
... return dict(enumerate(int(el) for el in factor_list))
>>> output_files = lancet.FilePattern('filename', './output/*-prime*/streams/*.o*')
>>> output_factors = lancet.FileInfo(output_files, 'filename',
... lancet.CustomFile(metadata_fn=load_factors))
>>> primes = sorted(factors[0] for factors in output_factors.specs
if factors[0]==factors[1]) # i.e. if the input integer is the 1st factor
>>> primes # A prime quintuplet, the closest admissable constellation of 5 primes.
[101, 103, 107, 109, 113]
Installation
____________
A PyPI package will be made available shortly. The development version
can be obtained from Lancet's `repository on GitHub
<https://github.com/ioam/lancet>`_ using::
git clone git://github.com/ioam/lancet.git
Lancet uses the lightweight `param <https://github.com/ioam/param>`_
package. It may be installed using::
pip install param
Documentation
_____________
Lancet's code is well documented and the Python code may also be
inspected and read directly as the majority of modules, classes and
methods contain extensive docstrings. You can start with the above
example, and then study the first paper below to see how Lancet can be
integrated in a real research workflow.
Papers published using Lancet
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Paper describing `reproducible workflows using Lancet and IPython Notebook <http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3874632/>`_: ::
@article{Stevens2013,
author = {Jean-Luc Stevens and Marco Elver and James A. Bednar},
title = {{An automated and reproducible workflow for running and analysing
neural simulations using Lancet and IPython Notebook}},
journal = {{Frontiers in Neuroinformatics}},
year = {2013},
volume = {7},
pages = {44},
url = {http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3874632/}
}
All the code, notebooks and other assets used in the following paper along with
information on how to reproduce this paper may be found `here <https://github.com/ioam/topographica/tree/master/models/stevens.jn13>`_.
Lancet was exclusively used to launch and analyse simulations results: ::
@article{Stevens2013,
author = {Stevens, Jean-Luc R. and Law, Judith S. and
Antol\'{i}k, J\'{a}n and Bednar, James A.},
title = {Mechanisms for Stable, Robust, and Adaptive
Development of Orientation Maps in the Primary Visual Cortex},
journal = {The Journal of Neuroscience},
volume = {33},
number = {40},
pages = {15747-15766},
year = {2013},
doi = {10.1523/JNEUROSCI.1037-13.2013},
url = {http://www.jneurosci.org/content/33/40/15747.full}
}
The following paper used Lancet to collect the results of thousands of microprocessor simulations::
@inproceedings{ElverN2014,
author = {Marco Elver and Vijay Nagarajan},
title = {{TSO-CC: Consistency directed cache coherence for TSO}},
booktitle = {HPCA},
year = {2014},
pages = {165-176},
website = {http://homepages.inf.ed.ac.uk/s0787712/research/tsocc}
}
Contributors
~~~~~~~~~~~~
The following people have contributed to Lancet's design and
implementation:
Jean-Luc Stevens: Original coding and design
`Marco Elver <https://github.com/melver/lancet>`_ : Python 3 fork,
cleaned up many aspects of the design.
James A. Bednar: For supporting the development of a solution that
works with any tool and not just `Topographica
<http://www.topographica.org>`_ .
Philipp Rudiger: Testing, feedback and suggestions.
And now for something completely different...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
.. figure:: _static/pythons.svg
:align: center
:scale: 100 %
.. Contents:
.. toctree::
:maxdepth: 2
.. Indices and tables
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| {'content_hash': '0f0223f87e3e9a7d2638b4c4e4c35d64', 'timestamp': '', 'source': 'github', 'line_count': 207, 'max_line_length': 136, 'avg_line_length': 35.88405797101449, 'alnum_prop': 0.7003231017770598, 'repo_name': 'melver/lancet', 'id': 'a76613cc31ad7a7ed5c0fa1b45229e7367848d08', 'size': '7428', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'doc/index.rst', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '124648'}]} |
/*!
* Module dependencies.
*/
var _ = require('underscore'),
keystone = require('../../../'),
querystring = require('querystring'),
https = require('https'),
util = require('util'),
utils = require('keystone-utils'),
super_ = require('../Type');
var RADIUS_KM = 6371,
RADIUS_MILES = 3959;
/**
* Location FieldType Constructor
* @extends Field
* @api public
*/
function location(list, path, options) {
this._underscoreMethods = ['format', 'googleLookup', 'kmFrom', 'milesFrom'];
this._fixedSize = 'full';
this.enableMapsAPI = keystone.get('google api key') ? true : false;
this._properties = ['enableMapsAPI'];
if (!options.defaults) {
options.defaults = {};
}
if (options.required) {
if (Array.isArray(options.required)) {
// required can be specified as an array of paths
this.requiredPaths = options.required;
} else if ('string' === typeof options.required) {
// or it can be specified as a comma-delimited list
this.requiredPaths = options.required.replace(/,/g, ' ').split(/\s+/);
}
// options.required should always be simplified to a boolean
options.required = true;
}
// default this.requiredPaths
if (!this.requiredPaths) {
this.requiredPaths = ['street1', 'suburb'];
}
location.super_.call(this, list, path, options);
}
/*!
* Inherit from Field
*/
util.inherits(location, super_);
/**
* Registers the field on the List's Mongoose Schema.
*
* @api public
*/
location.prototype.addToSchema = function() {
var field = this,
schema = this.list.schema,
options = this.options;
var paths = this.paths = {
number: this._path.append('.number'),
name: this._path.append('.name'),
street1: this._path.append('.street1'),
street2: this._path.append('.street2'),
suburb: this._path.append('.suburb'),
state: this._path.append('.state'),
postcode: this._path.append('.postcode'),
country: this._path.append('.country'),
geo: this._path.append('.geo'),
geo_lat: this._path.append('.geo_lat'),
geo_lng: this._path.append('.geo_lng'),
serialised: this._path.append('.serialised'),
improve: this._path.append('_improve'),
overwrite: this._path.append('_improve_overwrite')
};
var getFieldDef = function(type, key) {
var def = { type: type };
if (options.defaults[key]) {
def.default = options.defaults[key];
}
return def;
};
schema.nested[this.path] = true;
schema.add({
number: getFieldDef(String, 'number'),
name: getFieldDef(String, 'name'),
street1: getFieldDef(String, 'street1'),
street2: getFieldDef(String, 'street2'),
street3: getFieldDef(String, 'street3'),
suburb: getFieldDef(String, 'suburb'),
state: getFieldDef(String, 'state'),
postcode: getFieldDef(String, 'postcode'),
country: getFieldDef(String, 'country'),
geo: { type: [Number], index: '2dsphere' }
}, this.path + '.');
schema.virtual(paths.serialised).get(function() {
return _.compact([
this.get(paths.number),
this.get(paths.name),
this.get(paths.street1),
this.get(paths.street2),
this.get(paths.suburb),
this.get(paths.state),
this.get(paths.postcode),
this.get(paths.country)
]).join(', ');
});
// pre-save hook to fix blank geo fields
// see http://stackoverflow.com/questions/16388836/does-applying-a-2dsphere-index-on-a-mongoose-schema-force-the-location-field-to
schema.pre('save', function(next) {
var obj = field._path.get(this);
if (Array.isArray(obj.geo) && (obj.geo.length !== 2 || (obj.geo[0] === null && obj.geo[1] === null))) {
obj.geo = undefined;
}
next();
});
this.bindUnderscoreMethods();
};
/**
* Formats a list of the values stored by the field. Only paths that
* have values will be included.
*
* Optionally provide a space-separated list of values to include.
*
* Delimiter defaults to `', '`.
*
* @api public
*/
location.prototype.format = function(item, values, delimiter) {
if (!values) {
return item.get(this.paths.serialised);
}
var paths = this.paths;
values = values.split(' ').map(function(i) {
return item.get(paths[i]);
});
return _.compact(values).join(delimiter || ', ');
};
/**
* Detects whether the field has been modified
*
* @api public
*/
location.prototype.isModified = function(item) {
return item.isModified(this.paths.number) ||
item.isModified(this.paths.name) ||
item.isModified(this.paths.street1) ||
item.isModified(this.paths.street2) ||
item.isModified(this.paths.suburb) ||
item.isModified(this.paths.state) ||
item.isModified(this.paths.postcode) ||
item.isModified(this.paths.country) ||
item.isModified(this.paths.geo);
};
/**
* Validates that a value for this field has been provided in a data object
*
* options.required specifies an array or space-delimited list of paths that
* are required (defaults to street1, suburb)
*
* @api public
*/
location.prototype.validateInput = function(data, required, item) {
if (!required) {
return true;
}
var paths = this.paths,
nested = this._path.get(data),
values = nested || data,
valid = true;
this.requiredPaths.forEach(function(path) {
if (nested) {
if (!(path in values) && item && item.get(paths[path])) {
return;
}
if (!values[path]) {
valid = false;
}
} else {
if (!(paths[path] in values) && item && item.get(paths[path])) {
return;
}
if (!values[paths[path]]) {
valid = false;
}
}
});
return valid;
};
/**
* Updates the value for this field in the item from a data object
*
* @api public
*/
location.prototype.updateItem = function(item, data) {
var paths = this.paths,
fieldKeys = ['number', 'name', 'street1', 'street2', 'suburb', 'state', 'postcode', 'country'],
geoKeys = ['geo', 'geo_lat', 'geo_lng'],
valueKeys = fieldKeys.concat(geoKeys),
valuePaths = valueKeys,
values = this._path.get(data);
if (!values) {
// Handle flattened values
valuePaths = valueKeys.map(function(i) {
return paths[i];
});
values = _.pick(data, valuePaths);
}
// convert valuePaths to a map for easier usage
valuePaths = _.object(valueKeys, valuePaths);
var setValue = function(key) {
if (valuePaths[key] in values && values[valuePaths[key]] !== item.get(paths[key])) {
item.set(paths[key], values[valuePaths[key]] || null);
}
};
_.each(fieldKeys, setValue);
if (valuePaths.geo in values) {
var oldGeo = item.get(paths.geo) || [],
newGeo = values[valuePaths.geo];
if (!Array.isArray(newGeo) || newGeo.length !== 2) {
newGeo = [];
}
if (newGeo[0] !== oldGeo[0] || newGeo[1] !== oldGeo[1]) {
item.set(paths.geo, newGeo);
}
} else if (valuePaths.geo_lat in values && valuePaths.geo_lng in values) {
var lat = utils.number(values[valuePaths.geo_lat]),
lng = utils.number(values[valuePaths.geo_lng]);
item.set(paths.geo, (lat && lng) ? [lng, lat] : undefined);
}
};
/**
* Returns a callback that handles a standard form submission for the field
*
* Handles:
* - `field.paths.improve` in `req.body` - improves data via `.googleLookup()`
* - `field.paths.overwrite` in `req.body` - in conjunction with `improve`, overwrites existing data
*
* @api public
*/
location.prototype.getRequestHandler = function(item, req, paths, callback) {
var field = this;
if (utils.isFunction(paths)) {
callback = paths;
paths = field.paths;
} else if (!paths) {
paths = field.paths;
}
callback = callback || function() {};
return function() {
var update = req.body[paths.overwrite] ? 'overwrite' : true;
if (req.body && req.body[paths.improve]) {
field.googleLookup(item, false, update, function() {
callback();
});
} else {
callback();
}
};
};
/**
* Immediately handles a standard form submission for the field (see `getRequestHandler()`)
*
* @api public
*/
location.prototype.handleRequest = function(item, req, paths, callback) {
this.getRequestHandler(item, req, paths, callback)();
};
/**
* Internal Google geocode request method
*
* @api private
*/
function doGoogleGeocodeRequest(address, region, callback) {
// https://developers.google.com/maps/documentation/geocoding/
// Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day, except with an enterprise license.
// Note: the Geocoding API may only be used in conjunction with a Google map; geocoding results without displaying them on a map is prohibited.
// Please make sure your Keystone app complies with the Google Maps API License.
var options = {
sensor: false,
language: 'en',
address: address
};
if (arguments.length === 2 && _.isFunction(region)) {
callback = region;
region = null;
}
if (region) {
options.region = region;
}
var endpoint = 'https://maps.googleapis.com/maps/api/geocode/json?' + querystring.stringify(options);
https.get(endpoint, function(res) {
var data = [];
res.on('data', function(chunk) {
data.push(chunk);
})
.on('end', function() {
var dataBuff = data.join('').trim();
var result;
try {
result = JSON.parse(dataBuff);
}
catch (exp) {
result = {'status_code': 500, 'status_text': 'JSON Parse Failed', 'status': 'UNKNOWN_ERROR'};
}
callback(null, result);
});
})
.on('error', function(err) {
callback(err);
});
}
/**
* Autodetect the full address and lat, lng from the stored value.
*
* Uses Google's Maps API and may only be used in conjunction with a Google map.
* Geocoding results without displaying them on a map is prohibited.
* Please make sure your Keystone app complies with the Google Maps API License.
*
* Internal status codes mimic the Google API status codes.
*
* @api private
*/
location.prototype.googleLookup = function(item, region, update, callback) {
if (_.isFunction(update)) {
callback = update;
update = false;
}
var field = this,
stored = item.get(this.path),
address = item.get(this.paths.serialised);
if (address.length === 0) {
return callback({'status_code': 500, 'status_text': 'No address to geocode', 'status': 'NO_ADDRESS'});
}
doGoogleGeocodeRequest(address, region || keystone.get('default region'), function(err, geocode){
if (err || geocode.status !== 'OK') {
return callback(err || new Error(geocode.status + ': ' + geocode.error_message));
}
// use the first result
// if there were no results in the array, status would be ZERO_RESULTS
var result = geocode.results[0];
// parse the address components into a location object
var location = {};
_.each(result.address_components, function(val){
if ( _.indexOf(val.types, 'street_number') >= 0 ) {
location.street1 = location.street1 || [];
location.street1.push(val.long_name);
}
if ( _.indexOf(val.types, 'route') >= 0 ) {
location.street1 = location.street1 || [];
location.street1.push(val.short_name);
}
// in some cases, you get suburb, city as locality - so only use the first
if ( _.indexOf(val.types, 'locality') >= 0 && !location.suburb) {
location.suburb = val.long_name;
}
if ( _.indexOf(val.types, 'administrative_area_level_1') >= 0 ) {
location.state = val.short_name;
}
if ( _.indexOf(val.types, 'country') >= 0 ) {
location.country = val.long_name;
}
if ( _.indexOf(val.types, 'postal_code') >= 0 ) {
location.postcode = val.short_name;
}
});
if (Array.isArray(location.street1)) {
location.street1 = location.street1.join(' ');
}
location.geo = [
result.geometry.location.lng,
result.geometry.location.lat
];
//console.log('------ Google Geocode Results ------');
//console.log(address);
//console.log(result);
//console.log(location);
if (update === 'overwrite') {
item.set(field.path, location);
} else if (update) {
_.each(location, function(value, key) {
if (key === 'geo') {
return;
}
if (!stored[key]) {
item.set(field.paths[key], value);
}
});
if (!Array.isArray(stored.geo) || !stored.geo[0] || !stored.geo[1]) {
item.set(field.paths.geo, location.geo);
}
}
callback(null, location, result);
});
};
/**
* Internal Distance calculation function
*
* See http://en.wikipedia.org/wiki/Haversine_formula
*
* @api private
*/
function calculateDistance(point1, point2) {
var dLng = (point2[0] - point1[0]) * Math.PI / 180;
var dLat = (point2[1] - point1[1]) * Math.PI / 180;
var lat1 = (point1[1]) * Math.PI / 180;
var lat2 = (point2[1]) * Math.PI / 180;
/* eslint-disable space-infix-ops */
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLng/2) * Math.sin(dLng/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
/* eslint-enable space-infix-ops */
return c;
}
/**
* Returns the distance from a [lat, lng] point in kilometres
*
* @api public
*/
location.prototype.kmFrom = function(item, point) {
return calculateDistance(this.get(this.paths.geo), point) * RADIUS_KM;
};
/**
* Returns the distance from a [lat, lng] point in miles
*
* @api public
*/
location.prototype.milesFrom = function(item, point) {
return calculateDistance(this.get(this.paths.geo), point) * RADIUS_MILES;
};
/*!
* Export class
*/
exports = module.exports = location;
| {'content_hash': '9382fffcf39b042f0ac9fa3f0e57130e', 'timestamp': '', 'source': 'github', 'line_count': 547, 'max_line_length': 144, 'avg_line_length': 24.111517367458866, 'alnum_prop': 0.6496322693153386, 'repo_name': 'trystant/keystone', 'id': 'cc5608b81b6cd21234b85f9cc42366e334dd0abc', 'size': '13189', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'fields/types/location/LocationType.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '292257'}, {'name': 'HTML', 'bytes': '52048'}, {'name': 'JavaScript', 'bytes': '2154446'}, {'name': 'Makefile', 'bytes': '116'}]} |
package com.siyeh.ig.junit;
import com.intellij.psi.PsiMethodCallExpression;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.testFrameworks.AssertHint;
import org.jetbrains.annotations.NotNull;
public class AssertEqualsBetweenInconvertibleTypesInspection extends BaseInspection {
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("assertequals.between.inconvertible.types.display.name");
}
@Override
@NotNull
public String buildErrorString(Object... infos) {
return (String)infos[0];
}
@Override
public boolean isEnabledByDefault() {
return true;
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new AssertEqualsBetweenInconvertibleTypesVisitor();
}
private static class AssertEqualsBetweenInconvertibleTypesVisitor extends BaseInspectionVisitor {
@Override
public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
super.visitMethodCallExpression(expression);
final String compatibilityErrorMessage = AssertHint.areExpectedActualTypesCompatible(expression, false);
if (compatibilityErrorMessage != null) {
registerMethodCallError(expression, compatibilityErrorMessage);
}
}
}
}
| {'content_hash': 'f32e6f44b7b42ed133d83311199d51f8', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 110, 'avg_line_length': 29.5, 'alnum_prop': 0.7848194546794399, 'repo_name': 'semonte/intellij-community', 'id': '869140f04f5979aee9c1376c1970c58d9f94b418', 'size': '1956', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/AssertEqualsBetweenInconvertibleTypesInspection.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '60580'}, {'name': 'C', 'bytes': '211556'}, {'name': 'C#', 'bytes': '1264'}, {'name': 'C++', 'bytes': '197528'}, {'name': 'CMake', 'bytes': '1675'}, {'name': 'CSS', 'bytes': '201445'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '3222009'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1895767'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '164918191'}, {'name': 'JavaScript', 'bytes': '570364'}, {'name': 'Jupyter Notebook', 'bytes': '93222'}, {'name': 'Kotlin', 'bytes': '4472431'}, {'name': 'Lex', 'bytes': '147154'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '51270'}, {'name': 'Objective-C', 'bytes': '27941'}, {'name': 'Perl', 'bytes': '903'}, {'name': 'Perl6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6680'}, {'name': 'Python', 'bytes': '25421481'}, {'name': 'Roff', 'bytes': '37534'}, {'name': 'Ruby', 'bytes': '1217'}, {'name': 'Scala', 'bytes': '11698'}, {'name': 'Shell', 'bytes': '65719'}, {'name': 'Smalltalk', 'bytes': '338'}, {'name': 'TeX', 'bytes': '25473'}, {'name': 'Thrift', 'bytes': '1846'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'Visual Basic', 'bytes': '77'}, {'name': 'XSLT', 'bytes': '113040'}]} |
Aria.classDefinition({
$classpath : "test.aria.widgets.environment.WidgetSettingsTestCase",
$extends : "aria.jsunit.TestCase",
$dependencies : ["aria.widgets.environment.WidgetSettings"],
$prototype : {
testGetSetWidgetSettings : function () {
aria.core.AppEnvironment.setEnvironment({
widgetSettings : {
directOnBlurValidation : false,
autoselect : true
}
});
var settings = aria.widgets.environment.WidgetSettings.getWidgetSettings();
this.assertTrue(settings.autoselect);
this.assertFalse(settings.directOnBlurValidation);
aria.core.AppEnvironment.setEnvironment({});
settings = aria.widgets.environment.WidgetSettings.getWidgetSettings();
this.assertFalse(settings.autoselect);
this.assertTrue(settings.directOnBlurValidation);
},
testGetSetDialogWidgetSettings : function () {
var settings = aria.widgets.environment.WidgetSettings.getWidgetSettings().dialog;
this.assertTrue(settings.movable === false);
this.assertFalse("movableProxy" in settings);
aria.core.AppEnvironment.setEnvironment({
widgetSettings : {
dialog : {
movable : true
}
}
});
settings = aria.widgets.environment.WidgetSettings.getWidgetSettings().dialog;
this.assertTrue(settings.movable === true);
this.assertFalse("movableProxy" in settings);
aria.core.AppEnvironment.setEnvironment({
widgetSettings : {
dialog : {
movableProxy : {
type : "Overlay"
}
}
}
});
settings = aria.widgets.environment.WidgetSettings.getWidgetSettings().dialog;
this.assertTrue(settings.movable === false);
this.assertTrue(settings.movableProxy.type == "Overlay");
aria.core.AppEnvironment.setEnvironment({
widgetSettings : {
dialog : {
movable : true,
movableProxy : {
type : "CloneOverlay",
cfg : {
opacity : 0.8
}
}
}
}
});
settings = aria.widgets.environment.WidgetSettings.getWidgetSettings().dialog;
this.assertTrue(settings.movable === true);
this.assertJsonEquals(settings.movableProxy, {
type : "CloneOverlay",
cfg : {
opacity : 0.8
}
});
}
}
});
| {'content_hash': '3e0ed925d6f2253fc840e532f2c2de69', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 94, 'avg_line_length': 36.01219512195122, 'alnum_prop': 0.500846596681341, 'repo_name': 'ymeine/ariatemplates', 'id': '249526c5055f0071bf9a39cade77087859c19b4e', 'size': '3546', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'test/aria/widgets/environment/WidgetSettingsTestCase.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '216069'}, {'name': 'HTML', 'bytes': '25071'}, {'name': 'JavaScript', 'bytes': '10491832'}, {'name': 'Shell', 'bytes': '2112'}, {'name': 'Smarty', 'bytes': '1093700'}]} |
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Screens.OnlinePlay.Lounge.Components;
using osu.Game.Users;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneRankRangePill : MultiplayerTestScene
{
[SetUp]
public new void Setup() => Schedule(() =>
{
Child = new RankRangePill
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre
};
});
[Test]
public void TestSingleUser()
{
AddStep("add user", () =>
{
Client.AddUser(new User
{
Id = 2,
Statistics = { GlobalRank = 1234 }
});
// Remove the local user so only the one above is displayed.
Client.RemoveUser(API.LocalUser.Value);
});
}
[Test]
public void TestMultipleUsers()
{
AddStep("add users", () =>
{
Client.AddUser(new User
{
Id = 2,
Statistics = { GlobalRank = 1234 }
});
Client.AddUser(new User
{
Id = 3,
Statistics = { GlobalRank = 3333 }
});
Client.AddUser(new User
{
Id = 4,
Statistics = { GlobalRank = 4321 }
});
// Remove the local user so only the ones above are displayed.
Client.RemoveUser(API.LocalUser.Value);
});
}
[TestCase(1, 10)]
[TestCase(10, 100)]
[TestCase(100, 1000)]
[TestCase(1000, 10000)]
[TestCase(10000, 100000)]
[TestCase(100000, 1000000)]
[TestCase(1000000, 10000000)]
public void TestRange(int min, int max)
{
AddStep("add users", () =>
{
Client.AddUser(new User
{
Id = 2,
Statistics = { GlobalRank = min }
});
Client.AddUser(new User
{
Id = 3,
Statistics = { GlobalRank = max }
});
// Remove the local user so only the ones above are displayed.
Client.RemoveUser(API.LocalUser.Value);
});
}
}
}
| {'content_hash': 'c49f589fbc6c9f7ecc9cb7b213fb26e4', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 78, 'avg_line_length': 27.25, 'alnum_prop': 0.4224172317510969, 'repo_name': 'UselessToucan/osu', 'id': '9e03743e8d9b164c1f2d9b644dc46194fed428f5', 'size': '2657', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'osu.Game.Tests/Visual/Multiplayer/TestSceneRankRangePill.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '10533691'}, {'name': 'GLSL', 'bytes': '230'}, {'name': 'PowerShell', 'bytes': '457'}, {'name': 'Ruby', 'bytes': '4185'}, {'name': 'Shell', 'bytes': '247'}]} |
<?php
namespace Mcwork\Mapper;
use ContentinumComponents\Mapper\Worker;
/**
* Query contents for this request
*
* @author Michael Jochum, [email protected]
*/
class News extends Worker
{
/**
* Content query
* @param array $params query conditions
* @return multitype:
*/
public function fetchContent(array $params = null)
{
return $this->getStorage()->getRepository( $this->getEntityName() )->findBy(array('contentGroupName' => 'news'),array('publishDate' => 'DESC'));
}
} | {'content_hash': '40684ba77f7e609b28f9856bbe362ac9', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 152, 'avg_line_length': 24.608695652173914, 'alnum_prop': 0.6395759717314488, 'repo_name': 'Mikel1961/contentinum.5.1', 'id': 'a78de64be8865d20f8e1cc66036706defa82726b', 'size': '1847', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'module/Mcwork/src/Mcwork/Mapper/News.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '784'}, {'name': 'CSS', 'bytes': '130891'}, {'name': 'HTML', 'bytes': '335811'}, {'name': 'JavaScript', 'bytes': '359949'}, {'name': 'PHP', 'bytes': '16482984'}]} |
CKEDITOR.plugins.setLang( 'sourcedialog', 'en-gb', {
toolbar: 'Source',
title: 'Source'
} );
| {'content_hash': 'ea3a9e2fe9b7f23a21884cc7975b586d', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 52, 'avg_line_length': 16.166666666666668, 'alnum_prop': 0.6391752577319587, 'repo_name': 'torinfo/xerteonlinetoolkits', 'id': '0b369d6a98ffe813a672ff155acc1c05dedfa31c', 'size': '259', 'binary': False, 'copies': '4', 'ref': 'refs/heads/develop', 'path': 'editor/js/vendor/ckeditor/plugins/sourcedialog/lang/en-gb.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '543'}, {'name': 'CSS', 'bytes': '827526'}, {'name': 'HTML', 'bytes': '2080447'}, {'name': 'Hack', 'bytes': '7370'}, {'name': 'JavaScript', 'bytes': '8900597'}, {'name': 'Less', 'bytes': '178053'}, {'name': 'Makefile', 'bytes': '11959'}, {'name': 'PHP', 'bytes': '2596206'}, {'name': 'PostScript', 'bytes': '3228'}, {'name': 'Python', 'bytes': '1899'}, {'name': 'Roff', 'bytes': '7682'}, {'name': 'SCSS', 'bytes': '676600'}, {'name': 'Shell', 'bytes': '413'}]} |
use libc::{c_int, c_uint, uint8_t};
use rustc_serialize::hex::ToHex;
use std::error::Error;
use std::fmt;
use std::io;
#[repr(C)]
struct YK_KEY;
#[link(name="ykpers-1")]
extern {
fn yk_init() -> c_int;
fn yk_open_first_key() -> *const YK_KEY;
fn yk_close_key(yk: *const YK_KEY) -> c_int;
fn yk_get_serial(yk: *const YK_KEY, slot: uint8_t, flags: c_uint,
serial: *mut c_uint) -> c_int;
fn yk_challenge_response(yk: *const YK_KEY, yk_cmd: uint8_t, may_block: c_int,
challenge_len: c_uint, challenge: *const uint8_t,
response_len: c_uint, response: *mut u8) -> c_int;
}
/*****************************
* Safe interface to ykpers *
*****************************/
#[derive(Debug)]
pub enum YubikeyError { InvalidYubikeySlot,
NoYubikeyConnected,
EmptyCRChallenge,
OtherError(io::Error) }
impl Error for YubikeyError {
fn description(&self) -> &str {
match *self {
YubikeyError::InvalidYubikeySlot => "The selected Yubikey slot is invalid. Valid are 1, 2",
YubikeyError::NoYubikeyConnected => "No Yubikey connected",
YubikeyError::EmptyCRChallenge => "The specified challenge was empty",
YubikeyError::OtherError(ref e) => e.description()
}
}
}
impl fmt::Display for YubikeyError {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(self.description())
}
}
/// Internal function used to retrieve and wrap the last error from libykpers
fn last_yk_error() -> YubikeyError {
YubikeyError::OtherError(io::Error::last_os_error())
}
/// Opaque pointer to foreign Yubikey type. Under the hood this is just a handle
/// for a USB device.
pub struct Yubikey {
/// Foreign pointer to the USB handle
yk: *const YK_KEY
}
/* When a Yubikey goes out of scope, close the handle */
impl Drop for Yubikey {
fn drop(&mut self) {
unsafe { yk_close_key(self.yk) };
}
}
impl Yubikey {
/// Connects to the first available Yubikey
pub fn get_yubikey() -> Result<Yubikey, YubikeyError> {
unsafe { yk_init() };
let yk = unsafe { yk_open_first_key() };
if yk.is_null() { // Probably no Yubikey connected
Err(YubikeyError::NoYubikeyConnected)
} else {
Ok(Yubikey{ yk: yk })
}
}
/// Returns the serial number of the Yubikey
pub fn get_serial(&self) -> Result<u32, YubikeyError> {
unsafe {
let mut serial: c_uint = 0;
match yk_get_serial(self.yk, 0, 0, &mut serial) {
0 => Err(last_yk_error()),
_ => Ok(serial as u32)
}
}
}
/// Handles a HMAC-SHA1 challenge-response interaction with a Yubikey.
///
/// # Examples
///
/// ```
/// use yubikey::Yubikey;
///
/// let yk = try!(Yubikey::get_yubikey());
/// yk.challenge_response(&some_byte_slice, false)
/// ```
///
/// # Failures
///
/// This function can fail in several different ways at a lower level, in
/// which case the exact error is returned as a `YubikeyError`.
/// This could be unrecoverable errors such as unplugged Yubikeys.
pub fn challenge_response(&self, slot: u8, challenge: &[u8],
may_block: bool) -> Result<String, YubikeyError> {
// Yubikey commands are defined in ykdef.h
let yk_cmd = try!(match slot {
1 => Ok(0x30), //#define SLOT_CHAL_HMAC1 0x30
2 => Ok(0x38), //#define SLOT_CHAL_HMAC2 0x38
_ => Err(YubikeyError::InvalidYubikeySlot)
});
let challenge_len = challenge.len() as c_uint;
if challenge_len == 0 {
return Err(YubikeyError::EmptyCRChallenge);
}
let response_len = 64; // Length of HMAC-SHA1 response
let mut response = Vec::with_capacity(response_len as usize);
let rc = unsafe {
let cr_status =
yk_challenge_response(self.yk, yk_cmd, may_block as c_int,
challenge_len, challenge.as_ptr(),
response_len, response.as_mut_ptr());
response.set_len(response_len as usize);
cr_status
};
if rc == 0 {
Err(last_yk_error())
} else {
let mut response_str = (&mut response).to_hex();
response_str.truncate(40);
Ok(response_str)
}
}
}
| {'content_hash': '73cb3936821c9eececbce8a9582dcdae', 'timestamp': '', 'source': 'github', 'line_count': 144, 'max_line_length': 103, 'avg_line_length': 32.05555555555556, 'alnum_prop': 0.5487435008665511, 'repo_name': 'tazjin/yubikey-fde', 'id': '025d00f32d2db080fa05d3d95d26438c0d9105a0', 'size': '4616', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/yubikey.rs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Rust', 'bytes': '13487'}, {'name': 'Shell', 'bytes': '2427'}]} |
#include <string.h>
#include <math.h>
#ifdef __UNIX__
#include <assert.h>
#include <unistd.h>
#include <errno.h>
#endif
#include <ctype.h>
#include "ocrclass.h"
#include "werdit.h"
#include "drawfx.h"
#include "tessbox.h"
#include "tessvars.h"
#include "pgedit.h"
#include "reject.h"
#include "fixspace.h"
#include "docqual.h"
#include "control.h"
#include "output.h"
#include "callcpp.h"
#include "globals.h"
#include "sorthelper.h"
#include "tesseractclass.h"
// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif
#define MIN_FONT_ROW_COUNT 8
#define MAX_XHEIGHT_DIFF 3
const char* const kBackUpConfigFile = "tempconfigdata.config";
// Multiple of x-height to make a repeated word have spaces in it.
const double kRepcharGapThreshold = 0.5;
// Min believable x-height for any text when refitting as a fraction of
// original x-height
const double kMinRefitXHeightFraction = 0.5;
/**
* recog_pseudo_word
*
* Make a word from the selected blobs and run Tess on them.
*
* @param page_res recognise blobs
* @param selection_box within this box
*/
namespace tesseract {
void Tesseract::recog_pseudo_word(PAGE_RES* page_res,
TBOX &selection_box) {
PAGE_RES_IT* it = make_pseudo_word(page_res, selection_box);
if (it != NULL) {
recog_interactive(it);
it->DeleteCurrentWord();
delete it;
}
}
/**
* recog_interactive
*
* Recognize a single word in interactive mode.
*
* @param block block
* @param row row of word
* @param word_res word to recognise
*/
BOOL8 Tesseract::recog_interactive(PAGE_RES_IT* pr_it) {
inT16 char_qual;
inT16 good_char_qual;
WordData word_data(*pr_it);
SetupWordPassN(2, &word_data);
classify_word_and_language(&Tesseract::classify_word_pass2, pr_it,
&word_data);
if (tessedit_debug_quality_metrics) {
WERD_RES* word_res = pr_it->word();
word_char_quality(word_res, pr_it->row()->row, &char_qual, &good_char_qual);
tprintf("\n%d chars; word_blob_quality: %d; outline_errs: %d; "
"char_quality: %d; good_char_quality: %d\n",
word_res->reject_map.length(),
word_blob_quality(word_res, pr_it->row()->row),
word_outline_errs(word_res), char_qual, good_char_qual);
}
return TRUE;
}
// Helper function to check for a target word and handle it appropriately.
// Inspired by Jetsoft's requirement to process only single words on pass2
// and beyond.
// If word_config is not null:
// If the word_box and target_word_box overlap, read the word_config file
// else reset to previous config data.
// return true.
// else
// If the word_box and target_word_box overlap or pass <= 1, return true.
// Note that this function uses a fixed temporary file for storing the previous
// configs, so it is neither thread-safe, nor process-safe, but the assumption
// is that it will only be used for one debug window at a time.
//
// Since this function is used for debugging (and not to change OCR results)
// set only debug params from the word config file.
bool Tesseract::ProcessTargetWord(const TBOX& word_box,
const TBOX& target_word_box,
const char* word_config,
int pass) {
if (word_config != NULL) {
if (word_box.major_overlap(target_word_box)) {
if (backup_config_file_ == NULL) {
backup_config_file_ = kBackUpConfigFile;
FILE* config_fp = fopen(backup_config_file_, "wb");
ParamUtils::PrintParams(config_fp, params());
fclose(config_fp);
ParamUtils::ReadParamsFile(word_config,
SET_PARAM_CONSTRAINT_DEBUG_ONLY,
params());
}
} else {
if (backup_config_file_ != NULL) {
ParamUtils::ReadParamsFile(backup_config_file_,
SET_PARAM_CONSTRAINT_DEBUG_ONLY,
params());
backup_config_file_ = NULL;
}
}
} else if (pass > 1 && !word_box.major_overlap(target_word_box)) {
return false;
}
return true;
}
// If tesseract is to be run, sets the words up ready for it.
void Tesseract::SetupAllWordsPassN(int pass_n,
const TBOX* target_word_box,
const char* word_config,
PAGE_RES* page_res,
GenericVector<WordData>* words) {
// Prepare all the words.
PAGE_RES_IT page_res_it(page_res);
for (page_res_it.restart_page(); page_res_it.word() != NULL;
page_res_it.forward()) {
if (target_word_box == NULL ||
ProcessTargetWord(page_res_it.word()->word->bounding_box(),
*target_word_box, word_config, 1)) {
words->push_back(WordData(page_res_it));
}
}
// Setup all the words for recognition with polygonal approximation.
for (int w = 0; w < words->size(); ++w) {
SetupWordPassN(pass_n, &(*words)[w]);
if (w > 0) (*words)[w].prev_word = &(*words)[w - 1];
}
}
// Sets up the single word ready for whichever engine is to be run.
void Tesseract::SetupWordPassN(int pass_n, WordData* word) {
if (pass_n == 1 || !word->word->done) {
if (pass_n == 1) {
word->word->SetupForRecognition(unicharset, this, BestPix(),
tessedit_ocr_engine_mode, NULL,
classify_bln_numeric_mode,
textord_use_cjk_fp_model,
poly_allow_detailed_fx,
word->row, word->block);
} else if (pass_n == 2) {
// TODO(rays) Should we do this on pass1 too?
word->word->caps_height = 0.0;
if (word->word->x_height == 0.0f)
word->word->x_height = word->row->x_height();
}
for (int s = 0; s <= sub_langs_.size(); ++s) {
// The sub_langs_.size() entry is for the master language.
Tesseract* lang_t = s < sub_langs_.size() ? sub_langs_[s] : this;
WERD_RES* word_res = new WERD_RES;
word_res->InitForRetryRecognition(*word->word);
word->lang_words.push_back(word_res);
// Cube doesn't get setup for pass2.
if (pass_n == 1 || lang_t->tessedit_ocr_engine_mode != OEM_CUBE_ONLY) {
word_res->SetupForRecognition(
lang_t->unicharset, lang_t, BestPix(),
lang_t->tessedit_ocr_engine_mode, NULL,
lang_t->classify_bln_numeric_mode,
lang_t->textord_use_cjk_fp_model,
lang_t->poly_allow_detailed_fx, word->row, word->block);
}
}
}
}
// Runs word recognition on all the words.
bool Tesseract::RecogAllWordsPassN(int pass_n, ETEXT_DESC* monitor,
PAGE_RES_IT* pr_it,
GenericVector<WordData>* words) {
// TODO(rays) Before this loop can be parallelized (it would yield a massive
// speed-up) all remaining member globals need to be converted to local/heap
// (eg set_pass1 and set_pass2) and an intermediate adaption pass needs to be
// added. The results will be significantly different with adaption on, and
// deterioration will need investigation.
pr_it->restart_page();
for (int w = 0; w < words->size(); ++w) {
WordData* word = &(*words)[w];
if (w > 0) word->prev_word = &(*words)[w - 1];
if (monitor != NULL) {
monitor->ocr_alive = TRUE;
if (pass_n == 1)
monitor->progress = 30 + 50 * w / words->size();
else
monitor->progress = 80 + 10 * w / words->size();
if (monitor->deadline_exceeded() ||
(monitor->cancel != NULL && (*monitor->cancel)(monitor->cancel_this,
words->size()))) {
// Timeout. Fake out the rest of the words.
for (; w < words->size(); ++w) {
(*words)[w].word->SetupFake(unicharset);
}
return false;
}
}
if (word->word->tess_failed) {
int s;
for (s = 0; s < word->lang_words.size() &&
word->lang_words[s]->tess_failed; ++s) {}
// If all are failed, skip it. Image words are skipped by this test.
if (s > word->lang_words.size()) continue;
}
// Sync pr_it with the wth WordData.
while (pr_it->word() != NULL && pr_it->word() != word->word)
pr_it->forward();
ASSERT_HOST(pr_it->word() != NULL);
WordRecognizer recognizer = pass_n == 1 ? &Tesseract::classify_word_pass1
: &Tesseract::classify_word_pass2;
classify_word_and_language(recognizer, pr_it, word);
if (tessedit_dump_choices) {
tprintf("Pass%d: %s [%s]\n", pass_n,
word->word->best_choice->unichar_string().string(),
word->word->best_choice->debug_string().string());
}
pr_it->forward();
}
return true;
}
/**
* recog_all_words()
*
* Walk the page_res, recognizing all the words.
* If monitor is not null, it is used as a progress monitor/timeout/cancel.
* If dopasses is 0, all recognition passes are run,
* 1 just pass 1, 2 passes2 and higher.
* If target_word_box is not null, special things are done to words that
* overlap the target_word_box:
* if word_config is not null, the word config file is read for just the
* target word(s), otherwise, on pass 2 and beyond ONLY the target words
* are processed (Jetsoft modification.)
* Returns false if we cancelled prematurely.
*
* @param page_res page structure
* @param monitor progress monitor
* @param word_config word_config file
* @param target_word_box specifies just to extract a rectangle
* @param dopasses 0 - all, 1 just pass 1, 2 passes 2 and higher
*/
bool Tesseract::recog_all_words(PAGE_RES* page_res,
ETEXT_DESC* monitor,
const TBOX* target_word_box,
const char* word_config,
int dopasses) {
PAGE_RES_IT page_res_it(page_res);
if (tessedit_minimal_rej_pass1) {
tessedit_test_adaption.set_value (TRUE);
tessedit_minimal_rejection.set_value (TRUE);
}
if (dopasses==0 || dopasses==1) {
page_res_it.restart_page();
// ****************** Pass 1 *******************
// Clear adaptive classifier at the beginning of the page if it is full.
// This is done only at the beginning of the page to ensure that the
// classifier is not reset at an arbitrary point while processing the page,
// which would cripple Passes 2+ if the reset happens towards the end of
// Pass 1 on a page with very difficult text.
// TODO(daria): preemptively clear the classifier if it is almost full.
if (AdaptiveClassifierIsFull()) ResetAdaptiveClassifierInternal();
// Now check the sub-langs as well.
for (int i = 0; i < sub_langs_.size(); ++i) {
if (sub_langs_[i]->AdaptiveClassifierIsFull())
sub_langs_[i]->ResetAdaptiveClassifierInternal();
}
// Set up all words ready for recognition, so that if parallelism is on
// all the input and output classes are ready to run the classifier.
GenericVector<WordData> words;
SetupAllWordsPassN(1, target_word_box, word_config, page_res, &words);
if (tessedit_parallelize) {
PrerecAllWordsPar(words);
}
stats_.word_count = words.size();
stats_.dict_words = 0;
stats_.doc_blob_quality = 0;
stats_.doc_outline_errs = 0;
stats_.doc_char_quality = 0;
stats_.good_char_count = 0;
stats_.doc_good_char_quality = 0;
most_recently_used_ = this;
// Run pass 1 word recognition.
if (!RecogAllWordsPassN(1, monitor, &page_res_it, &words)) return false;
// Pass 1 post-processing.
for (page_res_it.restart_page(); page_res_it.word() != NULL;
page_res_it.forward()) {
if (page_res_it.word()->word->flag(W_REP_CHAR)) {
fix_rep_char(&page_res_it);
continue;
}
// Count dict words.
if (page_res_it.word()->best_choice->permuter() == USER_DAWG_PERM)
++(stats_.dict_words);
// Update misadaption log (we only need to do it on pass 1, since
// adaption only happens on this pass).
if (page_res_it.word()->blamer_bundle != NULL &&
page_res_it.word()->blamer_bundle->misadaption_debug().length() > 0) {
page_res->misadaption_log.push_back(
page_res_it.word()->blamer_bundle->misadaption_debug());
}
}
}
if (dopasses == 1) return true;
// ****************** Pass 2 *******************
if (tessedit_tess_adaption_mode != 0x0 && !tessedit_test_adaption &&
tessedit_ocr_engine_mode != OEM_CUBE_ONLY ) {
page_res_it.restart_page();
GenericVector<WordData> words;
SetupAllWordsPassN(2, target_word_box, word_config, page_res, &words);
if (tessedit_parallelize) {
PrerecAllWordsPar(words);
}
most_recently_used_ = this;
// Run pass 2 word recognition.
if (!RecogAllWordsPassN(2, monitor, &page_res_it, &words)) return false;
}
// The next passes can only be run if tesseract has been used, as cube
// doesn't set all the necessary outputs in WERD_RES.
if (tessedit_ocr_engine_mode == OEM_TESSERACT_ONLY ||
tessedit_ocr_engine_mode == OEM_TESSERACT_CUBE_COMBINED) {
// ****************** Pass 3 *******************
// Fix fuzzy spaces.
set_global_loc_code(LOC_FUZZY_SPACE);
if (!tessedit_test_adaption && tessedit_fix_fuzzy_spaces
&& !tessedit_word_for_word && !right_to_left())
fix_fuzzy_spaces(monitor, stats_.word_count, page_res);
// ****************** Pass 4 *******************
if (tessedit_enable_dict_correction) dictionary_correction_pass(page_res);
if (tessedit_enable_bigram_correction) bigram_correction_pass(page_res);
// ****************** Pass 5,6 *******************
rejection_passes(page_res, monitor, target_word_box, word_config);
// ****************** Pass 7 *******************
// Cube combiner.
// If cube is loaded and its combiner is present, run it.
if (tessedit_ocr_engine_mode == OEM_TESSERACT_CUBE_COMBINED) {
run_cube_combiner(page_res);
}
// ****************** Pass 8 *******************
font_recognition_pass(page_res);
// ****************** Pass 9 *******************
// Check the correctness of the final results.
blamer_pass(page_res);
script_pos_pass(page_res);
}
// Write results pass.
set_global_loc_code(LOC_WRITE_RESULTS);
// This is now redundant, but retained commented so show how to obtain
// bounding boxes and style information.
// changed by jetsoft
// needed for dll to output memory structure
if ((dopasses == 0 || dopasses == 2) && (monitor || tessedit_write_unlv))
output_pass(page_res_it, target_word_box);
// end jetsoft
PageSegMode pageseg_mode = static_cast<PageSegMode>(
static_cast<int>(tessedit_pageseg_mode));
textord_.CleanupSingleRowResult(pageseg_mode, page_res);
// Remove empty words, as these mess up the result iterators.
for (page_res_it.restart_page(); page_res_it.word() != NULL;
page_res_it.forward()) {
WERD_RES* word = page_res_it.word();
if (word->best_choice == NULL || word->best_choice->length() == 0)
page_res_it.DeleteCurrentWord();
}
if (monitor != NULL) {
monitor->progress = 100;
}
return true;
}
void Tesseract::bigram_correction_pass(PAGE_RES *page_res) {
PAGE_RES_IT word_it(page_res);
WERD_RES *w_prev = NULL;
WERD_RES *w = word_it.word();
while (1) {
w_prev = w;
while (word_it.forward() != NULL &&
(!word_it.word() || word_it.word()->part_of_combo)) {
// advance word_it, skipping over parts of combos
}
if (!word_it.word()) break;
w = word_it.word();
if (!w || !w_prev || w->uch_set != w_prev->uch_set) {
continue;
}
if (w_prev->word->flag(W_REP_CHAR) || w->word->flag(W_REP_CHAR)) {
if (tessedit_bigram_debug) {
tprintf("Skipping because one of the words is W_REP_CHAR\n");
}
continue;
}
// Two words sharing the same language model, excellent!
GenericVector<WERD_CHOICE *> overrides_word1;
GenericVector<WERD_CHOICE *> overrides_word2;
STRING orig_w1_str = w_prev->best_choice->unichar_string();
STRING orig_w2_str = w->best_choice->unichar_string();
WERD_CHOICE prev_best(w->uch_set);
{
int w1start, w1end;
w_prev->best_choice->GetNonSuperscriptSpan(&w1start, &w1end);
prev_best = w_prev->best_choice->shallow_copy(w1start, w1end);
}
WERD_CHOICE this_best(w->uch_set);
{
int w2start, w2end;
w->best_choice->GetNonSuperscriptSpan(&w2start, &w2end);
this_best = w->best_choice->shallow_copy(w2start, w2end);
}
if (w->tesseract->getDict().valid_bigram(prev_best, this_best)) {
if (tessedit_bigram_debug) {
tprintf("Top choice \"%s %s\" verified by bigram model.\n",
orig_w1_str.string(), orig_w2_str.string());
}
continue;
}
if (tessedit_bigram_debug > 2) {
tprintf("Examining alt choices for \"%s %s\".\n",
orig_w1_str.string(), orig_w2_str.string());
}
if (tessedit_bigram_debug > 1) {
if (!w_prev->best_choices.singleton()) {
w_prev->PrintBestChoices();
}
if (!w->best_choices.singleton()) {
w->PrintBestChoices();
}
}
float best_rating = 0.0;
int best_idx = 0;
WERD_CHOICE_IT prev_it(&w_prev->best_choices);
for (prev_it.mark_cycle_pt(); !prev_it.cycled_list(); prev_it.forward()) {
WERD_CHOICE *p1 = prev_it.data();
WERD_CHOICE strip1(w->uch_set);
{
int p1start, p1end;
p1->GetNonSuperscriptSpan(&p1start, &p1end);
strip1 = p1->shallow_copy(p1start, p1end);
}
WERD_CHOICE_IT w_it(&w->best_choices);
for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
WERD_CHOICE *p2 = w_it.data();
WERD_CHOICE strip2(w->uch_set);
{
int p2start, p2end;
p2->GetNonSuperscriptSpan(&p2start, &p2end);
strip2 = p2->shallow_copy(p2start, p2end);
}
if (w->tesseract->getDict().valid_bigram(strip1, strip2)) {
overrides_word1.push_back(p1);
overrides_word2.push_back(p2);
if (overrides_word1.size() == 1 ||
p1->rating() + p2->rating() < best_rating) {
best_rating = p1->rating() + p2->rating();
best_idx = overrides_word1.size() - 1;
}
}
}
}
if (overrides_word1.size() >= 1) {
// Excellent, we have some bigram matches.
if (EqualIgnoringCaseAndTerminalPunct(*w_prev->best_choice,
*overrides_word1[best_idx]) &&
EqualIgnoringCaseAndTerminalPunct(*w->best_choice,
*overrides_word2[best_idx])) {
if (tessedit_bigram_debug > 1) {
tprintf("Top choice \"%s %s\" verified (sans case) by bigram "
"model.\n", orig_w1_str.string(), orig_w2_str.string());
}
continue;
}
STRING new_w1_str = overrides_word1[best_idx]->unichar_string();
STRING new_w2_str = overrides_word2[best_idx]->unichar_string();
if (new_w1_str != orig_w1_str) {
w_prev->ReplaceBestChoice(overrides_word1[best_idx]);
}
if (new_w2_str != orig_w2_str) {
w->ReplaceBestChoice(overrides_word2[best_idx]);
}
if (tessedit_bigram_debug > 0) {
STRING choices_description;
int num_bigram_choices
= overrides_word1.size() * overrides_word2.size();
if (num_bigram_choices == 1) {
choices_description = "This was the unique bigram choice.";
} else {
if (tessedit_bigram_debug > 1) {
STRING bigrams_list;
const int kMaxChoicesToPrint = 20;
for (int i = 0; i < overrides_word1.size() &&
i < kMaxChoicesToPrint; i++) {
if (i > 0) { bigrams_list += ", "; }
WERD_CHOICE *p1 = overrides_word1[i];
WERD_CHOICE *p2 = overrides_word2[i];
bigrams_list += p1->unichar_string() + " " + p2->unichar_string();
if (i == kMaxChoicesToPrint) {
bigrams_list += " ...";
}
}
choices_description = "There were many choices: {";
choices_description += bigrams_list;
choices_description += "}";
} else {
choices_description.add_str_int("There were ", num_bigram_choices);
choices_description += " compatible bigrams.";
}
}
tprintf("Replaced \"%s %s\" with \"%s %s\" with bigram model. %s\n",
orig_w1_str.string(), orig_w2_str.string(),
new_w1_str.string(), new_w2_str.string(),
choices_description.string());
}
}
}
}
void Tesseract::rejection_passes(PAGE_RES* page_res,
ETEXT_DESC* monitor,
const TBOX* target_word_box,
const char* word_config) {
PAGE_RES_IT page_res_it(page_res);
// ****************** Pass 5 *******************
// Gather statistics on rejects.
int word_index = 0;
while (!tessedit_test_adaption && page_res_it.word() != NULL) {
set_global_loc_code(LOC_MM_ADAPT);
WERD_RES* word = page_res_it.word();
word_index++;
if (monitor != NULL) {
monitor->ocr_alive = TRUE;
monitor->progress = 95 + 5 * word_index / stats_.word_count;
}
if (word->rebuild_word == NULL) {
// Word was not processed by tesseract.
page_res_it.forward();
continue;
}
check_debug_pt(word, 70);
// changed by jetsoft
// specific to its needs to extract one word when need
if (target_word_box &&
!ProcessTargetWord(word->word->bounding_box(),
*target_word_box, word_config, 4)) {
page_res_it.forward();
continue;
}
// end jetsoft
page_res_it.rej_stat_word();
int chars_in_word = word->reject_map.length();
int rejects_in_word = word->reject_map.reject_count();
int blob_quality = word_blob_quality(word, page_res_it.row()->row);
stats_.doc_blob_quality += blob_quality;
int outline_errs = word_outline_errs(word);
stats_.doc_outline_errs += outline_errs;
inT16 all_char_quality;
inT16 accepted_all_char_quality;
word_char_quality(word, page_res_it.row()->row,
&all_char_quality, &accepted_all_char_quality);
stats_.doc_char_quality += all_char_quality;
uinT8 permuter_type = word->best_choice->permuter();
if ((permuter_type == SYSTEM_DAWG_PERM) ||
(permuter_type == FREQ_DAWG_PERM) ||
(permuter_type == USER_DAWG_PERM)) {
stats_.good_char_count += chars_in_word - rejects_in_word;
stats_.doc_good_char_quality += accepted_all_char_quality;
}
check_debug_pt(word, 80);
if (tessedit_reject_bad_qual_wds &&
(blob_quality == 0) && (outline_errs >= chars_in_word))
word->reject_map.rej_word_bad_quality();
check_debug_pt(word, 90);
page_res_it.forward();
}
if (tessedit_debug_quality_metrics) {
tprintf
("QUALITY: num_chs= %d num_rejs= %d %5.3f blob_qual= %d %5.3f"
" outline_errs= %d %5.3f char_qual= %d %5.3f good_ch_qual= %d %5.3f\n",
page_res->char_count, page_res->rej_count,
page_res->rej_count / static_cast<float>(page_res->char_count),
stats_.doc_blob_quality,
stats_.doc_blob_quality / static_cast<float>(page_res->char_count),
stats_.doc_outline_errs,
stats_.doc_outline_errs / static_cast<float>(page_res->char_count),
stats_.doc_char_quality,
stats_.doc_char_quality / static_cast<float>(page_res->char_count),
stats_.doc_good_char_quality,
(stats_.good_char_count > 0) ?
(stats_.doc_good_char_quality /
static_cast<float>(stats_.good_char_count)) : 0.0);
}
BOOL8 good_quality_doc =
((page_res->rej_count / static_cast<float>(page_res->char_count)) <=
quality_rej_pc) &&
(stats_.doc_blob_quality / static_cast<float>(page_res->char_count) >=
quality_blob_pc) &&
(stats_.doc_outline_errs / static_cast<float>(page_res->char_count) <=
quality_outline_pc) &&
(stats_.doc_char_quality / static_cast<float>(page_res->char_count) >=
quality_char_pc);
// ****************** Pass 6 *******************
// Do whole document or whole block rejection pass
if (!tessedit_test_adaption) {
set_global_loc_code(LOC_DOC_BLK_REJ);
quality_based_rejection(page_res_it, good_quality_doc);
}
}
void Tesseract::blamer_pass(PAGE_RES* page_res) {
if (!wordrec_run_blamer) return;
PAGE_RES_IT page_res_it(page_res);
for (page_res_it.restart_page(); page_res_it.word() != NULL;
page_res_it.forward()) {
WERD_RES *word = page_res_it.word();
BlamerBundle::LastChanceBlame(wordrec_debug_blamer, word);
page_res->blame_reasons[word->blamer_bundle->incorrect_result_reason()]++;
}
tprintf("Blame reasons:\n");
for (int bl = 0; bl < IRR_NUM_REASONS; ++bl) {
tprintf("%s %d\n", BlamerBundle::IncorrectReasonName(
static_cast<IncorrectResultReason>(bl)),
page_res->blame_reasons[bl]);
}
if (page_res->misadaption_log.length() > 0) {
tprintf("Misadaption log:\n");
for (int i = 0; i < page_res->misadaption_log.length(); ++i) {
tprintf("%s\n", page_res->misadaption_log[i].string());
}
}
}
// Sets script positions and detects smallcaps on all output words.
void Tesseract::script_pos_pass(PAGE_RES* page_res) {
PAGE_RES_IT page_res_it(page_res);
for (page_res_it.restart_page(); page_res_it.word() != NULL;
page_res_it.forward()) {
WERD_RES* word = page_res_it.word();
if (word->word->flag(W_REP_CHAR)) {
page_res_it.forward();
continue;
}
float x_height = page_res_it.block()->block->x_height();
float word_x_height = word->x_height;
if (word_x_height < word->best_choice->min_x_height() ||
word_x_height > word->best_choice->max_x_height()) {
word_x_height = (word->best_choice->min_x_height() +
word->best_choice->max_x_height()) / 2.0f;
}
// Test for small caps. Word capheight must be close to block xheight,
// and word must contain no lower case letters, and at least one upper case.
double small_cap_xheight = x_height * kXHeightCapRatio;
double small_cap_delta = (x_height - small_cap_xheight) / 2.0;
if (word->uch_set->script_has_xheight() &&
small_cap_xheight - small_cap_delta <= word_x_height &&
word_x_height <= small_cap_xheight + small_cap_delta) {
// Scan for upper/lower.
int num_upper = 0;
int num_lower = 0;
for (int i = 0; i < word->best_choice->length(); ++i) {
if (word->uch_set->get_isupper(word->best_choice->unichar_id(i)))
++num_upper;
else if (word->uch_set->get_islower(word->best_choice->unichar_id(i)))
++num_lower;
}
if (num_upper > 0 && num_lower == 0)
word->small_caps = true;
}
word->SetScriptPositions();
}
}
// Factored helper considers the indexed word and updates all the pointed
// values.
static void EvaluateWord(const PointerVector<WERD_RES>& words, int index,
float* rating, float* certainty, bool* bad,
bool* valid_permuter, int* right, int* next_left) {
*right = -MAX_INT32;
*next_left = MAX_INT32;
if (index < words.size()) {
WERD_CHOICE* choice = words[index]->best_choice;
if (choice == NULL) {
*bad = true;
} else {
*rating += choice->rating();
*certainty = MIN(*certainty, choice->certainty());
if (!Dict::valid_word_permuter(choice->permuter(), false))
*valid_permuter = false;
}
*right = words[index]->word->bounding_box().right();
if (index + 1 < words.size())
*next_left = words[index + 1]->word->bounding_box().left();
} else {
*valid_permuter = false;
*bad = true;
}
}
// Helper chooses the best combination of words, transferring good ones from
// new_words to best_words. To win, a new word must have (better rating and
// certainty) or (better permuter status and rating within rating ratio and
// certainty within certainty margin) than current best.
// All the new_words are consumed (moved to best_words or deleted.)
// The return value is the number of new_words used minus the number of
// best_words that remain in the output.
static int SelectBestWords(double rating_ratio,
double certainty_margin,
bool debug,
PointerVector<WERD_RES>* new_words,
PointerVector<WERD_RES>* best_words) {
// Process the smallest groups of words that have an overlapping word
// boundary at the end.
GenericVector<WERD_RES*> out_words;
// Index into each word vector (best, new).
int b = 0, n = 0;
int num_best = 0, num_new = 0;
while (b < best_words->size() || n < new_words->size()) {
// Start of the current run in each.
int start_b = b, start_n = n;
// Rating of the current run in each.
float b_rating = 0.0f, n_rating = 0.0f;
// Certainty of the current run in each.
float b_certainty = 0.0f, n_certainty = 0.0f;
// True if any word is missing its best choice.
bool b_bad = false, n_bad = false;
// True if all words have a valid permuter.
bool b_valid_permuter = true, n_valid_permuter = true;
while (b < best_words->size() || n < new_words->size()) {
int b_right = -MAX_INT32;
int next_b_left = MAX_INT32;
EvaluateWord(*best_words, b, &b_rating, &b_certainty, &b_bad,
&b_valid_permuter, &b_right, &next_b_left);
int n_right = -MAX_INT32;
int next_n_left = MAX_INT32;
EvaluateWord(*new_words, n, &n_rating, &n_certainty, &n_bad,
&n_valid_permuter, &n_right, &next_n_left);
if (MAX(b_right, n_right) < MIN(next_b_left, next_n_left)) {
// The word breaks overlap. [start_b,b] and [start_n, n] match.
break;
}
// Keep searching for the matching word break.
if ((b_right < n_right && b < best_words->size()) ||
n == new_words->size())
++b;
else
++n;
}
bool new_better = false;
if (!n_bad && (b_bad || (n_certainty > b_certainty &&
n_rating < b_rating) ||
(!b_valid_permuter && n_valid_permuter &&
n_rating < b_rating * rating_ratio &&
n_certainty > b_certainty - certainty_margin))) {
// New is better.
for (int i = start_n; i <= n; ++i) {
out_words.push_back((*new_words)[i]);
(*new_words)[i] = NULL;
++num_new;
}
new_better = true;
} else if (!b_bad) {
// Current best is better.
for (int i = start_b; i <= b; ++i) {
out_words.push_back((*best_words)[i]);
(*best_words)[i] = NULL;
++num_best;
}
}
int end_b = b < best_words->size() ? b + 1 : b;
int end_n = n < new_words->size() ? n + 1 : n;
if (debug) {
tprintf("%d new words %s than %d old words: r: %g v %g c: %g v %g"
" valid dict: %d v %d\n",
end_n - start_n, new_better ? "better" : "worse",
end_b - start_b, n_rating, b_rating,
n_certainty, b_certainty, n_valid_permuter, b_valid_permuter);
}
// Move on to the next group.
b = end_b;
n = end_n;
}
// Transfer from out_words to best_words.
best_words->clear();
for (int i = 0; i < out_words.size(); ++i)
best_words->push_back(out_words[i]);
return num_new - num_best;
}
// Helper to recognize the word using the given (language-specific) tesseract.
// Returns positive if this recognizer found more new best words than the
// number kept from best_words.
int Tesseract::RetryWithLanguage(const WordData& word_data,
WordRecognizer recognizer,
WERD_RES** in_word,
PointerVector<WERD_RES>* best_words) {
bool debug = classify_debug_level || cube_debug_level;
if (debug) {
tprintf("Trying word using lang %s, oem %d\n",
lang.string(), static_cast<int>(tessedit_ocr_engine_mode));
}
// Run the recognizer on the word.
PointerVector<WERD_RES> new_words;
(this->*recognizer)(word_data, in_word, &new_words);
if (new_words.empty()) {
// Transfer input word to new_words, as the classifier must have put
// the result back in the input.
new_words.push_back(*in_word);
*in_word = NULL;
}
if (debug) {
for (int i = 0; i < new_words.size(); ++i)
new_words[i]->DebugTopChoice("Lang result");
}
// Initial version is a bit of a hack based on better certainty and rating
// (to reduce false positives from cube) or a dictionary vs non-dictionary
// word.
return SelectBestWords(classify_max_rating_ratio,
classify_max_certainty_margin,
debug, &new_words, best_words);
}
// Helper returns true if all the words are acceptable.
static bool WordsAcceptable(const PointerVector<WERD_RES>& words) {
for (int w = 0; w < words.size(); ++w) {
if (words[w]->tess_failed || !words[w]->tess_accepted) return false;
}
return true;
}
// Generic function for classifying a word. Can be used either for pass1 or
// pass2 according to the function passed to recognizer.
// word_data holds the word to be recognized, and its block and row, and
// pr_it points to the word as well, in case we are running LSTM and it wants
// to output multiple words.
// Recognizes in the current language, and if successful that is all.
// If recognition was not successful, tries all available languages until
// it gets a successful result or runs out of languages. Keeps the best result.
void Tesseract::classify_word_and_language(WordRecognizer recognizer,
PAGE_RES_IT* pr_it,
WordData* word_data) {
// Best result so far.
PointerVector<WERD_RES> best_words;
// Points to the best result. May be word or in lang_words.
WERD_RES* word = word_data->word;
clock_t start_t = clock();
if (classify_debug_level || cube_debug_level) {
tprintf("%s word with lang %s at:",
word->done ? "Already done" : "Processing",
most_recently_used_->lang.string());
word->word->bounding_box().print();
}
if (word->done) {
// If done on pass1, leave it as-is.
if (!word->tess_failed)
most_recently_used_ = word->tesseract;
return;
}
int sub = sub_langs_.size();
if (most_recently_used_ != this) {
// Get the index of the most_recently_used_.
for (sub = 0; sub < sub_langs_.size() &&
most_recently_used_ != sub_langs_[sub]; ++sub) {}
}
most_recently_used_->RetryWithLanguage(
*word_data, recognizer, &word_data->lang_words[sub], &best_words);
Tesseract* best_lang_tess = most_recently_used_;
if (!WordsAcceptable(best_words)) {
// Try all the other languages to see if they are any better.
if (most_recently_used_ != this &&
this->RetryWithLanguage(*word_data, recognizer,
&word_data->lang_words[sub_langs_.size()],
&best_words) > 0) {
best_lang_tess = this;
}
for (int i = 0; !WordsAcceptable(best_words) && i < sub_langs_.size();
++i) {
if (most_recently_used_ != sub_langs_[i] &&
sub_langs_[i]->RetryWithLanguage(*word_data, recognizer,
&word_data->lang_words[i],
&best_words) > 0) {
best_lang_tess = sub_langs_[i];
}
}
}
most_recently_used_ = best_lang_tess;
if (!best_words.empty()) {
if (best_words.size() == 1 && !best_words[0]->combination) {
// Move the best single result to the main word.
word_data->word->ConsumeWordResults(best_words[0]);
} else {
// Words came from LSTM, and must be moved to the PAGE_RES properly.
word_data->word = best_words.back();
pr_it->ReplaceCurrentWord(&best_words);
}
ASSERT_HOST(word_data->word->box_word != NULL);
} else {
tprintf("no best words!!\n");
}
clock_t ocr_t = clock();
if (tessedit_timing_debug) {
tprintf("%s (ocr took %.2f sec)\n",
word->best_choice->unichar_string().string(),
static_cast<double>(ocr_t-start_t)/CLOCKS_PER_SEC);
}
}
/**
* classify_word_pass1
*
* Baseline normalize the word and pass it to Tess.
*/
void Tesseract::classify_word_pass1(const WordData& word_data,
WERD_RES** in_word,
PointerVector<WERD_RES>* out_words) {
ROW* row = word_data.row;
BLOCK* block = word_data.block;
prev_word_best_choice_ = word_data.prev_word != NULL
? word_data.prev_word->word->best_choice : NULL;
// If we only intend to run cube - run it and return.
if (tessedit_ocr_engine_mode == OEM_CUBE_ONLY) {
cube_word_pass1(block, row, *in_word);
return;
}
WERD_RES* word = *in_word;
match_word_pass_n(1, word, row, block);
if (!word->tess_failed && !word->word->flag(W_REP_CHAR)) {
word->tess_would_adapt = AdaptableWord(word);
bool adapt_ok = word_adaptable(word, tessedit_tess_adaption_mode);
if (adapt_ok) {
// Send word to adaptive classifier for training.
word->BestChoiceToCorrectText();
LearnWord(NULL, word);
// Mark misadaptions if running blamer.
if (word->blamer_bundle != NULL) {
word->blamer_bundle->SetMisAdaptionDebug(word->best_choice,
wordrec_debug_blamer);
}
}
if (tessedit_enable_doc_dict && !word->IsAmbiguous())
tess_add_doc_word(word->best_choice);
}
}
// Helper to report the result of the xheight fix.
void Tesseract::ReportXhtFixResult(bool accept_new_word, float new_x_ht,
WERD_RES* word, WERD_RES* new_word) {
tprintf("New XHT Match:%s = %s ",
word->best_choice->unichar_string().string(),
word->best_choice->debug_string().string());
word->reject_map.print(debug_fp);
tprintf(" -> %s = %s ",
new_word->best_choice->unichar_string().string(),
new_word->best_choice->debug_string().string());
new_word->reject_map.print(debug_fp);
tprintf(" %s->%s %s %s\n",
word->guessed_x_ht ? "GUESS" : "CERT",
new_word->guessed_x_ht ? "GUESS" : "CERT",
new_x_ht > 0.1 ? "STILL DOUBT" : "OK",
accept_new_word ? "ACCEPTED" : "");
}
// Run the x-height fix-up, based on min/max top/bottom information in
// unicharset.
// Returns true if the word was changed.
// See the comment in fixxht.cpp for a description of the overall process.
bool Tesseract::TrainedXheightFix(WERD_RES *word, BLOCK* block, ROW *row) {
bool accept_new_x_ht = false;
int original_misfits = CountMisfitTops(word);
if (original_misfits == 0)
return false;
float new_x_ht = ComputeCompatibleXheight(word);
if (new_x_ht >= kMinRefitXHeightFraction * word->x_height) {
WERD_RES new_x_ht_word(word->word);
if (word->blamer_bundle != NULL) {
new_x_ht_word.blamer_bundle = new BlamerBundle();
new_x_ht_word.blamer_bundle->CopyTruth(*(word->blamer_bundle));
}
new_x_ht_word.x_height = new_x_ht;
new_x_ht_word.caps_height = 0.0;
new_x_ht_word.SetupForRecognition(
unicharset, this, BestPix(), tessedit_ocr_engine_mode, NULL,
classify_bln_numeric_mode, textord_use_cjk_fp_model,
poly_allow_detailed_fx, row, block);
match_word_pass_n(2, &new_x_ht_word, row, block);
if (!new_x_ht_word.tess_failed) {
int new_misfits = CountMisfitTops(&new_x_ht_word);
if (debug_x_ht_level >= 1) {
tprintf("Old misfits=%d with x-height %f, new=%d with x-height %f\n",
original_misfits, word->x_height,
new_misfits, new_x_ht);
tprintf("Old rating= %f, certainty=%f, new=%f, %f\n",
word->best_choice->rating(), word->best_choice->certainty(),
new_x_ht_word.best_choice->rating(),
new_x_ht_word.best_choice->certainty());
}
// The misfits must improve and either the rating or certainty.
accept_new_x_ht = new_misfits < original_misfits &&
(new_x_ht_word.best_choice->certainty() >
word->best_choice->certainty() ||
new_x_ht_word.best_choice->rating() <
word->best_choice->rating());
if (debug_x_ht_level >= 1) {
ReportXhtFixResult(accept_new_x_ht, new_x_ht, word, &new_x_ht_word);
}
}
if (accept_new_x_ht) {
word->ConsumeWordResults(&new_x_ht_word);
return true;
}
}
return false;
}
/**
* classify_word_pass2
*
* Control what to do with the word in pass 2
*/
void Tesseract::classify_word_pass2(const WordData& word_data,
WERD_RES** in_word,
PointerVector<WERD_RES>* out_words) {
// Return if we do not want to run Tesseract.
if (tessedit_ocr_engine_mode != OEM_TESSERACT_ONLY &&
tessedit_ocr_engine_mode != OEM_TESSERACT_CUBE_COMBINED &&
word_data.word->best_choice != NULL)
return;
ROW* row = word_data.row;
BLOCK* block = word_data.block;
WERD_RES* word = *in_word;
prev_word_best_choice_ = word_data.prev_word != NULL
? word_data.prev_word->word->best_choice : NULL;
set_global_subloc_code(SUBLOC_NORM);
check_debug_pt(word, 30);
if (!word->done) {
word->caps_height = 0.0;
if (word->x_height == 0.0f)
word->x_height = row->x_height();
match_word_pass_n(2, word, row, block);
check_debug_pt(word, 40);
}
SubAndSuperscriptFix(word);
if (!word->tess_failed && !word->word->flag(W_REP_CHAR)) {
if (unicharset.top_bottom_useful() && unicharset.script_has_xheight() &&
block->classify_rotation().y() == 0.0f) {
// Use the tops and bottoms since they are available.
TrainedXheightFix(word, block, row);
}
set_global_subloc_code(SUBLOC_NORM);
}
#ifndef GRAPHICS_DISABLED
if (tessedit_display_outwords) {
if (fx_win == NULL)
create_fx_win();
clear_fx_win();
word->rebuild_word->plot(fx_win);
TBOX wbox = word->rebuild_word->bounding_box();
fx_win->ZoomToRectangle(wbox.left(), wbox.top(),
wbox.right(), wbox.bottom());
ScrollView::Update();
}
#endif
set_global_subloc_code(SUBLOC_NORM);
check_debug_pt(word, 50);
}
/**
* match_word_pass2
*
* Baseline normalize the word and pass it to Tess.
*/
void Tesseract::match_word_pass_n(int pass_n, WERD_RES *word,
ROW *row, BLOCK* block) {
if (word->tess_failed) return;
tess_segment_pass_n(pass_n, word);
if (!word->tess_failed) {
if (!word->word->flag (W_REP_CHAR)) {
word->fix_quotes();
if (tessedit_fix_hyphens)
word->fix_hyphens();
/* Dont trust fix_quotes! - though I think I've fixed the bug */
if (word->best_choice->length() != word->box_word->length()) {
tprintf("POST FIX_QUOTES FAIL String:\"%s\"; Strlen=%d;"
" #Blobs=%d\n",
word->best_choice->debug_string().string(),
word->best_choice->length(),
word->box_word->length());
}
word->tess_accepted = tess_acceptable_word(word);
// Also sets word->done flag
make_reject_map(word, row, pass_n);
}
}
set_word_fonts(word);
ASSERT_HOST(word->raw_choice != NULL);
}
// Helper to return the best rated BLOB_CHOICE in the whole word that matches
// the given char_id, or NULL if none can be found.
static BLOB_CHOICE* FindBestMatchingChoice(UNICHAR_ID char_id,
WERD_RES* word_res) {
// Find the corresponding best BLOB_CHOICE from any position in the word_res.
BLOB_CHOICE* best_choice = NULL;
for (int i = 0; i < word_res->best_choice->length(); ++i) {
BLOB_CHOICE* choice = FindMatchingChoice(char_id,
word_res->GetBlobChoices(i));
if (choice != NULL) {
if (best_choice == NULL || choice->rating() < best_choice->rating())
best_choice = choice;
}
}
return best_choice;
}
// Helper to insert blob_choice in each location in the leader word if there is
// no matching BLOB_CHOICE there already, and correct any incorrect results
// in the best_choice.
static void CorrectRepcharChoices(BLOB_CHOICE* blob_choice,
WERD_RES* word_res) {
WERD_CHOICE* word = word_res->best_choice;
for (int i = 0; i < word_res->best_choice->length(); ++i) {
BLOB_CHOICE* choice = FindMatchingChoice(blob_choice->unichar_id(),
word_res->GetBlobChoices(i));
if (choice == NULL) {
BLOB_CHOICE_IT choice_it(word_res->GetBlobChoices(i));
choice_it.add_before_stay_put(new BLOB_CHOICE(*blob_choice));
}
}
// Correct any incorrect results in word.
for (int i = 0; i < word->length(); ++i) {
if (word->unichar_id(i) != blob_choice->unichar_id())
word->set_unichar_id(blob_choice->unichar_id(), i);
}
}
/**
* fix_rep_char()
* The word is a repeated char. (Leader.) Find the repeated char character.
* Create the appropriate single-word or multi-word sequence according to
* the size of spaces in between blobs, and correct the classifications
* where some of the characters disagree with the majority.
*/
void Tesseract::fix_rep_char(PAGE_RES_IT* page_res_it) {
WERD_RES *word_res = page_res_it->word();
const WERD_CHOICE &word = *(word_res->best_choice);
// Find the frequency of each unique character in the word.
SortHelper<UNICHAR_ID> rep_ch(word.length());
for (int i = 0; i < word.length(); ++i) {
rep_ch.Add(word.unichar_id(i), 1);
}
// Find the most frequent result.
UNICHAR_ID maxch_id = INVALID_UNICHAR_ID; // most common char
int max_count = rep_ch.MaxCount(&maxch_id);
// Find the best exemplar of a classifier result for maxch_id.
BLOB_CHOICE* best_choice = FindBestMatchingChoice(maxch_id, word_res);
if (best_choice == NULL) {
tprintf("Failed to find a choice for %s, occurring %d times\n",
word_res->uch_set->debug_str(maxch_id).string(), max_count);
return;
}
word_res->done = TRUE;
// Measure the mean space.
int total_gap = 0;
int gap_count = 0;
WERD* werd = word_res->word;
C_BLOB_IT blob_it(werd->cblob_list());
C_BLOB* prev_blob = blob_it.data();
for (blob_it.forward(); !blob_it.at_first(); blob_it.forward()) {
C_BLOB* blob = blob_it.data();
int gap = blob->bounding_box().left();
gap -= prev_blob->bounding_box().right();
total_gap += gap;
++gap_count;
prev_blob = blob;
}
// Just correct existing classification.
CorrectRepcharChoices(best_choice, word_res);
word_res->reject_map.initialise(word.length());
}
ACCEPTABLE_WERD_TYPE Tesseract::acceptable_word_string(
const UNICHARSET& char_set, const char *s, const char *lengths) {
int i = 0;
int offset = 0;
int leading_punct_count;
int upper_count = 0;
int hyphen_pos = -1;
ACCEPTABLE_WERD_TYPE word_type = AC_UNACCEPTABLE;
if (strlen (lengths) > 20)
return word_type;
/* Single Leading punctuation char*/
if (s[offset] != '\0' && STRING(chs_leading_punct).contains(s[offset]))
offset += lengths[i++];
leading_punct_count = i;
/* Initial cap */
while (s[offset] != '\0' && char_set.get_isupper(s + offset, lengths[i])) {
offset += lengths[i++];
upper_count++;
}
if (upper_count > 1) {
word_type = AC_UPPER_CASE;
} else {
/* Lower case word, possibly with an initial cap */
while (s[offset] != '\0' && char_set.get_islower(s + offset, lengths[i])) {
offset += lengths[i++];
}
if (i - leading_punct_count < quality_min_initial_alphas_reqd)
goto not_a_word;
/*
Allow a single hyphen in a lower case word
- dont trust upper case - I've seen several cases of "H" -> "I-I"
*/
if (lengths[i] == 1 && s[offset] == '-') {
hyphen_pos = i;
offset += lengths[i++];
if (s[offset] != '\0') {
while ((s[offset] != '\0') &&
char_set.get_islower(s + offset, lengths[i])) {
offset += lengths[i++];
}
if (i < hyphen_pos + 3)
goto not_a_word;
}
} else {
/* Allow "'s" in NON hyphenated lower case words */
if (lengths[i] == 1 && (s[offset] == '\'') &&
lengths[i + 1] == 1 && (s[offset + lengths[i]] == 's')) {
offset += lengths[i++];
offset += lengths[i++];
}
}
if (upper_count > 0)
word_type = AC_INITIAL_CAP;
else
word_type = AC_LOWER_CASE;
}
/* Up to two different, constrained trailing punctuation chars */
if (lengths[i] == 1 && s[offset] != '\0' &&
STRING(chs_trailing_punct1).contains(s[offset]))
offset += lengths[i++];
if (lengths[i] == 1 && s[offset] != '\0' && i > 0 &&
s[offset - lengths[i - 1]] != s[offset] &&
STRING(chs_trailing_punct2).contains (s[offset]))
offset += lengths[i++];
if (s[offset] != '\0')
word_type = AC_UNACCEPTABLE;
not_a_word:
if (word_type == AC_UNACCEPTABLE) {
/* Look for abbreviation string */
i = 0;
offset = 0;
if (s[0] != '\0' && char_set.get_isupper(s, lengths[0])) {
word_type = AC_UC_ABBREV;
while (s[offset] != '\0' &&
char_set.get_isupper(s + offset, lengths[i]) &&
lengths[i + 1] == 1 && s[offset + lengths[i]] == '.') {
offset += lengths[i++];
offset += lengths[i++];
}
}
else if (s[0] != '\0' && char_set.get_islower(s, lengths[0])) {
word_type = AC_LC_ABBREV;
while (s[offset] != '\0' &&
char_set.get_islower(s + offset, lengths[i]) &&
lengths[i + 1] == 1 && s[offset + lengths[i]] == '.') {
offset += lengths[i++];
offset += lengths[i++];
}
}
if (s[offset] != '\0')
word_type = AC_UNACCEPTABLE;
}
return word_type;
}
BOOL8 Tesseract::check_debug_pt(WERD_RES *word, int location) {
BOOL8 show_map_detail = FALSE;
inT16 i;
if (!test_pt)
return FALSE;
tessedit_rejection_debug.set_value (FALSE);
debug_x_ht_level.set_value (0);
if (word->word->bounding_box ().contains (FCOORD (test_pt_x, test_pt_y))) {
if (location < 0)
return TRUE; // For breakpoint use
tessedit_rejection_debug.set_value (TRUE);
debug_x_ht_level.set_value (20);
tprintf ("\n\nTESTWD::");
switch (location) {
case 0:
tprintf ("classify_word_pass1 start\n");
word->word->print();
break;
case 10:
tprintf ("make_reject_map: initial map");
break;
case 20:
tprintf ("make_reject_map: after NN");
break;
case 30:
tprintf ("classify_word_pass2 - START");
break;
case 40:
tprintf ("classify_word_pass2 - Pre Xht");
break;
case 50:
tprintf ("classify_word_pass2 - END");
show_map_detail = TRUE;
break;
case 60:
tprintf ("fixspace");
break;
case 70:
tprintf ("MM pass START");
break;
case 80:
tprintf ("MM pass END");
break;
case 90:
tprintf ("After Poor quality rejection");
break;
case 100:
tprintf ("unrej_good_quality_words - START");
break;
case 110:
tprintf ("unrej_good_quality_words - END");
break;
case 120:
tprintf ("Write results pass");
show_map_detail = TRUE;
break;
}
if (word->best_choice != NULL) {
tprintf(" \"%s\" ", word->best_choice->unichar_string().string());
word->reject_map.print(debug_fp);
tprintf("\n");
if (show_map_detail) {
tprintf("\"%s\"\n", word->best_choice->unichar_string().string());
for (i = 0; word->best_choice->unichar_string()[i] != '\0'; i++) {
tprintf("**** \"%c\" ****\n", word->best_choice->unichar_string()[i]);
word->reject_map[i].full_print(debug_fp);
}
}
} else {
tprintf("null best choice\n");
}
tprintf ("Tess Accepted: %s\n", word->tess_accepted ? "TRUE" : "FALSE");
tprintf ("Done flag: %s\n\n", word->done ? "TRUE" : "FALSE");
return TRUE;
} else {
return FALSE;
}
}
/**
* find_modal_font
*
* Find the modal font and remove from the stats.
*/
static void find_modal_font( //good chars in word
STATS *fonts, //font stats
inT16 *font_out, //output font
inT8 *font_count //output count
) {
inT16 font; //font index
inT32 count; //pile couat
if (fonts->get_total () > 0) {
font = (inT16) fonts->mode ();
*font_out = font;
count = fonts->pile_count (font);
*font_count = count < MAX_INT8 ? count : MAX_INT8;
fonts->add (font, -*font_count);
}
else {
*font_out = -1;
*font_count = 0;
}
}
/**
* set_word_fonts
*
* Get the fonts for the word.
*/
void Tesseract::set_word_fonts(WERD_RES *word) {
// Don't try to set the word fonts for a cube word, as the configs
// will be meaningless.
if (word->chopped_word == NULL) return;
ASSERT_HOST(word->best_choice != NULL);
inT32 index; // char id index
// character iterator
BLOB_CHOICE_IT choice_it; // choice iterator
int fontinfo_size = get_fontinfo_table().size();
int fontset_size = get_fontset_table().size();
if (fontinfo_size == 0 || fontset_size == 0) return;
STATS fonts(0, fontinfo_size); // font counters
word->italic = 0;
word->bold = 0;
if (!word->best_choice_fontinfo_ids.empty()) {
word->best_choice_fontinfo_ids.clear();
}
// Compute the modal font for the word
for (index = 0; index < word->best_choice->length(); ++index) {
UNICHAR_ID word_ch_id = word->best_choice->unichar_id(index);
choice_it.set_to_list(word->GetBlobChoices(index));
if (tessedit_debug_fonts) {
tprintf("Examining fonts in %s\n",
word->best_choice->debug_string().string());
}
for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
choice_it.forward()) {
UNICHAR_ID blob_ch_id = choice_it.data()->unichar_id();
if (blob_ch_id == word_ch_id) {
if (tessedit_debug_fonts) {
tprintf("%s font %s (%d) font2 %s (%d)\n",
word->uch_set->id_to_unichar(blob_ch_id),
choice_it.data()->fontinfo_id() < 0 ? "unknown" :
fontinfo_table_.get(choice_it.data()->fontinfo_id()).name,
choice_it.data()->fontinfo_id(),
choice_it.data()->fontinfo_id2() < 0 ? "unknown" :
fontinfo_table_.get(choice_it.data()->fontinfo_id2()).name,
choice_it.data()->fontinfo_id2());
}
// 1st choice font gets 2 pts, 2nd choice 1 pt.
if (choice_it.data()->fontinfo_id() >= 0) {
fonts.add(choice_it.data()->fontinfo_id(), 2);
}
if (choice_it.data()->fontinfo_id2() >= 0) {
fonts.add(choice_it.data()->fontinfo_id2(), 1);
}
break;
}
}
}
inT16 font_id1, font_id2;
find_modal_font(&fonts, &font_id1, &word->fontinfo_id_count);
find_modal_font(&fonts, &font_id2, &word->fontinfo_id2_count);
word->fontinfo = font_id1 >= 0 ? &fontinfo_table_.get(font_id1) : NULL;
word->fontinfo2 = font_id2 >= 0 ? &fontinfo_table_.get(font_id2) : NULL;
// All the blobs get the word's best choice font.
for (int i = 0; i < word->best_choice->length(); ++i) {
word->best_choice_fontinfo_ids.push_back(font_id1);
}
if (word->fontinfo_id_count > 0) {
FontInfo fi = fontinfo_table_.get(font_id1);
if (tessedit_debug_fonts) {
if (word->fontinfo_id2_count > 0) {
tprintf("Word modal font=%s, score=%d, 2nd choice %s/%d\n",
fi.name, word->fontinfo_id_count,
fontinfo_table_.get(font_id2).name,
word->fontinfo_id2_count);
} else {
tprintf("Word modal font=%s, score=%d. No 2nd choice\n",
fi.name, word->fontinfo_id_count);
}
}
// 1st choices got 2 pts, so we need to halve the score for the mode.
word->italic = (fi.is_italic() ? 1 : -1) * (word->fontinfo_id_count + 1) / 2;
word->bold = (fi.is_bold() ? 1 : -1) * (word->fontinfo_id_count + 1) / 2;
}
}
/**
* font_recognition_pass
*
* Smooth the fonts for the document.
*/
void Tesseract::font_recognition_pass(PAGE_RES* page_res) {
PAGE_RES_IT page_res_it(page_res);
WERD_RES *word; // current word
STATS doc_fonts(0, font_table_size_); // font counters
// Gather font id statistics.
for (page_res_it.restart_page(); page_res_it.word() != NULL;
page_res_it.forward()) {
word = page_res_it.word();
if (word->fontinfo != NULL) {
doc_fonts.add(word->fontinfo->universal_id, word->fontinfo_id_count);
}
if (word->fontinfo2 != NULL) {
doc_fonts.add(word->fontinfo2->universal_id, word->fontinfo_id2_count);
}
}
inT16 doc_font; // modal font
inT8 doc_font_count; // modal font
find_modal_font(&doc_fonts, &doc_font, &doc_font_count);
if (doc_font_count == 0)
return;
// Get the modal font pointer.
const FontInfo* modal_font = NULL;
for (page_res_it.restart_page(); page_res_it.word() != NULL;
page_res_it.forward()) {
word = page_res_it.word();
if (word->fontinfo != NULL && word->fontinfo->universal_id == doc_font) {
modal_font = word->fontinfo;
break;
}
if (word->fontinfo2 != NULL && word->fontinfo2->universal_id == doc_font) {
modal_font = word->fontinfo2;
break;
}
}
ASSERT_HOST(modal_font != NULL);
// Assign modal font to weak words.
for (page_res_it.restart_page(); page_res_it.word() != NULL;
page_res_it.forward()) {
word = page_res_it.word();
int length = word->best_choice->length();
// 1st choices got 2 pts, so we need to halve the score for the mode.
int count = (word->fontinfo_id_count + 1) / 2;
if (!(count == length || (length > 3 && count >= length * 3 / 4))) {
word->fontinfo = modal_font;
// Counts only get 1 as it came from the doc.
word->fontinfo_id_count = 1;
word->italic = modal_font->is_italic() ? 1 : -1;
word->bold = modal_font->is_bold() ? 1 : -1;
}
}
}
// If a word has multiple alternates check if the best choice is in the
// dictionary. If not, replace it with an alternate that exists in the
// dictionary.
void Tesseract::dictionary_correction_pass(PAGE_RES *page_res) {
PAGE_RES_IT word_it(page_res);
for (WERD_RES* word = word_it.word(); word != NULL;
word = word_it.forward()) {
if (word->best_choices.singleton())
continue; // There are no alternates.
WERD_CHOICE* best = word->best_choice;
if (word->tesseract->getDict().valid_word(*best) != 0)
continue; // The best choice is in the dictionary.
WERD_CHOICE_IT choice_it(&word->best_choices);
for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
choice_it.forward()) {
WERD_CHOICE* alternate = choice_it.data();
if (word->tesseract->getDict().valid_word(*alternate)) {
// The alternate choice is in the dictionary.
if (tessedit_bigram_debug) {
tprintf("Dictionary correction replaces best choice '%s' with '%s'\n",
best->unichar_string().string(),
alternate->unichar_string().string());
}
// Replace the 'best' choice with a better choice.
word->ReplaceBestChoice(alternate);
break;
}
}
}
}
} // namespace tesseract
| {'content_hash': 'f0510e1bb5616259c988f48281d1db86', 'timestamp': '', 'source': 'github', 'line_count': 1641, 'max_line_length': 81, 'avg_line_length': 36.948811700182816, 'alnum_prop': 0.5790411162238385, 'repo_name': 'forkch/scrabble_ar', 'id': '13e6a4902e426d5357c8b0f8db6604130539f3f9', 'size': '61610', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'examples/android-ocr/libraries/tess-two/jni/com_googlecode_tesseract_android/src/ccmain/control.cpp', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '20493086'}, {'name': 'C++', 'bytes': '16184510'}, {'name': 'CSS', 'bytes': '165'}, {'name': 'Groff', 'bytes': '91826'}, {'name': 'HTML', 'bytes': '518171'}, {'name': 'Java', 'bytes': '5495590'}, {'name': 'Makefile', 'bytes': '28541'}, {'name': 'PostScript', 'bytes': '7260'}, {'name': 'Python', 'bytes': '4368'}, {'name': 'Shell', 'bytes': '758844'}, {'name': 'TeX', 'bytes': '5482'}]} |
#region Using directives
using System;
using System.Data;
using System.Collections;
using System.Diagnostics;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.ComponentModel;
using Nettiers.AdventureWorks.Entities;
using Nettiers.AdventureWorks.Data;
#endregion
namespace Nettiers.AdventureWorks.Data.WebServiceClient
{
///<summary>
/// This class is the WebServiceClient Data Access Logic Component implementation for the <see cref="ProductProductPhoto"/> entity.
///</summary>
[DataObject]
[CLSCompliant(true)]
public partial class WsProductProductPhotoProvider: WsProductProductPhotoProviderBase
{
/// <summary>
/// Creates a new <see cref="WsProductProductPhotoProvider"/> instance.
/// Uses connection string to connect to datasource.
/// </summary>
/// <param name="url">The url to the nettiers webservice.</param>
public WsProductProductPhotoProvider(string url): base(url){}
}
}
| {'content_hash': 'c6d845011e8d2a55e82ff4756baea99a', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 132, 'avg_line_length': 31.9, 'alnum_prop': 0.7513061650992685, 'repo_name': 'netTiers/netTiers', 'id': '8cee10caacf66d835f0ad0ebed34be637a1cc3f9', 'size': '959', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Samples/AdventureWorks/Generated/Nettiers.AdventureWorks.Data.WebServiceClient/WsProductProductPhotoProvider.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP.NET', 'bytes': '620'}, {'name': 'C#', 'bytes': '336934'}, {'name': 'CSS', 'bytes': '9299'}, {'name': 'JavaScript', 'bytes': '18312'}, {'name': 'XSLT', 'bytes': '26775'}]} |
package com.google.cloud.dataflow.sdk.runners.inprocess;
import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessExecutionContext.InProcessStepContext;
import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.CommittedBundle;
import com.google.cloud.dataflow.sdk.runners.inprocess.InProcessPipelineRunner.UncommittedBundle;
import com.google.cloud.dataflow.sdk.runners.inprocess.ParDoInProcessEvaluator.BundleOutputManager;
import com.google.cloud.dataflow.sdk.transforms.AppliedPTransform;
import com.google.cloud.dataflow.sdk.transforms.DoFn;
import com.google.cloud.dataflow.sdk.transforms.PTransform;
import com.google.cloud.dataflow.sdk.transforms.ParDo.BoundMulti;
import com.google.cloud.dataflow.sdk.util.DoFnRunner;
import com.google.cloud.dataflow.sdk.util.DoFnRunners;
import com.google.cloud.dataflow.sdk.util.common.CounterSet;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.cloud.dataflow.sdk.values.PCollectionTuple;
import com.google.cloud.dataflow.sdk.values.TupleTag;
import java.util.HashMap;
import java.util.Map;
/**
* The {@link InProcessPipelineRunner} {@link TransformEvaluatorFactory} for the
* {@link BoundMulti} primitive {@link PTransform}.
*/
class ParDoMultiEvaluatorFactory implements TransformEvaluatorFactory {
@Override
public <T> TransformEvaluator<T> forApplication(
AppliedPTransform<?, ?, ?> application,
CommittedBundle<?> inputBundle,
InProcessEvaluationContext evaluationContext) {
@SuppressWarnings({"cast", "unchecked", "rawtypes"})
TransformEvaluator<T> evaluator = (TransformEvaluator<T>) createMultiEvaluator(
(AppliedPTransform) application, inputBundle, evaluationContext);
return evaluator;
}
private static <InT, OuT> ParDoInProcessEvaluator<InT> createMultiEvaluator(
AppliedPTransform<PCollection<InT>, PCollectionTuple, BoundMulti<InT, OuT>> application,
CommittedBundle<InT> inputBundle,
InProcessEvaluationContext evaluationContext) {
PCollectionTuple output = application.getOutput();
Map<TupleTag<?>, PCollection<?>> outputs = output.getAll();
Map<TupleTag<?>, UncommittedBundle<?>> outputBundles = new HashMap<>();
for (Map.Entry<TupleTag<?>, PCollection<?>> outputEntry : outputs.entrySet()) {
outputBundles.put(
outputEntry.getKey(),
evaluationContext.createBundle(inputBundle, outputEntry.getValue()));
}
InProcessExecutionContext executionContext =
evaluationContext.getExecutionContext(application, inputBundle.getKey());
String stepName = evaluationContext.getStepName(application);
InProcessStepContext stepContext =
executionContext.getOrCreateStepContext(stepName, stepName, null);
CounterSet counters = evaluationContext.createCounterSet();
DoFn<InT, OuT> fn = application.getTransform().getFn();
DoFnRunner<InT, OuT> runner =
DoFnRunners.createDefault(
evaluationContext.getPipelineOptions(),
fn,
evaluationContext.createSideInputReader(application.getTransform().getSideInputs()),
BundleOutputManager.create(outputBundles),
application.getTransform().getMainOutputTag(),
application.getTransform().getSideOutputTags().getAll(),
stepContext,
counters.getAddCounterMutator(),
application.getInput().getWindowingStrategy());
runner.startBundle();
return new ParDoInProcessEvaluator<>(
runner, application, counters, outputBundles.values(), stepContext);
}
}
| {'content_hash': 'af2a134d2cb3c15555248ae4603fd776', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 102, 'avg_line_length': 47.14473684210526, 'alnum_prop': 0.7585821936924365, 'repo_name': 'shakamunyi/beam', 'id': '1d6563d5cc28a97f618b165e6423a78022a8f328', 'size': '4388', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sdks/java/core/src/main/java/com/google/cloud/dataflow/sdk/runners/inprocess/ParDoMultiEvaluatorFactory.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '146134'}, {'name': 'Groovy', 'bytes': '3274'}, {'name': 'Java', 'bytes': '34540397'}, {'name': 'Protocol Buffer', 'bytes': '137365'}, {'name': 'Python', 'bytes': '4248665'}, {'name': 'Shell', 'bytes': '53893'}]} |
object Test {
object MyEnum extends Enumeration {
val Foo = Value(2000000000)
val Bar = Value(-2000000000)
val X = Value(Integer.MAX_VALUE)
val Y = Value(Integer.MIN_VALUE)
}
import MyEnum.*
def main(args: Array[String]): Unit = {
println(Foo > Bar)
println(X > Y)
}
}
| {'content_hash': 'ab5cc2bc69f10cbb945ec0f63cfe2caa', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 41, 'avg_line_length': 22.0, 'alnum_prop': 0.6168831168831169, 'repo_name': 'dotty-staging/dotty', 'id': '090c147e4bb42004e51e1d1f9d6f848c5e5dd6da', 'size': '308', 'binary': False, 'copies': '3', 'ref': 'refs/heads/main', 'path': 'tests/run/t5588.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '836'}, {'name': 'CSS', 'bytes': '136099'}, {'name': 'HTML', 'bytes': '3463'}, {'name': 'Java', 'bytes': '227667'}, {'name': 'JavaScript', 'bytes': '153556'}, {'name': 'Scala', 'bytes': '17956546'}, {'name': 'Shell', 'bytes': '23230'}, {'name': 'TypeScript', 'bytes': '8378'}]} |
<body>
<script language="javascript">
function checkMe() {
if (confirm("Are you sure you want to delete the Job?")) {
return true;
} else {
return false;
}
}
function link_create() {
var f1 = document.getElementById("job_title");
var f2 = document.getElementById("job_page_url");
f2.value = string_to_slug(f1.value);
}
function string_to_slug(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
var to = "aaaaeeeeiiiioooouuuunc------";
for (var i = 0, l = from.length; i < l; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
var url = window.base_url = <?php echo json_encode(base_url()); ?>;
return url + 'jobs/' + str;
}
</script>
<div id="wrapper">
<?php $this->load->view('admin/admin_dashboard_navbar_view'); ?>
<div id="page-wrapper">
<div class="container-fluid">
<!-- Page Heading -->
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">
<?php echo $common_header; ?>
</h1>
<ol class="breadcrumb">
<li>
<i class="fa fa-dashboard"></i> <a href="<?php echo base_url(); ?>admin">Dashboard</a>
</li>
<li class="active">
<i class="fa fa-edit"></i> <?php echo $common_header; ?>
</li>
</ol>
</div>
</div>
<!-- /.row -->
<div class="row">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title"> <?php echo $common_header; ?></h3>
</div>
<form name='add_project_cat_form' id='add_project_cat_form' enctype="multipart/form-data"
class="form-horizontal form-widgets" role="form" method="POST" action="">
<div class="panel-body">
<div class="form-group">
<div class="col-md-12">
<fieldset>
<?php if (validation_errors()) { ?>
<div class="form-group">
<div class="col-md-8">
<div class="alert alert-danger" role="alert">
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a>
<?php echo validation_errors(); ?>
</div>
</div>
</div>
<?php }
if ($this->session->flashdata('add_success')) { ?>
<div class="form-group">
<div class="col-md-8">
<div class="alert alert-success" role="alert">
<i class="fa fa-check"></i>
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a>
<?php echo $this->session->flashdata('add_success'); ?>
</div>
</div>
</div>
<?php }
if ($this->session->flashdata('job_update_message')) { ?>
<div class="form-group">
<div class="col-md-8">
<div class="alert alert-success" role="alert">
<i class="fa fa-check"></i>
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a>
<?php echo $this->session->flashdata('job_update_message'); ?>
</div>
</div>
</div>
<?php }
if ($this->session->flashdata('cant_delete_message')) { ?>
<div class="form-group">
<div class="col-md-8">
<div class="alert alert-warning" role="alert">
<i class="fa fa-exclamation-triangle"></i>
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a>
<?php echo $this->session->flashdata('cant_delete_message'); ?>
</div>
</div>
</div>
<?php }
if ($this->session->flashdata('job_delete_message')) { ?>
<div class="form-group">
<div class="col-md-8">
<div class="alert alert-success" role="alert">
<i class="fa fa-check"></i>
<a href="#" class="close" data-dismiss="alert"
aria-label="close">×</a>
<?php echo $this->session->flashdata('job_delete_message'); ?>
</div>
</div>
</div>
<?php }
?>
<div class="form-group">
<label class="col-md-3 control-label" for="job_type">Job Type:</label>
<div class="col-md-5">
<select class="form-control" name="job_type"
id="job_type" title="Select a Job Type" required autofocus>
<option selected>Please Select a Job Type</option>
<option value="Full Time">Full Time</option>
<option value="Part Time">Part Time</option>
<option value="Contractual">Contractual</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="job_title">Job
Title:</label>
<div class="col-md-5">
<input type="text" class="form-control" name="job_title"
onblur="link_create()"
id="job_title" placeholder="Job Title" required/>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="job_page_url">Job Page URL:</label>
<div class="col-md-5">
<input type="url" class="form-control" name="job_page_url"
id="job_page_url"
placeholder="Write Job Page URL" required/>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="job_short_description">Job Short
Description:</label>
<div class="col-md-5">
<textarea type="text" class="form-control" id="job_short_description"
name="job_short_description" rows="3"
placeholder="Job Short Description" required></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="job_experience">Job Experience:</label>
<div class="col-md-5">
<textarea type="text" class="form-control" id="job_experience"
name="job_experience" rows="3"
placeholder="Job Experience" required></textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="working_hour">Working Hour:</label>
<div class="col-md-5">
<input type="text" class="form-control" name="working_hour"
id="working_hour"
placeholder="Write Job Working Hour" required/>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="job_salary">Job Salary:</label>
<div class="col-md-5">
<input type="text" class="form-control" name="job_salary"
id="job_salary"
placeholder="Write Job Salary" required/>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="job_application_deadline">Job Application Deadline:</label>
<div class="col-md-5">
<input type="text" name="job_application_deadline" class="form-control"
placeholder="Click to pick Job application deadline"
id="job_application_deadline" required/>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="other_conditions">Other Job Conditions:</label>
<div class="col-md-5">
<input type="text" name="other_conditions" class="form-control"
placeholder="Write other conditions of the job"
id="other_conditions"/>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label label-optional"
for="is_active">Is Active:</label>
<div class="col-md-1">
<div class="checkbox">
<input type="checkbox" id="is_active"
name="is_active" value="1"/>
</div>
</div>
</div>
</fieldset>
</div>
</div>
</div>
<div class="panel-footer panel-success">
<button id="update" name="update" type="submit" data-role="button"
class="btn btn-submit btn-success"><span class="glyphicon glyphicon-plus"></span>Create
</button>
<button id="clearFormButton" name="clearFormButton" type="reset"
class="btn btn-submit btn-danger"><span class="glyphicon glyphicon-remove"></span>Cancel
</button>
</div>
</form>
</div>
<!-- /.row -->
</div>
<div class="row row-fluid">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $list_title; ?></h3>
</div>
<div class="panel-body">
<div class="form-group">
<div class="col-lg-12">
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Serial</th>
<th>Job Title</th>
<th>Job Page URL</th>
<th>Job Short Description</th>
<th>Job Type</th>
<th>Job Application Deadline</th>
<th>Is Active</th>
<th>Action</th>
</tr>
</thead>
<?php $i = $start_from;
$start = 0; ?>
<?php if (isset($all_jobs) && $all_jobs->num_rows() > 0): ?>
<?php foreach ($all_jobs->result() as $row):
?>
<tbody>
<tr>
<td align="center"><?php echo $i + $start; ?></td>
<td><?php echo $row->job_title; ?></td>
<td><?php echo $row->job_page_url; ?></td>
<td><?php echo $row->job_short_description; ?></td>
<td><?php echo $row->job_type; ?></td>
<td><?php echo $row->job_application_deadline; ?></td>
<td align="center"><?php echo $row->is_active ? 'Yes' : 'No'; ?></td>
<td align="center"><a class="btn btn-success" title="Edit"
href="<?php echo base_url(); ?>admin/update/job/<?php echo base64_encode($row->job_id); ?>"
role="button"><span
class="glyphicon glyphicon-edit"></span></a>
<a class="btn btn-danger"
href="<?php echo base_url(); ?>admin/delete/job/<?php echo base64_encode($row->job_id); ?>"
onclick="return checkMe()" title="Delete"
role="button"><span class="glyphicon glyphicon-trash"></span></a>
</td>
</tr>
</tbody> <?php $i++; ?>
<?php endforeach; ?>
</table>
<div class="pagination" style="float:right;"> <?php echo $paginglinks; ?></div>
<div class="pagination"
style="float:left;"> <?php echo(!empty($pagermessage) ? $pagermessage : ''); ?></div>
<?php else: ?>
<div class="col-md-12">
<div class="alert alert-info " role="alert">
No Results were found.
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<!-- jQuery -->
<script src="<?php echo base_url(); ?>js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="<?php echo base_url(); ?>js/bootstrap.min.js"></script>
<script src="<?php echo base_url(); ?>js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
// When the document is ready
$(document).ready(function () {
$('#job_application_deadline').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
</body> | {'content_hash': 'ce5f98d75be83ce03ab86d720faaff07', 'timestamp': '', 'source': 'github', 'line_count': 354, 'max_line_length': 161, 'avg_line_length': 57.5225988700565, 'alnum_prop': 0.30462112655306195, 'repo_name': 'arafat19/newsdil', 'id': 'c99e031684bb4f1c183182f271029ee692dcb714', 'size': '20387', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/views/admin/admin_add_job_view.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '419'}, {'name': 'CSS', 'bytes': '216912'}, {'name': 'HTML', 'bytes': '5538430'}, {'name': 'JavaScript', 'bytes': '3302786'}, {'name': 'PHP', 'bytes': '3063870'}]} |
using System;
using System.Collections.Generic;
namespace CocosInjector.InjectorHost.Extensions
{
public static class EnumerableExtensions
{
public static void ForEach<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> kvps,
Action<TKey, TValue> action)
{
foreach (var kvp in kvps)
action(kvp.Key, kvp.Value);
}
public static void ForEach<T>(this IEnumerable<T> objs, Action<T> action)
{
foreach (var obj in objs)
action(obj);
}
}
} | {'content_hash': 'f9876ddbfb1426effaf0dfc324a2302f', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 99, 'avg_line_length': 27.19047619047619, 'alnum_prop': 0.5971978984238179, 'repo_name': 'rdavisau/cocossharp-injector', 'id': '9642bb8efd2fce04dadc3c6273747cbb77b51942', 'size': '573', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CocosInjector.InjectorHost/Extensions/EnumerableExtensions.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '11583'}]} |
module.exports = {
master: {
product: require('./data-util/master/product-data-util'),
holiday: require('./data-util/master/holiday-data-util'),
uom: require('./data-util/master/uom-data-util'),
vat: require('./data-util/master/vat-data-util'),
currency: require('./data-util/master/currency-data-util'),
buyer: require('./data-util/master/buyer-data-util'),
budget: require('./data-util/master/budget-data-util'),
supplier: require('./data-util/master/supplier-data-util'),
unit: require('./data-util/master/unit-data-util'),
machine: require('./data-util/master/machine-data-util'),
//lotMachine: require('./data-util/master/lot-machine-data-util'),
category: require('./data-util/master/category-data-util'),
lampStandard: require('./data-util/master/lamp-standard-data-util'),
instruction: require('./data-util/master/instruction-data-util'),
orderType: require('./data-util/master/order-type-data-util'),
processType: require('./data-util/master/process-type-data-util'),
colorType: require('./data-util/master/color-type-data-util'),
machineType: require('./data-util/master/machine-type-data-util'),
machineEvent: require('./data-util/master/machine-event-data-util'),
comodity: require('./data-util/master/comodity-data-util'),
quality: require('./data-util/master/quality-data-util'),
termOfPayment: require('./data-util/master/term-of-payment-data-util'),
company: require('./data-util/master/company-data-util'),
contact: require('./data-util/master/contact-data-util'),
kursBudget: require('./data-util/master/kurs-budget-data-util')
},
purchasing:{
purchaseRequest: require('./data-util/purchasing/purchase-request-data-util'),
purchaseOrder: require('./data-util/purchasing/purchase-order-data-util'),
purchaseOrderExternal: require('./data-util/purchasing/purchase-order-external-data-util'),
},
transaction: {
deliveryOrder: require('./data-util/transaction/delivery-order-data-util'),
unitReceiptNote: require('./data-util/transaction/unit-receipt-note-data-util'),
unitPaymentOrder: require('./data-util/transaction/unit-payment-order-data-util'),
unitPaymentPriceCorrectionNote: require('./data-util/transaction/unit-payment-price-correction-note-data-util'),
unitPaymentQuantityCorrectionNote: require('./data-util/transaction/unit-payment-quantity-correction-note-data-util')
},
production: {
monitoringEvent: require('./data-util/production/finishing-printing/monitoring-event-data-util'),
monitoringSpecificationMachine: require('./data-util/production/finishing-printing/monitoring-specification-machine-data-util'),
kanban: require('./data-util/production/finishing-printing/kanban-data-util')
},
sales: {
productionOrder: require('./data-util/sales/production-order-data-util'),
dealTrackingBoard: require('./data-util/sales/deal-tracking-board-data-util'),
dealTrackingStage: require('./data-util/sales/deal-tracking-stage-data-util'),
dealTrackingDeal: require('./data-util/sales/deal-tracking-deal-data-util'),
dealTrackingActivity: require('./data-util/sales/deal-tracking-activity-data-util')
},
}; | {'content_hash': '372e4b9654e003f7e48bc81fd1277b1c', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 136, 'avg_line_length': 61.872727272727275, 'alnum_prop': 0.6843961210696444, 'repo_name': 'baguswidypriyono/dl-module', 'id': '1674032c7ac5637e1eea4961fc908514d1ada242', 'size': '3403', 'binary': False, 'copies': '4', 'ref': 'refs/heads/dev', 'path': 'test/data.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '4618447'}]} |
package org.wikipedia.zero;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.shadows.ShadowApplication;
import org.wikipedia.test.ImmediateExecutor;
import org.wikipedia.test.TestApi;
import org.wikipedia.test.TestFileUtil;
import org.wikipedia.test.TestLatch;
import org.wikipedia.test.TestRunner;
import org.wikipedia.test.TestWebServer;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
@RunWith(TestRunner.class)
public class WikipediaZeroTaskTest {
private TestWebServer server = new TestWebServer();
@Before
public void setUp() throws Exception {
server.setUp();
}
@After
public void tearDown() throws Exception {
server.tearDown();
}
@Test
public void testOnFinish_ineligible() throws Exception {
testOnFinish("{}", null);
}
@Test
public void testOnFinish_eligible() throws Exception {
testOnFinish(TestFileUtil.readRawFile("wikipedia_zero_task_test_eligible.json"),
new ZeroMessage("Overstay your stay!", "#FFFFFF", "#00FFFF"));
}
private void testOnFinish(String responseBody,
@Nullable ZeroMessage expected) throws Exception {
TestLatch latch = new TestLatch();
Subject subject = new Subject(latch, expected);
server.enqueue(responseBody);
subject.execute();
ShadowApplication.runBackgroundTasks();
server.takeRequest();
latch.await();
}
private class Subject extends WikipediaZeroTask {
@NonNull
private final TestLatch latch;
@Nullable
private final ZeroMessage expected;
public Subject(@NonNull TestLatch latch, @Nullable ZeroMessage expected) {
super(new ImmediateExecutor(), new TestApi(server), "userAgent");
this.latch = latch;
this.expected = expected;
}
@Override
public void onFinish(ZeroMessage result) {
super.onFinish(result);
assertThat(result, is(expected));
latch.countDown();
}
}
}
| {'content_hash': '7d495bdec5685864c87099301c035fab', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 88, 'avg_line_length': 28.3625, 'alnum_prop': 0.6712208021154694, 'repo_name': 'reproio/apps-android-wikipedia', 'id': 'c46f2eb796a9c458e7774ffe2a25bacf7b77452e', 'size': '2269', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'wikipedia/src/test/java/org/wikipedia/zero/WikipediaZeroTaskTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '56929'}, {'name': 'HTML', 'bytes': '2666'}, {'name': 'Java', 'bytes': '1266636'}, {'name': 'JavaScript', 'bytes': '149604'}, {'name': 'Python', 'bytes': '21239'}, {'name': 'Shell', 'bytes': '976'}]} |
ALTER TABLE `addons` ADD COLUMN `reputation` smallint;
| {'content_hash': '1a08e03130fec1d431ee300d80db36bf', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 54, 'avg_line_length': 55.0, 'alnum_prop': 0.7818181818181819, 'repo_name': 'kumar303/olympia', 'id': '09de04194acecbc0d3520a3bc198e16d7c324079', 'size': '55', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'src/olympia/migrations/949-add-addon-reputation.sql', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '249'}, {'name': 'CSS', 'bytes': '663668'}, {'name': 'HTML', 'bytes': '1600995'}, {'name': 'JavaScript', 'bytes': '1314186'}, {'name': 'Makefile', 'bytes': '4235'}, {'name': 'PLSQL', 'bytes': '74'}, {'name': 'Python', 'bytes': '3999917'}, {'name': 'Shell', 'bytes': '9101'}, {'name': 'Smarty', 'bytes': '1930'}]} |
<?php
use Symfony\Component\Console\Tester\ApplicationTester;
require_once 'PHPUnit/Autoload.php';
require_once 'PHPUnit/Framework/Assert/Functions.php';
trait ApplicationContext
{
/**
* @var ApplicationTester|null
*/
private $applicationTester = null;
protected $inputFile;
protected $outputFile;
/**
* @When /^I run "([^"]*)"$/
*/
public function iRun($command)
{
$status = $this->run($command);
if ($status !== 0) {
throw new FailedCommandException($this->applicationTester->getDisplay());
}
}
/**
* @Then /^I should see "(?P<message>[^"]*)"$/
*/
public function iShouldSee($message)
{
assertRegExp('/'.preg_quote($message, '/').'/sm', $this->applicationTester->getDisplay());
}
/**
* @return \Symfony\Component\Console\Application
*/
abstract protected function createApplication();
/**
* @param string $command
*
* @return integer
*/
private function run($command)
{
$application = $this->createApplication();
$application->setAutoExit(false);
$this->applicationTester = new ApplicationTester($application);
$this->outputFile = tempnam('.', 'phpeg');
return $this->applicationTester->run(array(
'command' => $command,
'input-file' => $this->inputFile,
'output-file' => $this->outputFile
));
}
}
| {'content_hash': 'f06a0e23d82023e3f94f207b7e94f26f', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 98, 'avg_line_length': 23.365079365079364, 'alnum_prop': 0.5740489130434783, 'repo_name': 'scato/phpeg', 'id': '36a163a04505b42223698254467a3b69edb95e83', 'size': '1472', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'features/bootstrap/ApplicationContext.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Cucumber', 'bytes': '13485'}, {'name': 'PHP', 'bytes': '175095'}]} |
"""Support for TPLink HS100/HS110/HS200 smart switch energy sensors."""
from __future__ import annotations
from dataclasses import dataclass
from typing import cast
from kasa import SmartDevice
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_VOLTAGE,
ELECTRIC_CURRENT_AMPERE,
ELECTRIC_POTENTIAL_VOLT,
ENERGY_KILO_WATT_HOUR,
POWER_WATT,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from . import legacy_device_id
from .const import (
ATTR_CURRENT_A,
ATTR_CURRENT_POWER_W,
ATTR_TODAY_ENERGY_KWH,
ATTR_TOTAL_ENERGY_KWH,
DOMAIN,
)
from .coordinator import TPLinkDataUpdateCoordinator
from .entity import CoordinatedTPLinkEntity
@dataclass
class TPLinkSensorEntityDescription(SensorEntityDescription):
"""Describes TPLink sensor entity."""
emeter_attr: str | None = None
precision: int | None = None
ENERGY_SENSORS: tuple[TPLinkSensorEntityDescription, ...] = (
TPLinkSensorEntityDescription(
key=ATTR_CURRENT_POWER_W,
native_unit_of_measurement=POWER_WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
name="Current Consumption",
emeter_attr="power",
precision=1,
),
TPLinkSensorEntityDescription(
key=ATTR_TOTAL_ENERGY_KWH,
native_unit_of_measurement=ENERGY_KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
name="Total Consumption",
emeter_attr="total",
precision=3,
),
TPLinkSensorEntityDescription(
key=ATTR_TODAY_ENERGY_KWH,
native_unit_of_measurement=ENERGY_KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
name="Today's Consumption",
precision=3,
),
TPLinkSensorEntityDescription(
key=ATTR_VOLTAGE,
native_unit_of_measurement=ELECTRIC_POTENTIAL_VOLT,
device_class=SensorDeviceClass.VOLTAGE,
state_class=SensorStateClass.MEASUREMENT,
name="Voltage",
emeter_attr="voltage",
precision=1,
),
TPLinkSensorEntityDescription(
key=ATTR_CURRENT_A,
native_unit_of_measurement=ELECTRIC_CURRENT_AMPERE,
device_class=SensorDeviceClass.CURRENT,
state_class=SensorStateClass.MEASUREMENT,
name="Current",
emeter_attr="current",
precision=2,
),
)
def async_emeter_from_device(
device: SmartDevice, description: TPLinkSensorEntityDescription
) -> float | None:
"""Map a sensor key to the device attribute."""
if attr := description.emeter_attr:
if (val := getattr(device.emeter_realtime, attr)) is None:
return None
return round(cast(float, val), description.precision)
# ATTR_TODAY_ENERGY_KWH
if (emeter_today := device.emeter_today) is not None:
return round(cast(float, emeter_today), description.precision)
# today's consumption not available, when device was off all the day
# bulb's do not report this information, so filter it out
return None if device.is_bulb else 0.0
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up sensors."""
coordinator: TPLinkDataUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
entities: list[SmartPlugSensor] = []
parent = coordinator.device
if not parent.has_emeter:
return
def _async_sensors_for_device(device: SmartDevice) -> list[SmartPlugSensor]:
return [
SmartPlugSensor(device, coordinator, description)
for description in ENERGY_SENSORS
if async_emeter_from_device(device, description) is not None
]
if parent.is_strip:
# Historically we only add the children if the device is a strip
for child in parent.children:
entities.extend(_async_sensors_for_device(child))
else:
entities.extend(_async_sensors_for_device(parent))
async_add_entities(entities)
class SmartPlugSensor(CoordinatedTPLinkEntity, SensorEntity):
"""Representation of a TPLink Smart Plug energy sensor."""
entity_description: TPLinkSensorEntityDescription
def __init__(
self,
device: SmartDevice,
coordinator: TPLinkDataUpdateCoordinator,
description: TPLinkSensorEntityDescription,
) -> None:
"""Initialize the switch."""
super().__init__(device, coordinator)
self.entity_description = description
self._attr_unique_id = (
f"{legacy_device_id(self.device)}_{self.entity_description.key}"
)
@property
def name(self) -> str:
"""Return the name of the Smart Plug.
Overridden to include the description.
"""
return f"{self.device.alias} {self.entity_description.name}"
@property
def native_value(self) -> float | None:
"""Return the sensors state."""
return async_emeter_from_device(self.device, self.entity_description)
| {'content_hash': '01ca7e622a7acef2b119c0ecc3a5d364', 'timestamp': '', 'source': 'github', 'line_count': 169, 'max_line_length': 87, 'avg_line_length': 31.78698224852071, 'alnum_prop': 0.6826135517498139, 'repo_name': 'toddeye/home-assistant', 'id': '7ba28702114b40d0f15037bb4dc5fae8831ad303', 'size': '5372', 'binary': False, 'copies': '4', 'ref': 'refs/heads/dev', 'path': 'homeassistant/components/tplink/sensor.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '3005'}, {'name': 'PLSQL', 'bytes': '840'}, {'name': 'Python', 'bytes': '47414832'}, {'name': 'Shell', 'bytes': '6252'}]} |
'use strict';
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('pdfjs/core/cff_parser', ['exports', 'pdfjs/shared/util',
'pdfjs/core/charsets', 'pdfjs/core/encodings'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('../shared/util.js'), require('./charsets.js'),
require('./encodings.js'));
} else {
factory((root.pdfjsCoreCFFParser = {}), root.pdfjsSharedUtil,
root.pdfjsCoreCharsets, root.pdfjsCoreEncodings);
}
}(this, function (exports, sharedUtil, coreCharsets, coreEncodings) {
var error = sharedUtil.error;
var info = sharedUtil.info;
var bytesToString = sharedUtil.bytesToString;
var warn = sharedUtil.warn;
var isArray = sharedUtil.isArray;
var Util = sharedUtil.Util;
var stringToBytes = sharedUtil.stringToBytes;
var assert = sharedUtil.assert;
var ISOAdobeCharset = coreCharsets.ISOAdobeCharset;
var ExpertCharset = coreCharsets.ExpertCharset;
var ExpertSubsetCharset = coreCharsets.ExpertSubsetCharset;
var StandardEncoding = coreEncodings.StandardEncoding;
var ExpertEncoding = coreEncodings.ExpertEncoding;
// Maximum subroutine call depth of type 2 chartrings. Matches OTS.
var MAX_SUBR_NESTING = 10;
/**
* The CFF class takes a Type1 file and wrap it into a
* 'Compact Font Format' which itself embed Type2 charstrings.
*/
var CFFStandardStrings = [
'.notdef', 'space', 'exclam', 'quotedbl', 'numbersign', 'dollar', 'percent',
'ampersand', 'quoteright', 'parenleft', 'parenright', 'asterisk', 'plus',
'comma', 'hyphen', 'period', 'slash', 'zero', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine', 'colon', 'semicolon', 'less',
'equal', 'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', 'bracketleft', 'backslash', 'bracketright', 'asciicircum',
'underscore', 'quoteleft', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', 'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown', 'cent',
'sterling', 'fraction', 'yen', 'florin', 'section', 'currency',
'quotesingle', 'quotedblleft', 'guillemotleft', 'guilsinglleft',
'guilsinglright', 'fi', 'fl', 'endash', 'dagger', 'daggerdbl',
'periodcentered', 'paragraph', 'bullet', 'quotesinglbase', 'quotedblbase',
'quotedblright', 'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve', 'dotaccent',
'dieresis', 'ring', 'cedilla', 'hungarumlaut', 'ogonek', 'caron', 'emdash',
'AE', 'ordfeminine', 'Lslash', 'Oslash', 'OE', 'ordmasculine', 'ae',
'dotlessi', 'lslash', 'oslash', 'oe', 'germandbls', 'onesuperior',
'logicalnot', 'mu', 'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
'onequarter', 'divide', 'brokenbar', 'degree', 'thorn', 'threequarters',
'twosuperior', 'registered', 'minus', 'eth', 'multiply', 'threesuperior',
'copyright', 'Aacute', 'Acircumflex', 'Adieresis', 'Agrave', 'Aring',
'Atilde', 'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde', 'Oacute',
'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde', 'Scaron', 'Uacute',
'Ucircumflex', 'Udieresis', 'Ugrave', 'Yacute', 'Ydieresis', 'Zcaron',
'aacute', 'acircumflex', 'adieresis', 'agrave', 'aring', 'atilde',
'ccedilla', 'eacute', 'ecircumflex', 'edieresis', 'egrave', 'iacute',
'icircumflex', 'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
'odieresis', 'ograve', 'otilde', 'scaron', 'uacute', 'ucircumflex',
'udieresis', 'ugrave', 'yacute', 'ydieresis', 'zcaron', 'exclamsmall',
'Hungarumlautsmall', 'dollaroldstyle', 'dollarsuperior', 'ampersandsmall',
'Acutesmall', 'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
'sevenoldstyle', 'eightoldstyle', 'nineoldstyle', 'commasuperior',
'threequartersemdash', 'periodsuperior', 'questionsmall', 'asuperior',
'bsuperior', 'centsuperior', 'dsuperior', 'esuperior', 'isuperior',
'lsuperior', 'msuperior', 'nsuperior', 'osuperior', 'rsuperior', 'ssuperior',
'tsuperior', 'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall', 'Bsmall',
'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall', 'Hsmall', 'Ismall',
'Jsmall', 'Ksmall', 'Lsmall', 'Msmall', 'Nsmall', 'Osmall', 'Psmall',
'Qsmall', 'Rsmall', 'Ssmall', 'Tsmall', 'Usmall', 'Vsmall', 'Wsmall',
'Xsmall', 'Ysmall', 'Zsmall', 'colonmonetary', 'onefitted', 'rupiah',
'Tildesmall', 'exclamdownsmall', 'centoldstyle', 'Lslashsmall',
'Scaronsmall', 'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall', 'oneeighth',
'threeeighths', 'fiveeighths', 'seveneighths', 'onethird', 'twothirds',
'zerosuperior', 'foursuperior', 'fivesuperior', 'sixsuperior',
'sevensuperior', 'eightsuperior', 'ninesuperior', 'zeroinferior',
'oneinferior', 'twoinferior', 'threeinferior', 'fourinferior',
'fiveinferior', 'sixinferior', 'seveninferior', 'eightinferior',
'nineinferior', 'centinferior', 'dollarinferior', 'periodinferior',
'commainferior', 'Agravesmall', 'Aacutesmall', 'Acircumflexsmall',
'Atildesmall', 'Adieresissmall', 'Aringsmall', 'AEsmall', 'Ccedillasmall',
'Egravesmall', 'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
'Igravesmall', 'Iacutesmall', 'Icircumflexsmall', 'Idieresissmall',
'Ethsmall', 'Ntildesmall', 'Ogravesmall', 'Oacutesmall', 'Ocircumflexsmall',
'Otildesmall', 'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall', 'Yacutesmall',
'Thornsmall', 'Ydieresissmall', '001.000', '001.001', '001.002', '001.003',
'Black', 'Bold', 'Book', 'Light', 'Medium', 'Regular', 'Roman', 'Semibold'
];
var CFFParser = (function CFFParserClosure() {
var CharstringValidationData = [
null,
{ id: 'hstem', min: 2, stackClearing: true, stem: true },
null,
{ id: 'vstem', min: 2, stackClearing: true, stem: true },
{ id: 'vmoveto', min: 1, stackClearing: true },
{ id: 'rlineto', min: 2, resetStack: true },
{ id: 'hlineto', min: 1, resetStack: true },
{ id: 'vlineto', min: 1, resetStack: true },
{ id: 'rrcurveto', min: 6, resetStack: true },
null,
{ id: 'callsubr', min: 1, undefStack: true },
{ id: 'return', min: 0, undefStack: true },
null, // 12
null,
{ id: 'endchar', min: 0, stackClearing: true },
null,
null,
null,
{ id: 'hstemhm', min: 2, stackClearing: true, stem: true },
{ id: 'hintmask', min: 0, stackClearing: true },
{ id: 'cntrmask', min: 0, stackClearing: true },
{ id: 'rmoveto', min: 2, stackClearing: true },
{ id: 'hmoveto', min: 1, stackClearing: true },
{ id: 'vstemhm', min: 2, stackClearing: true, stem: true },
{ id: 'rcurveline', min: 8, resetStack: true },
{ id: 'rlinecurve', min: 8, resetStack: true },
{ id: 'vvcurveto', min: 4, resetStack: true },
{ id: 'hhcurveto', min: 4, resetStack: true },
null, // shortint
{ id: 'callgsubr', min: 1, undefStack: true },
{ id: 'vhcurveto', min: 4, resetStack: true },
{ id: 'hvcurveto', min: 4, resetStack: true }
];
var CharstringValidationData12 = [
null,
null,
null,
{ id: 'and', min: 2, stackDelta: -1 },
{ id: 'or', min: 2, stackDelta: -1 },
{ id: 'not', min: 1, stackDelta: 0 },
null,
null,
null,
{ id: 'abs', min: 1, stackDelta: 0 },
{ id: 'add', min: 2, stackDelta: -1,
stackFn: function stack_div(stack, index) {
stack[index - 2] = stack[index - 2] + stack[index - 1];
}
},
{ id: 'sub', min: 2, stackDelta: -1,
stackFn: function stack_div(stack, index) {
stack[index - 2] = stack[index - 2] - stack[index - 1];
}
},
{ id: 'div', min: 2, stackDelta: -1,
stackFn: function stack_div(stack, index) {
stack[index - 2] = stack[index - 2] / stack[index - 1];
}
},
null,
{ id: 'neg', min: 1, stackDelta: 0,
stackFn: function stack_div(stack, index) {
stack[index - 1] = -stack[index - 1];
}
},
{ id: 'eq', min: 2, stackDelta: -1 },
null,
null,
{ id: 'drop', min: 1, stackDelta: -1 },
null,
{ id: 'put', min: 2, stackDelta: -2 },
{ id: 'get', min: 1, stackDelta: 0 },
{ id: 'ifelse', min: 4, stackDelta: -3 },
{ id: 'random', min: 0, stackDelta: 1 },
{ id: 'mul', min: 2, stackDelta: -1,
stackFn: function stack_div(stack, index) {
stack[index - 2] = stack[index - 2] * stack[index - 1];
}
},
null,
{ id: 'sqrt', min: 1, stackDelta: 0 },
{ id: 'dup', min: 1, stackDelta: 1 },
{ id: 'exch', min: 2, stackDelta: 0 },
{ id: 'index', min: 2, stackDelta: 0 },
{ id: 'roll', min: 3, stackDelta: -2 },
null,
null,
null,
{ id: 'hflex', min: 7, resetStack: true },
{ id: 'flex', min: 13, resetStack: true },
{ id: 'hflex1', min: 9, resetStack: true },
{ id: 'flex1', min: 11, resetStack: true }
];
function CFFParser(file, properties, seacAnalysisEnabled) {
this.bytes = file.getBytes();
this.properties = properties;
this.seacAnalysisEnabled = !!seacAnalysisEnabled;
}
CFFParser.prototype = {
parse: function CFFParser_parse() {
var properties = this.properties;
var cff = new CFF();
this.cff = cff;
// The first five sections must be in order, all the others are reached
// via offsets contained in one of the below.
var header = this.parseHeader();
var nameIndex = this.parseIndex(header.endPos);
var topDictIndex = this.parseIndex(nameIndex.endPos);
var stringIndex = this.parseIndex(topDictIndex.endPos);
var globalSubrIndex = this.parseIndex(stringIndex.endPos);
var topDictParsed = this.parseDict(topDictIndex.obj.get(0));
var topDict = this.createDict(CFFTopDict, topDictParsed, cff.strings);
cff.header = header.obj;
cff.names = this.parseNameIndex(nameIndex.obj);
cff.strings = this.parseStringIndex(stringIndex.obj);
cff.topDict = topDict;
cff.globalSubrIndex = globalSubrIndex.obj;
this.parsePrivateDict(cff.topDict);
cff.isCIDFont = topDict.hasName('ROS');
var charStringOffset = topDict.getByName('CharStrings');
var charStringIndex = this.parseIndex(charStringOffset).obj;
var fontMatrix = topDict.getByName('FontMatrix');
if (fontMatrix) {
properties.fontMatrix = fontMatrix;
}
var fontBBox = topDict.getByName('FontBBox');
if (fontBBox) {
// adjusting ascent/descent
properties.ascent = Math.max(fontBBox[3], fontBBox[1]);
properties.descent = Math.min(fontBBox[1], fontBBox[3]);
properties.ascentScaled = true;
}
var charset, encoding;
if (cff.isCIDFont) {
var fdArrayIndex = this.parseIndex(topDict.getByName('FDArray')).obj;
for (var i = 0, ii = fdArrayIndex.count; i < ii; ++i) {
var dictRaw = fdArrayIndex.get(i);
var fontDict = this.createDict(CFFTopDict, this.parseDict(dictRaw),
cff.strings);
this.parsePrivateDict(fontDict);
cff.fdArray.push(fontDict);
}
// cid fonts don't have an encoding
encoding = null;
charset = this.parseCharsets(topDict.getByName('charset'),
charStringIndex.count, cff.strings, true);
cff.fdSelect = this.parseFDSelect(topDict.getByName('FDSelect'),
charStringIndex.count);
} else {
charset = this.parseCharsets(topDict.getByName('charset'),
charStringIndex.count, cff.strings, false);
encoding = this.parseEncoding(topDict.getByName('Encoding'),
properties,
cff.strings, charset.charset);
}
cff.charset = charset;
cff.encoding = encoding;
var charStringsAndSeacs = this.parseCharStrings(
charStringIndex,
topDict.privateDict.subrsIndex,
globalSubrIndex.obj,
cff.fdSelect,
cff.fdArray);
cff.charStrings = charStringsAndSeacs.charStrings;
cff.seacs = charStringsAndSeacs.seacs;
cff.widths = charStringsAndSeacs.widths;
return cff;
},
parseHeader: function CFFParser_parseHeader() {
var bytes = this.bytes;
var bytesLength = bytes.length;
var offset = 0;
// Prevent an infinite loop, by checking that the offset is within the
// bounds of the bytes array. Necessary in empty, or invalid, font files.
while (offset < bytesLength && bytes[offset] !== 1) {
++offset;
}
if (offset >= bytesLength) {
error('Invalid CFF header');
} else if (offset !== 0) {
info('cff data is shifted');
bytes = bytes.subarray(offset);
this.bytes = bytes;
}
var major = bytes[0];
var minor = bytes[1];
var hdrSize = bytes[2];
var offSize = bytes[3];
var header = new CFFHeader(major, minor, hdrSize, offSize);
return { obj: header, endPos: hdrSize };
},
parseDict: function CFFParser_parseDict(dict) {
var pos = 0;
function parseOperand() {
var value = dict[pos++];
if (value === 30) {
return parseFloatOperand();
} else if (value === 28) {
value = dict[pos++];
value = ((value << 24) | (dict[pos++] << 16)) >> 16;
return value;
} else if (value === 29) {
value = dict[pos++];
value = (value << 8) | dict[pos++];
value = (value << 8) | dict[pos++];
value = (value << 8) | dict[pos++];
return value;
} else if (value >= 32 && value <= 246) {
return value - 139;
} else if (value >= 247 && value <= 250) {
return ((value - 247) * 256) + dict[pos++] + 108;
} else if (value >= 251 && value <= 254) {
return -((value - 251) * 256) - dict[pos++] - 108;
}
warn('CFFParser_parseDict: "' + value + '" is a reserved command.');
return NaN;
}
function parseFloatOperand() {
var str = '';
var eof = 15;
var lookup = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '.', 'E', 'E-', null, '-'];
var length = dict.length;
while (pos < length) {
var b = dict[pos++];
var b1 = b >> 4;
var b2 = b & 15;
if (b1 === eof) {
break;
}
str += lookup[b1];
if (b2 === eof) {
break;
}
str += lookup[b2];
}
return parseFloat(str);
}
var operands = [];
var entries = [];
pos = 0;
var end = dict.length;
while (pos < end) {
var b = dict[pos];
if (b <= 21) {
if (b === 12) {
b = (b << 8) | dict[++pos];
}
entries.push([b, operands]);
operands = [];
++pos;
} else {
operands.push(parseOperand());
}
}
return entries;
},
parseIndex: function CFFParser_parseIndex(pos) {
var cffIndex = new CFFIndex();
var bytes = this.bytes;
var count = (bytes[pos++] << 8) | bytes[pos++];
var offsets = [];
var end = pos;
var i, ii;
if (count !== 0) {
var offsetSize = bytes[pos++];
// add 1 for offset to determine size of last object
var startPos = pos + ((count + 1) * offsetSize) - 1;
for (i = 0, ii = count + 1; i < ii; ++i) {
var offset = 0;
for (var j = 0; j < offsetSize; ++j) {
offset <<= 8;
offset += bytes[pos++];
}
offsets.push(startPos + offset);
}
end = offsets[count];
}
for (i = 0, ii = offsets.length - 1; i < ii; ++i) {
var offsetStart = offsets[i];
var offsetEnd = offsets[i + 1];
cffIndex.add(bytes.subarray(offsetStart, offsetEnd));
}
return {obj: cffIndex, endPos: end};
},
parseNameIndex: function CFFParser_parseNameIndex(index) {
var names = [];
for (var i = 0, ii = index.count; i < ii; ++i) {
var name = index.get(i);
// OTS doesn't allow names to be over 127 characters.
var length = Math.min(name.length, 127);
var data = [];
// OTS also only permits certain characters in the name.
for (var j = 0; j < length; ++j) {
var c = name[j];
if (j === 0 && c === 0) {
data[j] = c;
continue;
}
if ((c < 33 || c > 126) || c === 91 /* [ */ || c === 93 /* ] */ ||
c === 40 /* ( */ || c === 41 /* ) */ || c === 123 /* { */ ||
c === 125 /* } */ || c === 60 /* < */ || c === 62 /* > */ ||
c === 47 /* / */ || c === 37 /* % */ || c === 35 /* # */) {
data[j] = 95;
continue;
}
data[j] = c;
}
names.push(bytesToString(data));
}
return names;
},
parseStringIndex: function CFFParser_parseStringIndex(index) {
var strings = new CFFStrings();
for (var i = 0, ii = index.count; i < ii; ++i) {
var data = index.get(i);
strings.add(bytesToString(data));
}
return strings;
},
createDict: function CFFParser_createDict(Type, dict, strings) {
var cffDict = new Type(strings);
for (var i = 0, ii = dict.length; i < ii; ++i) {
var pair = dict[i];
var key = pair[0];
var value = pair[1];
cffDict.setByKey(key, value);
}
return cffDict;
},
parseCharString: function CFFParser_parseCharString(state, data,
localSubrIndex,
globalSubrIndex) {
if (!data || state.callDepth > MAX_SUBR_NESTING) {
return false;
}
var stackSize = state.stackSize;
var stack = state.stack;
var length = data.length;
for (var j = 0; j < length;) {
var value = data[j++];
var validationCommand = null;
if (value === 12) {
var q = data[j++];
if (q === 0) {
// The CFF specification state that the 'dotsection' command
// (12, 0) is deprecated and treated as a no-op, but all Type2
// charstrings processors should support them. Unfortunately
// the font sanitizer don't. As a workaround the sequence (12, 0)
// is replaced by a useless (0, hmoveto).
data[j - 2] = 139;
data[j - 1] = 22;
stackSize = 0;
} else {
validationCommand = CharstringValidationData12[q];
}
} else if (value === 28) { // number (16 bit)
stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16)) >> 16;
j += 2;
stackSize++;
} else if (value === 14) {
if (stackSize >= 4) {
stackSize -= 4;
if (this.seacAnalysisEnabled) {
state.seac = stack.slice(stackSize, stackSize + 4);
return false;
}
}
validationCommand = CharstringValidationData[value];
} else if (value >= 32 && value <= 246) { // number
stack[stackSize] = value - 139;
stackSize++;
} else if (value >= 247 && value <= 254) { // number (+1 bytes)
stack[stackSize] = (value < 251 ?
((value - 247) << 8) + data[j] + 108 :
-((value - 251) << 8) - data[j] - 108);
j++;
stackSize++;
} else if (value === 255) { // number (32 bit)
stack[stackSize] = ((data[j] << 24) | (data[j + 1] << 16) |
(data[j + 2] << 8) | data[j + 3]) / 65536;
j += 4;
stackSize++;
} else if (value === 19 || value === 20) {
state.hints += stackSize >> 1;
// skipping right amount of hints flag data
j += (state.hints + 7) >> 3;
stackSize %= 2;
validationCommand = CharstringValidationData[value];
} else if (value === 10 || value === 29) {
var subrsIndex;
if (value === 10) {
subrsIndex = localSubrIndex;
} else {
subrsIndex = globalSubrIndex;
}
if (!subrsIndex) {
validationCommand = CharstringValidationData[value];
warn('Missing subrsIndex for ' + validationCommand.id);
return false;
}
var bias = 32768;
if (subrsIndex.count < 1240) {
bias = 107;
} else if (subrsIndex.count < 33900) {
bias = 1131;
}
var subrNumber = stack[--stackSize] + bias;
if (subrNumber < 0 || subrNumber >= subrsIndex.count ||
isNaN(subrNumber)) {
validationCommand = CharstringValidationData[value];
warn('Out of bounds subrIndex for ' + validationCommand.id);
return false;
}
state.stackSize = stackSize;
state.callDepth++;
var valid = this.parseCharString(state, subrsIndex.get(subrNumber),
localSubrIndex, globalSubrIndex);
if (!valid) {
return false;
}
state.callDepth--;
stackSize = state.stackSize;
continue;
} else if (value === 11) {
state.stackSize = stackSize;
return true;
} else {
validationCommand = CharstringValidationData[value];
}
if (validationCommand) {
if (validationCommand.stem) {
state.hints += stackSize >> 1;
}
if ('min' in validationCommand) {
if (!state.undefStack && stackSize < validationCommand.min) {
warn('Not enough parameters for ' + validationCommand.id +
'; actual: ' + stackSize +
', expected: ' + validationCommand.min);
return false;
}
}
if (state.firstStackClearing && validationCommand.stackClearing) {
state.firstStackClearing = false;
// the optional character width can be found before the first
// stack-clearing command arguments
stackSize -= validationCommand.min;
if (stackSize >= 2 && validationCommand.stem) {
// there are even amount of arguments for stem commands
stackSize %= 2;
} else if (stackSize > 1) {
warn('Found too many parameters for stack-clearing command');
}
if (stackSize > 0 && stack[stackSize - 1] >= 0) {
state.width = stack[stackSize - 1];
}
}
if ('stackDelta' in validationCommand) {
if ('stackFn' in validationCommand) {
validationCommand.stackFn(stack, stackSize);
}
stackSize += validationCommand.stackDelta;
} else if (validationCommand.stackClearing) {
stackSize = 0;
} else if (validationCommand.resetStack) {
stackSize = 0;
state.undefStack = false;
} else if (validationCommand.undefStack) {
stackSize = 0;
state.undefStack = true;
state.firstStackClearing = false;
}
}
}
state.stackSize = stackSize;
return true;
},
parseCharStrings: function CFFParser_parseCharStrings(charStrings,
localSubrIndex,
globalSubrIndex,
fdSelect,
fdArray) {
var seacs = [];
var widths = [];
var count = charStrings.count;
for (var i = 0; i < count; i++) {
var charstring = charStrings.get(i);
var state = {
callDepth: 0,
stackSize: 0,
stack: [],
undefStack: true,
hints: 0,
firstStackClearing: true,
seac: null,
width: null
};
var valid = true;
var localSubrToUse = null;
if (fdSelect && fdArray.length) {
var fdIndex = fdSelect.getFDIndex(i);
if (fdIndex === -1) {
warn('Glyph index is not in fd select.');
valid = false;
}
if (fdIndex >= fdArray.length) {
warn('Invalid fd index for glyph index.');
valid = false;
}
if (valid) {
localSubrToUse = fdArray[fdIndex].privateDict.subrsIndex;
}
} else if (localSubrIndex) {
localSubrToUse = localSubrIndex;
}
if (valid) {
valid = this.parseCharString(state, charstring, localSubrToUse,
globalSubrIndex);
}
if (state.width !== null) {
widths[i] = state.width;
}
if (state.seac !== null) {
seacs[i] = state.seac;
}
if (!valid) {
// resetting invalid charstring to single 'endchar'
charStrings.set(i, new Uint8Array([14]));
}
}
return { charStrings, seacs, widths, };
},
emptyPrivateDictionary:
function CFFParser_emptyPrivateDictionary(parentDict) {
var privateDict = this.createDict(CFFPrivateDict, [],
parentDict.strings);
parentDict.setByKey(18, [0, 0]);
parentDict.privateDict = privateDict;
},
parsePrivateDict: function CFFParser_parsePrivateDict(parentDict) {
// no private dict, do nothing
if (!parentDict.hasName('Private')) {
this.emptyPrivateDictionary(parentDict);
return;
}
var privateOffset = parentDict.getByName('Private');
// make sure the params are formatted correctly
if (!isArray(privateOffset) || privateOffset.length !== 2) {
parentDict.removeByName('Private');
return;
}
var size = privateOffset[0];
var offset = privateOffset[1];
// remove empty dicts or ones that refer to invalid location
if (size === 0 || offset >= this.bytes.length) {
this.emptyPrivateDictionary(parentDict);
return;
}
var privateDictEnd = offset + size;
var dictData = this.bytes.subarray(offset, privateDictEnd);
var dict = this.parseDict(dictData);
var privateDict = this.createDict(CFFPrivateDict, dict,
parentDict.strings);
parentDict.privateDict = privateDict;
// Parse the Subrs index also since it's relative to the private dict.
if (!privateDict.getByName('Subrs')) {
return;
}
var subrsOffset = privateDict.getByName('Subrs');
var relativeOffset = offset + subrsOffset;
// Validate the offset.
if (subrsOffset === 0 || relativeOffset >= this.bytes.length) {
this.emptyPrivateDictionary(parentDict);
return;
}
var subrsIndex = this.parseIndex(relativeOffset);
privateDict.subrsIndex = subrsIndex.obj;
},
parseCharsets: function CFFParser_parseCharsets(pos, length, strings, cid) {
if (pos === 0) {
return new CFFCharset(true, CFFCharsetPredefinedTypes.ISO_ADOBE,
ISOAdobeCharset);
} else if (pos === 1) {
return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT,
ExpertCharset);
} else if (pos === 2) {
return new CFFCharset(true, CFFCharsetPredefinedTypes.EXPERT_SUBSET,
ExpertSubsetCharset);
}
var bytes = this.bytes;
var start = pos;
var format = bytes[pos++];
var charset = ['.notdef'];
var id, count, i;
// subtract 1 for the .notdef glyph
length -= 1;
switch (format) {
case 0:
for (i = 0; i < length; i++) {
id = (bytes[pos++] << 8) | bytes[pos++];
charset.push(cid ? id : strings.get(id));
}
break;
case 1:
while (charset.length <= length) {
id = (bytes[pos++] << 8) | bytes[pos++];
count = bytes[pos++];
for (i = 0; i <= count; i++) {
charset.push(cid ? id++ : strings.get(id++));
}
}
break;
case 2:
while (charset.length <= length) {
id = (bytes[pos++] << 8) | bytes[pos++];
count = (bytes[pos++] << 8) | bytes[pos++];
for (i = 0; i <= count; i++) {
charset.push(cid ? id++ : strings.get(id++));
}
}
break;
default:
error('Unknown charset format');
}
// Raw won't be needed if we actually compile the charset.
var end = pos;
var raw = bytes.subarray(start, end);
return new CFFCharset(false, format, charset, raw);
},
parseEncoding: function CFFParser_parseEncoding(pos,
properties,
strings,
charset) {
var encoding = Object.create(null);
var bytes = this.bytes;
var predefined = false;
var format, i, ii;
var raw = null;
function readSupplement() {
var supplementsCount = bytes[pos++];
for (i = 0; i < supplementsCount; i++) {
var code = bytes[pos++];
var sid = (bytes[pos++] << 8) + (bytes[pos++] & 0xff);
encoding[code] = charset.indexOf(strings.get(sid));
}
}
if (pos === 0 || pos === 1) {
predefined = true;
format = pos;
var baseEncoding = pos ? ExpertEncoding : StandardEncoding;
for (i = 0, ii = charset.length; i < ii; i++) {
var index = baseEncoding.indexOf(charset[i]);
if (index !== -1) {
encoding[index] = i;
}
}
} else {
var dataStart = pos;
format = bytes[pos++];
switch (format & 0x7f) {
case 0:
var glyphsCount = bytes[pos++];
for (i = 1; i <= glyphsCount; i++) {
encoding[bytes[pos++]] = i;
}
break;
case 1:
var rangesCount = bytes[pos++];
var gid = 1;
for (i = 0; i < rangesCount; i++) {
var start = bytes[pos++];
var left = bytes[pos++];
for (var j = start; j <= start + left; j++) {
encoding[j] = gid++;
}
}
break;
default:
error('Unknown encoding format: ' + format + ' in CFF');
break;
}
var dataEnd = pos;
if (format & 0x80) { // hasSupplement
// The font sanitizer does not support CFF encoding with a
// supplement, since the encoding is not really used to map
// between gid to glyph, let's overwrite what is declared in
// the top dictionary to let the sanitizer think the font use
// StandardEncoding, that's a lie but that's ok.
bytes[dataStart] &= 0x7f;
readSupplement();
}
raw = bytes.subarray(dataStart, dataEnd);
}
format = format & 0x7f;
return new CFFEncoding(predefined, format, encoding, raw);
},
parseFDSelect: function CFFParser_parseFDSelect(pos, length) {
var start = pos;
var bytes = this.bytes;
var format = bytes[pos++];
var fdSelect = [], rawBytes;
var i, invalidFirstGID = false;
switch (format) {
case 0:
for (i = 0; i < length; ++i) {
var id = bytes[pos++];
fdSelect.push(id);
}
rawBytes = bytes.subarray(start, pos);
break;
case 3:
var rangesCount = (bytes[pos++] << 8) | bytes[pos++];
for (i = 0; i < rangesCount; ++i) {
var first = (bytes[pos++] << 8) | bytes[pos++];
if (i === 0 && first !== 0) {
warn('parseFDSelect: The first range must have a first GID of 0' +
' -- trying to recover.');
invalidFirstGID = true;
first = 0;
}
var fdIndex = bytes[pos++];
var next = (bytes[pos] << 8) | bytes[pos + 1];
for (var j = first; j < next; ++j) {
fdSelect.push(fdIndex);
}
}
// Advance past the sentinel(next).
pos += 2;
rawBytes = bytes.subarray(start, pos);
if (invalidFirstGID) {
rawBytes[3] = rawBytes[4] = 0; // Adjust the first range, first GID.
}
break;
default:
error('parseFDSelect: Unknown format "' + format + '".');
break;
}
assert(fdSelect.length === length, 'parseFDSelect: Invalid font data.');
return new CFFFDSelect(fdSelect, rawBytes);
}
};
return CFFParser;
})();
// Compact Font Format
var CFF = (function CFFClosure() {
function CFF() {
this.header = null;
this.names = [];
this.topDict = null;
this.strings = new CFFStrings();
this.globalSubrIndex = null;
// The following could really be per font, but since we only have one font
// store them here.
this.encoding = null;
this.charset = null;
this.charStrings = null;
this.fdArray = [];
this.fdSelect = null;
this.isCIDFont = false;
}
return CFF;
})();
var CFFHeader = (function CFFHeaderClosure() {
function CFFHeader(major, minor, hdrSize, offSize) {
this.major = major;
this.minor = minor;
this.hdrSize = hdrSize;
this.offSize = offSize;
}
return CFFHeader;
})();
var CFFStrings = (function CFFStringsClosure() {
function CFFStrings() {
this.strings = [];
}
CFFStrings.prototype = {
get: function CFFStrings_get(index) {
if (index >= 0 && index <= 390) {
return CFFStandardStrings[index];
}
if (index - 391 <= this.strings.length) {
return this.strings[index - 391];
}
return CFFStandardStrings[0];
},
add: function CFFStrings_add(value) {
this.strings.push(value);
},
get count() {
return this.strings.length;
}
};
return CFFStrings;
})();
var CFFIndex = (function CFFIndexClosure() {
function CFFIndex() {
this.objects = [];
this.length = 0;
}
CFFIndex.prototype = {
add: function CFFIndex_add(data) {
this.length += data.length;
this.objects.push(data);
},
set: function CFFIndex_set(index, data) {
this.length += data.length - this.objects[index].length;
this.objects[index] = data;
},
get: function CFFIndex_get(index) {
return this.objects[index];
},
get count() {
return this.objects.length;
}
};
return CFFIndex;
})();
var CFFDict = (function CFFDictClosure() {
function CFFDict(tables, strings) {
this.keyToNameMap = tables.keyToNameMap;
this.nameToKeyMap = tables.nameToKeyMap;
this.defaults = tables.defaults;
this.types = tables.types;
this.opcodes = tables.opcodes;
this.order = tables.order;
this.strings = strings;
this.values = Object.create(null);
}
CFFDict.prototype = {
// value should always be an array
setByKey: function CFFDict_setByKey(key, value) {
if (!(key in this.keyToNameMap)) {
return false;
}
var valueLength = value.length;
// ignore empty values
if (valueLength === 0) {
return true;
}
// Ignore invalid values (fixes bug1068432.pdf and bug1308536.pdf).
for (var i = 0; i < valueLength; i++) {
if (isNaN(value[i])) {
warn('Invalid CFFDict value: "' + value + '" for key "' + key + '".');
return true;
}
}
var type = this.types[key];
// remove the array wrapping these types of values
if (type === 'num' || type === 'sid' || type === 'offset') {
value = value[0];
}
this.values[key] = value;
return true;
},
setByName: function CFFDict_setByName(name, value) {
if (!(name in this.nameToKeyMap)) {
error('Invalid dictionary name "' + name + '"');
}
this.values[this.nameToKeyMap[name]] = value;
},
hasName: function CFFDict_hasName(name) {
return this.nameToKeyMap[name] in this.values;
},
getByName: function CFFDict_getByName(name) {
if (!(name in this.nameToKeyMap)) {
error('Invalid dictionary name "' + name + '"');
}
var key = this.nameToKeyMap[name];
if (!(key in this.values)) {
return this.defaults[key];
}
return this.values[key];
},
removeByName: function CFFDict_removeByName(name) {
delete this.values[this.nameToKeyMap[name]];
}
};
CFFDict.createTables = function CFFDict_createTables(layout) {
var tables = {
keyToNameMap: {},
nameToKeyMap: {},
defaults: {},
types: {},
opcodes: {},
order: []
};
for (var i = 0, ii = layout.length; i < ii; ++i) {
var entry = layout[i];
var key = isArray(entry[0]) ? (entry[0][0] << 8) + entry[0][1] : entry[0];
tables.keyToNameMap[key] = entry[1];
tables.nameToKeyMap[entry[1]] = key;
tables.types[key] = entry[2];
tables.defaults[key] = entry[3];
tables.opcodes[key] = isArray(entry[0]) ? entry[0] : [entry[0]];
tables.order.push(key);
}
return tables;
};
return CFFDict;
})();
var CFFTopDict = (function CFFTopDictClosure() {
var layout = [
[[12, 30], 'ROS', ['sid', 'sid', 'num'], null],
[[12, 20], 'SyntheticBase', 'num', null],
[0, 'version', 'sid', null],
[1, 'Notice', 'sid', null],
[[12, 0], 'Copyright', 'sid', null],
[2, 'FullName', 'sid', null],
[3, 'FamilyName', 'sid', null],
[4, 'Weight', 'sid', null],
[[12, 1], 'isFixedPitch', 'num', 0],
[[12, 2], 'ItalicAngle', 'num', 0],
[[12, 3], 'UnderlinePosition', 'num', -100],
[[12, 4], 'UnderlineThickness', 'num', 50],
[[12, 5], 'PaintType', 'num', 0],
[[12, 6], 'CharstringType', 'num', 2],
[[12, 7], 'FontMatrix', ['num', 'num', 'num', 'num', 'num', 'num'],
[0.001, 0, 0, 0.001, 0, 0]],
[13, 'UniqueID', 'num', null],
[5, 'FontBBox', ['num', 'num', 'num', 'num'], [0, 0, 0, 0]],
[[12, 8], 'StrokeWidth', 'num', 0],
[14, 'XUID', 'array', null],
[15, 'charset', 'offset', 0],
[16, 'Encoding', 'offset', 0],
[17, 'CharStrings', 'offset', 0],
[18, 'Private', ['offset', 'offset'], null],
[[12, 21], 'PostScript', 'sid', null],
[[12, 22], 'BaseFontName', 'sid', null],
[[12, 23], 'BaseFontBlend', 'delta', null],
[[12, 31], 'CIDFontVersion', 'num', 0],
[[12, 32], 'CIDFontRevision', 'num', 0],
[[12, 33], 'CIDFontType', 'num', 0],
[[12, 34], 'CIDCount', 'num', 8720],
[[12, 35], 'UIDBase', 'num', null],
// XXX: CID Fonts on DirectWrite 6.1 only seem to work if FDSelect comes
// before FDArray.
[[12, 37], 'FDSelect', 'offset', null],
[[12, 36], 'FDArray', 'offset', null],
[[12, 38], 'FontName', 'sid', null]
];
var tables = null;
function CFFTopDict(strings) {
if (tables === null) {
tables = CFFDict.createTables(layout);
}
CFFDict.call(this, tables, strings);
this.privateDict = null;
}
CFFTopDict.prototype = Object.create(CFFDict.prototype);
return CFFTopDict;
})();
var CFFPrivateDict = (function CFFPrivateDictClosure() {
var layout = [
[6, 'BlueValues', 'delta', null],
[7, 'OtherBlues', 'delta', null],
[8, 'FamilyBlues', 'delta', null],
[9, 'FamilyOtherBlues', 'delta', null],
[[12, 9], 'BlueScale', 'num', 0.039625],
[[12, 10], 'BlueShift', 'num', 7],
[[12, 11], 'BlueFuzz', 'num', 1],
[10, 'StdHW', 'num', null],
[11, 'StdVW', 'num', null],
[[12, 12], 'StemSnapH', 'delta', null],
[[12, 13], 'StemSnapV', 'delta', null],
[[12, 14], 'ForceBold', 'num', 0],
[[12, 17], 'LanguageGroup', 'num', 0],
[[12, 18], 'ExpansionFactor', 'num', 0.06],
[[12, 19], 'initialRandomSeed', 'num', 0],
[20, 'defaultWidthX', 'num', 0],
[21, 'nominalWidthX', 'num', 0],
[19, 'Subrs', 'offset', null]
];
var tables = null;
function CFFPrivateDict(strings) {
if (tables === null) {
tables = CFFDict.createTables(layout);
}
CFFDict.call(this, tables, strings);
this.subrsIndex = null;
}
CFFPrivateDict.prototype = Object.create(CFFDict.prototype);
return CFFPrivateDict;
})();
var CFFCharsetPredefinedTypes = {
ISO_ADOBE: 0,
EXPERT: 1,
EXPERT_SUBSET: 2
};
var CFFCharset = (function CFFCharsetClosure() {
function CFFCharset(predefined, format, charset, raw) {
this.predefined = predefined;
this.format = format;
this.charset = charset;
this.raw = raw;
}
return CFFCharset;
})();
var CFFEncoding = (function CFFEncodingClosure() {
function CFFEncoding(predefined, format, encoding, raw) {
this.predefined = predefined;
this.format = format;
this.encoding = encoding;
this.raw = raw;
}
return CFFEncoding;
})();
var CFFFDSelect = (function CFFFDSelectClosure() {
function CFFFDSelect(fdSelect, raw) {
this.fdSelect = fdSelect;
this.raw = raw;
}
CFFFDSelect.prototype = {
getFDIndex: function CFFFDSelect_get(glyphIndex) {
if (glyphIndex < 0 || glyphIndex >= this.fdSelect.length) {
return -1;
}
return this.fdSelect[glyphIndex];
}
};
return CFFFDSelect;
})();
// Helper class to keep track of where an offset is within the data and helps
// filling in that offset once it's known.
var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
function CFFOffsetTracker() {
this.offsets = Object.create(null);
}
CFFOffsetTracker.prototype = {
isTracking: function CFFOffsetTracker_isTracking(key) {
return key in this.offsets;
},
track: function CFFOffsetTracker_track(key, location) {
if (key in this.offsets) {
error('Already tracking location of ' + key);
}
this.offsets[key] = location;
},
offset: function CFFOffsetTracker_offset(value) {
for (var key in this.offsets) {
this.offsets[key] += value;
}
},
setEntryLocation: function CFFOffsetTracker_setEntryLocation(key,
values,
output) {
if (!(key in this.offsets)) {
error('Not tracking location of ' + key);
}
var data = output.data;
var dataOffset = this.offsets[key];
var size = 5;
for (var i = 0, ii = values.length; i < ii; ++i) {
var offset0 = i * size + dataOffset;
var offset1 = offset0 + 1;
var offset2 = offset0 + 2;
var offset3 = offset0 + 3;
var offset4 = offset0 + 4;
// It's easy to screw up offsets so perform this sanity check.
if (data[offset0] !== 0x1d || data[offset1] !== 0 ||
data[offset2] !== 0 || data[offset3] !== 0 || data[offset4] !== 0) {
error('writing to an offset that is not empty');
}
var value = values[i];
data[offset0] = 0x1d;
data[offset1] = (value >> 24) & 0xFF;
data[offset2] = (value >> 16) & 0xFF;
data[offset3] = (value >> 8) & 0xFF;
data[offset4] = value & 0xFF;
}
}
};
return CFFOffsetTracker;
})();
// Takes a CFF and converts it to the binary representation.
var CFFCompiler = (function CFFCompilerClosure() {
function CFFCompiler(cff) {
this.cff = cff;
}
CFFCompiler.prototype = {
compile: function CFFCompiler_compile() {
var cff = this.cff;
var output = {
data: [],
length: 0,
add: function CFFCompiler_add(data) {
this.data = this.data.concat(data);
this.length = this.data.length;
}
};
// Compile the five entries that must be in order.
var header = this.compileHeader(cff.header);
output.add(header);
var nameIndex = this.compileNameIndex(cff.names);
output.add(nameIndex);
if (cff.isCIDFont) {
// The spec is unclear on how font matrices should relate to each other
// when there is one in the main top dict and the sub top dicts.
// Windows handles this differently than linux and osx so we have to
// normalize to work on all.
// Rules based off of some mailing list discussions:
// - If main font has a matrix and subfont doesn't, use the main matrix.
// - If no main font matrix and there is a subfont matrix, use the
// subfont matrix.
// - If both have matrices, concat together.
// - If neither have matrices, use default.
// To make this work on all platforms we move the top matrix into each
// sub top dict and concat if necessary.
if (cff.topDict.hasName('FontMatrix')) {
var base = cff.topDict.getByName('FontMatrix');
cff.topDict.removeByName('FontMatrix');
for (var i = 0, ii = cff.fdArray.length; i < ii; i++) {
var subDict = cff.fdArray[i];
var matrix = base.slice(0);
if (subDict.hasName('FontMatrix')) {
matrix = Util.transform(matrix, subDict.getByName('FontMatrix'));
}
subDict.setByName('FontMatrix', matrix);
}
}
}
var compiled = this.compileTopDicts([cff.topDict],
output.length,
cff.isCIDFont);
output.add(compiled.output);
var topDictTracker = compiled.trackers[0];
var stringIndex = this.compileStringIndex(cff.strings.strings);
output.add(stringIndex);
var globalSubrIndex = this.compileIndex(cff.globalSubrIndex);
output.add(globalSubrIndex);
// Now start on the other entries that have no specific order.
if (cff.encoding && cff.topDict.hasName('Encoding')) {
if (cff.encoding.predefined) {
topDictTracker.setEntryLocation('Encoding', [cff.encoding.format],
output);
} else {
var encoding = this.compileEncoding(cff.encoding);
topDictTracker.setEntryLocation('Encoding', [output.length], output);
output.add(encoding);
}
}
if (cff.charset && cff.topDict.hasName('charset')) {
if (cff.charset.predefined) {
topDictTracker.setEntryLocation('charset', [cff.charset.format],
output);
} else {
var charset = this.compileCharset(cff.charset);
topDictTracker.setEntryLocation('charset', [output.length], output);
output.add(charset);
}
}
var charStrings = this.compileCharStrings(cff.charStrings);
topDictTracker.setEntryLocation('CharStrings', [output.length], output);
output.add(charStrings);
if (cff.isCIDFont) {
// For some reason FDSelect must be in front of FDArray on windows. OSX
// and linux don't seem to care.
topDictTracker.setEntryLocation('FDSelect', [output.length], output);
var fdSelect = this.compileFDSelect(cff.fdSelect.raw);
output.add(fdSelect);
// It is unclear if the sub font dictionary can have CID related
// dictionary keys, but the sanitizer doesn't like them so remove them.
compiled = this.compileTopDicts(cff.fdArray, output.length, true);
topDictTracker.setEntryLocation('FDArray', [output.length], output);
output.add(compiled.output);
var fontDictTrackers = compiled.trackers;
this.compilePrivateDicts(cff.fdArray, fontDictTrackers, output);
}
this.compilePrivateDicts([cff.topDict], [topDictTracker], output);
// If the font data ends with INDEX whose object data is zero-length,
// the sanitizer will bail out. Add a dummy byte to avoid that.
output.add([0]);
return output.data;
},
encodeNumber: function CFFCompiler_encodeNumber(value) {
if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) { // isInt
return this.encodeInteger(value);
}
return this.encodeFloat(value);
},
encodeFloat: function CFFCompiler_encodeFloat(num) {
var value = num.toString();
// rounding inaccurate doubles
var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);
if (m) {
var epsilon = parseFloat('1e' + ((m[2] ? +m[2] : 0) + m[1].length));
value = (Math.round(num * epsilon) / epsilon).toString();
}
var nibbles = '';
var i, ii;
for (i = 0, ii = value.length; i < ii; ++i) {
var a = value[i];
if (a === 'e') {
nibbles += value[++i] === '-' ? 'c' : 'b';
} else if (a === '.') {
nibbles += 'a';
} else if (a === '-') {
nibbles += 'e';
} else {
nibbles += a;
}
}
nibbles += (nibbles.length & 1) ? 'f' : 'ff';
var out = [30];
for (i = 0, ii = nibbles.length; i < ii; i += 2) {
out.push(parseInt(nibbles.substr(i, 2), 16));
}
return out;
},
encodeInteger: function CFFCompiler_encodeInteger(value) {
var code;
if (value >= -107 && value <= 107) {
code = [value + 139];
} else if (value >= 108 && value <= 1131) {
value = value - 108;
code = [(value >> 8) + 247, value & 0xFF];
} else if (value >= -1131 && value <= -108) {
value = -value - 108;
code = [(value >> 8) + 251, value & 0xFF];
} else if (value >= -32768 && value <= 32767) {
code = [0x1c, (value >> 8) & 0xFF, value & 0xFF];
} else {
code = [0x1d,
(value >> 24) & 0xFF,
(value >> 16) & 0xFF,
(value >> 8) & 0xFF,
value & 0xFF];
}
return code;
},
compileHeader: function CFFCompiler_compileHeader(header) {
return [
header.major,
header.minor,
header.hdrSize,
header.offSize
];
},
compileNameIndex: function CFFCompiler_compileNameIndex(names) {
var nameIndex = new CFFIndex();
for (var i = 0, ii = names.length; i < ii; ++i) {
nameIndex.add(stringToBytes(names[i]));
}
return this.compileIndex(nameIndex);
},
compileTopDicts: function CFFCompiler_compileTopDicts(dicts,
length,
removeCidKeys) {
var fontDictTrackers = [];
var fdArrayIndex = new CFFIndex();
for (var i = 0, ii = dicts.length; i < ii; ++i) {
var fontDict = dicts[i];
if (removeCidKeys) {
fontDict.removeByName('CIDFontVersion');
fontDict.removeByName('CIDFontRevision');
fontDict.removeByName('CIDFontType');
fontDict.removeByName('CIDCount');
fontDict.removeByName('UIDBase');
}
var fontDictTracker = new CFFOffsetTracker();
var fontDictData = this.compileDict(fontDict, fontDictTracker);
fontDictTrackers.push(fontDictTracker);
fdArrayIndex.add(fontDictData);
fontDictTracker.offset(length);
}
fdArrayIndex = this.compileIndex(fdArrayIndex, fontDictTrackers);
return {
trackers: fontDictTrackers,
output: fdArrayIndex
};
},
compilePrivateDicts: function CFFCompiler_compilePrivateDicts(dicts,
trackers,
output) {
for (var i = 0, ii = dicts.length; i < ii; ++i) {
var fontDict = dicts[i];
assert(fontDict.privateDict && fontDict.hasName('Private'),
'There must be an private dictionary.');
var privateDict = fontDict.privateDict;
var privateDictTracker = new CFFOffsetTracker();
var privateDictData = this.compileDict(privateDict, privateDictTracker);
var outputLength = output.length;
privateDictTracker.offset(outputLength);
if (!privateDictData.length) {
// The private dictionary was empty, set the output length to zero to
// ensure the offset length isn't out of bounds in the eyes of the
// sanitizer.
outputLength = 0;
}
trackers[i].setEntryLocation('Private',
[privateDictData.length, outputLength],
output);
output.add(privateDictData);
if (privateDict.subrsIndex && privateDict.hasName('Subrs')) {
var subrs = this.compileIndex(privateDict.subrsIndex);
privateDictTracker.setEntryLocation('Subrs', [privateDictData.length],
output);
output.add(subrs);
}
}
},
compileDict: function CFFCompiler_compileDict(dict, offsetTracker) {
var out = [];
// The dictionary keys must be in a certain order.
var order = dict.order;
for (var i = 0; i < order.length; ++i) {
var key = order[i];
if (!(key in dict.values)) {
continue;
}
var values = dict.values[key];
var types = dict.types[key];
if (!isArray(types)) {
types = [types];
}
if (!isArray(values)) {
values = [values];
}
// Remove any empty dict values.
if (values.length === 0) {
continue;
}
for (var j = 0, jj = types.length; j < jj; ++j) {
var type = types[j];
var value = values[j];
switch (type) {
case 'num':
case 'sid':
out = out.concat(this.encodeNumber(value));
break;
case 'offset':
// For offsets we just insert a 32bit integer so we don't have to
// deal with figuring out the length of the offset when it gets
// replaced later on by the compiler.
var name = dict.keyToNameMap[key];
// Some offsets have the offset and the length, so just record the
// position of the first one.
if (!offsetTracker.isTracking(name)) {
offsetTracker.track(name, out.length);
}
out = out.concat([0x1d, 0, 0, 0, 0]);
break;
case 'array':
case 'delta':
out = out.concat(this.encodeNumber(value));
for (var k = 1, kk = values.length; k < kk; ++k) {
out = out.concat(this.encodeNumber(values[k]));
}
break;
default:
error('Unknown data type of ' + type);
break;
}
}
out = out.concat(dict.opcodes[key]);
}
return out;
},
compileStringIndex: function CFFCompiler_compileStringIndex(strings) {
var stringIndex = new CFFIndex();
for (var i = 0, ii = strings.length; i < ii; ++i) {
stringIndex.add(stringToBytes(strings[i]));
}
return this.compileIndex(stringIndex);
},
compileGlobalSubrIndex: function CFFCompiler_compileGlobalSubrIndex() {
var globalSubrIndex = this.cff.globalSubrIndex;
this.out.writeByteArray(this.compileIndex(globalSubrIndex));
},
compileCharStrings: function CFFCompiler_compileCharStrings(charStrings) {
return this.compileIndex(charStrings);
},
compileCharset: function CFFCompiler_compileCharset(charset) {
return this.compileTypedArray(charset.raw);
},
compileEncoding: function CFFCompiler_compileEncoding(encoding) {
return this.compileTypedArray(encoding.raw);
},
compileFDSelect: function CFFCompiler_compileFDSelect(fdSelect) {
return this.compileTypedArray(fdSelect);
},
compileTypedArray: function CFFCompiler_compileTypedArray(data) {
var out = [];
for (var i = 0, ii = data.length; i < ii; ++i) {
out[i] = data[i];
}
return out;
},
compileIndex: function CFFCompiler_compileIndex(index, trackers) {
trackers = trackers || [];
var objects = index.objects;
// First 2 bytes contains the number of objects contained into this index
var count = objects.length;
// If there is no object, just create an index. This technically
// should just be [0, 0] but OTS has an issue with that.
if (count === 0) {
return [0, 0, 0];
}
var data = [(count >> 8) & 0xFF, count & 0xff];
var lastOffset = 1, i;
for (i = 0; i < count; ++i) {
lastOffset += objects[i].length;
}
var offsetSize;
if (lastOffset < 0x100) {
offsetSize = 1;
} else if (lastOffset < 0x10000) {
offsetSize = 2;
} else if (lastOffset < 0x1000000) {
offsetSize = 3;
} else {
offsetSize = 4;
}
// Next byte contains the offset size use to reference object in the file
data.push(offsetSize);
// Add another offset after this one because we need a new offset
var relativeOffset = 1;
for (i = 0; i < count + 1; i++) {
if (offsetSize === 1) {
data.push(relativeOffset & 0xFF);
} else if (offsetSize === 2) {
data.push((relativeOffset >> 8) & 0xFF,
relativeOffset & 0xFF);
} else if (offsetSize === 3) {
data.push((relativeOffset >> 16) & 0xFF,
(relativeOffset >> 8) & 0xFF,
relativeOffset & 0xFF);
} else {
data.push((relativeOffset >>> 24) & 0xFF,
(relativeOffset >> 16) & 0xFF,
(relativeOffset >> 8) & 0xFF,
relativeOffset & 0xFF);
}
if (objects[i]) {
relativeOffset += objects[i].length;
}
}
for (i = 0; i < count; i++) {
// Notify the tracker where the object will be offset in the data.
if (trackers[i]) {
trackers[i].offset(data.length);
}
for (var j = 0, jj = objects[i].length; j < jj; j++) {
data.push(objects[i][j]);
}
}
return data;
}
};
return CFFCompiler;
})();
exports.CFFStandardStrings = CFFStandardStrings;
exports.CFFParser = CFFParser;
exports.CFF = CFF;
exports.CFFHeader = CFFHeader;
exports.CFFStrings = CFFStrings;
exports.CFFIndex = CFFIndex;
exports.CFFCharset = CFFCharset;
exports.CFFTopDict = CFFTopDict;
exports.CFFPrivateDict = CFFPrivateDict;
exports.CFFCompiler = CFFCompiler;
}));
| {'content_hash': '861b3186a02c6eed1b511c9dce60cf05', 'timestamp': '', 'source': 'github', 'line_count': 1651, 'max_line_length': 80, 'avg_line_length': 36.293761356753485, 'alnum_prop': 0.543398808431101, 'repo_name': 'ydfzgyj/pdf.js', 'id': '9409c0e05ec3e6492a3d7724e1b65f26f831ed76', 'size': '60519', 'binary': False, 'copies': '2', 'ref': 'refs/heads/dev', 'path': 'src/core/cff_parser.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '61201'}, {'name': 'HTML', 'bytes': '44281'}, {'name': 'JavaScript', 'bytes': '2855466'}]} |
// Copyright 2009 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.
#define SS_DISABLE 4
typedef byte* kevent_udata;
int32 runtime·bsdthread_create(void*, M*, G*, void(*)(void));
int32 runtime·bsdthread_register(void);
int32 runtime·mach_msg_trap(MachHeader*, int32, uint32, uint32, uint32, uint32, uint32);
uint32 runtime·mach_reply_port(void);
int32 runtime·mach_semacquire(uint32, int64);
uint32 runtime·mach_semcreate(void);
void runtime·mach_semdestroy(uint32);
void runtime·mach_semrelease(uint32);
void runtime·mach_semreset(uint32);
uint32 runtime·mach_task_self(void);
uint32 runtime·mach_task_self(void);
uint32 runtime·mach_thread_self(void);
uint32 runtime·mach_thread_self(void);
int32 runtime·sysctl(uint32*, uint32, byte*, uintptr*, byte*, uintptr);
typedef uint32 Sigset;
void runtime·sigprocmask(int32, Sigset*, Sigset*);
void runtime·unblocksignals(void);
struct Sigaction;
void runtime·sigaction(uintptr, struct Sigaction*, struct Sigaction*);
struct StackT;
void runtime·sigaltstack(struct StackT*, struct StackT*);
void runtime·sigtramp(void);
void runtime·sigpanic(void);
void runtime·setitimer(int32, Itimerval*, Itimerval*);
#define NSIG 32
#define SI_USER 0 /* empirically true, but not what headers say */
#define SIG_BLOCK 1
#define SIG_UNBLOCK 2
#define SIG_SETMASK 3
| {'content_hash': 'e40c3577a8d1f21b7cf02ccaa4c3f551', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 88, 'avg_line_length': 33.23809523809524, 'alnum_prop': 0.7693409742120344, 'repo_name': 'eggfly/go-linux-arm', 'id': '91a405f2145586f2c9cac92c17d5bfc431689346', 'size': '1417', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': '70499e5fbe5b/src/pkg/runtime/os_darwin.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '1011898'}, {'name': 'Awk', 'bytes': '7702'}, {'name': 'C', 'bytes': '10172735'}, {'name': 'C++', 'bytes': '378408'}, {'name': 'CSS', 'bytes': '6240'}, {'name': 'Emacs Lisp', 'bytes': '98402'}, {'name': 'Go', 'bytes': '32140585'}, {'name': 'JavaScript', 'bytes': '26492'}, {'name': 'Objective-C', 'bytes': '38063'}, {'name': 'OpenEdge ABL', 'bytes': '9784'}, {'name': 'Perl', 'bytes': '700558'}, {'name': 'Python', 'bytes': '131538'}, {'name': 'Shell', 'bytes': '185353'}, {'name': 'VimL', 'bytes': '56082'}]} |
package com.jetbrains.python.psi.types;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.util.NullableFunction;
import com.intellij.util.ProcessingContext;
import com.intellij.util.SmartList;
import com.jetbrains.python.psi.AccessDirection;
import com.jetbrains.python.psi.PyExpression;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.resolve.RatedResolveResult;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
/**
* @author yole
*/
public class PyUnionType implements PyType {
private final Set<PyType> myMembers;
PyUnionType(Collection<PyType> members) {
myMembers = new LinkedHashSet<>(members);
}
@Nullable
public List<? extends RatedResolveResult> resolveMember(@NotNull String name,
@Nullable PyExpression location,
@NotNull AccessDirection direction,
@NotNull PyResolveContext resolveContext) {
SmartList<RatedResolveResult> ret = new SmartList<>();
boolean allNulls = true;
for (PyType member : myMembers) {
if (member != null) {
List<? extends RatedResolveResult> result = member.resolveMember(name, location, direction, resolveContext);
if (result != null) {
allNulls = false;
ret.addAll(result);
}
}
}
return allNulls ? null : ret;
}
public Object[] getCompletionVariants(String completionPrefix, PsiElement location, ProcessingContext context) {
Set<Object> variants = new HashSet<>();
for (PyType member : myMembers) {
if (member != null) {
Collections.addAll(variants, member.getCompletionVariants(completionPrefix, location, context));
}
}
return variants.toArray(new Object[variants.size()]);
}
public String getName() {
return StringUtil.join(myMembers, (NullableFunction<PyType, String>)type -> type != null ? type.getName() : null, " | ");
}
/**
* @return true if all types in the union are built-in.
*/
@Override
public boolean isBuiltin() {
for (PyType one : myMembers) {
if (one == null || !one.isBuiltin()) return false;
}
return true;
}
@Override
public void assertValid(String message) {
for (PyType member : myMembers) {
if (member != null) {
member.assertValid(message);
}
}
}
@Nullable
public static PyType union(@Nullable PyType type1, @Nullable PyType type2) {
Set<PyType> members = new LinkedHashSet<>();
if (type1 instanceof PyUnionType) {
members.addAll(((PyUnionType)type1).myMembers);
}
else {
members.add(type1);
}
if (type2 instanceof PyUnionType) {
members.addAll(((PyUnionType)type2).myMembers);
}
else {
members.add(type2);
}
if (members.size() == 1) {
return members.iterator().next();
}
return new PyUnionType(members);
}
@Nullable
public static PyType union(Collection<PyType> members) {
final int n = members.size();
if (n == 0) {
return null;
}
else if (n == 1) {
return members.iterator().next();
}
else {
final Iterator<PyType> it = members.iterator();
PyType res = unit(it.next());
while (it.hasNext()) {
res = union(res, it.next());
}
return res;
}
}
@Nullable
public static PyType createWeakType(@Nullable PyType type) {
if (type == null) {
return null;
}
else if (type instanceof PyUnionType) {
final PyUnionType unionType = (PyUnionType)type;
if (unionType.isWeak()) {
return unionType;
}
}
return union(type, null);
}
public boolean isWeak() {
for (PyType member : myMembers) {
if (member == null) {
return true;
}
}
return false;
}
public Collection<PyType> getMembers() {
return myMembers;
}
/**
* Excludes all subtypes of type from the union
*
* @param type type to exclude. If type is a union all subtypes of union members will be excluded from the union
* If type is null only null will be excluded from the union.
* @param context
* @return union with excluded types
*/
@Nullable
public PyType exclude(@Nullable PyType type, @NotNull TypeEvalContext context) {
final List<PyType> members = new ArrayList<>();
for (PyType m : getMembers()) {
if (type == null) {
if (m != null) {
members.add(m);
}
}
else {
if (!PyTypeChecker.match(type, m, context)) {
members.add(m);
}
}
}
return union(members);
}
@Nullable
public PyType excludeNull(@NotNull TypeEvalContext context) {
return exclude(null, context);
}
private static PyType unit(@Nullable PyType type) {
if (type instanceof PyUnionType) {
Set<PyType> members = new LinkedHashSet<>();
members.addAll(((PyUnionType)type).getMembers());
return new PyUnionType(members);
}
else {
return new PyUnionType(Collections.singletonList(type));
}
}
@Override
public boolean equals(Object other) {
if (other instanceof PyUnionType) {
final PyUnionType otherType = (PyUnionType)other;
return myMembers.equals(otherType.myMembers);
}
return false;
}
@Override
public int hashCode() {
return myMembers.hashCode();
}
@Override
public String toString() {
return "PyUnionType: " + getName();
}
}
| {'content_hash': 'f680aeff0b2d2c96a964a867be5d0976', 'timestamp': '', 'source': 'github', 'line_count': 208, 'max_line_length': 125, 'avg_line_length': 27.20673076923077, 'alnum_prop': 0.6241385403781586, 'repo_name': 'asedunov/intellij-community', 'id': '2fcde6dd481eda3dffa45c65066ca92498b265eb', 'size': '6259', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'python/src/com/jetbrains/python/psi/types/PyUnionType.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '60827'}, {'name': 'C', 'bytes': '211454'}, {'name': 'C#', 'bytes': '1264'}, {'name': 'C++', 'bytes': '199030'}, {'name': 'CMake', 'bytes': '1675'}, {'name': 'CSS', 'bytes': '201445'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '3250629'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1899872'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '165745831'}, {'name': 'JavaScript', 'bytes': '570364'}, {'name': 'Jupyter Notebook', 'bytes': '93222'}, {'name': 'Kotlin', 'bytes': '4687386'}, {'name': 'Lex', 'bytes': '147047'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '51039'}, {'name': 'Objective-C', 'bytes': '27861'}, {'name': 'Perl', 'bytes': '903'}, {'name': 'Perl6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6680'}, {'name': 'Python', 'bytes': '25459263'}, {'name': 'Roff', 'bytes': '37534'}, {'name': 'Ruby', 'bytes': '1217'}, {'name': 'Shell', 'bytes': '66338'}, {'name': 'Smalltalk', 'bytes': '338'}, {'name': 'TeX', 'bytes': '25473'}, {'name': 'Thrift', 'bytes': '1846'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'Visual Basic', 'bytes': '77'}, {'name': 'XSLT', 'bytes': '113040'}]} |
package com.kii.demo.ui.fragments;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.kii.cloud.engine.Constants;
import com.kii.cloud.engine.KiiCloudClient;
import com.kii.cloud.storage.KiiFile;
import com.kii.cloud.storage.exception.CloudExecutionException;
import com.kii.demo.R;
import com.kii.demo.ui.view.ActionItem;
import com.kii.demo.ui.view.KiiListItemView;
import com.kii.demo.ui.view.QuickAction;
import com.kii.demo.utils.MimeInfo;
import com.kii.demo.utils.MimeUtil;
import com.kii.demo.utils.UiUtils;
import com.kii.demo.utils.Utils;
public class FileListFragment extends ListFragment {
protected File mDirectory;
protected ArrayList<File> mFiles;
protected FilePickerListAdapter mAdapter;
protected boolean mShowHiddenFiles = false;
protected String[] acceptedFileExtensions;
private final static String DEFAULT_INITIAL_DIRECTORY = "/mnt/sdcard/";
private View mView;
private final static int OPTIONS_MENU_SCAN_CHANGE = 0;
private final static int OPTIONS_MENU_DOWNLOAD_ALL = 1;
QuickAction mQuickAction = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.list_with_header, container, false);
Button b = (Button) mView.findViewById(R.id.button_left);
b.setText(getString(R.string.header_btn_home));
b.setOnClickListener(mClickListener);
b = (Button) mView.findViewById(R.id.button_right);
b.setText(getString(R.string.header_btn_up));
b.setOnClickListener(mClickListener);
setHasOptionsMenu(true);
return mView;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
File newFile = (File) l.getItemAtPosition(position);
if (newFile.isFile()) {
Intent intent = null;
MimeInfo mime = MimeUtil.getInfoByFileName(newFile
.getAbsolutePath());
intent = UiUtils.getLaunchFileIntent(newFile.getAbsolutePath(),
mime);
if (intent == null) {
UiUtils.showToast(getActivity(), "Failed to launch the file - "
+ newFile.getName());
} else {
try {
startActivity(intent);
} catch (Exception ex) {
UiUtils.showToast(
getActivity(),
"Encounter error when launch file ("
+ newFile.getName() + "). Error("
+ ex.getMessage() + ")");
}
}
} else {
mDirectory = newFile;
// Update the files list
refreshFilesList();
}
super.onListItemClick(l, v, position, id);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mDirectory = new File(DEFAULT_INITIAL_DIRECTORY);
mFiles = new ArrayList<File>();
mAdapter = new FilePickerListAdapter(getActivity(), mFiles);
setListAdapter(mAdapter);
}
private void uploadFile(final File file) {
KiiCloudClient client = KiiCloudClient.getInstance(getActivity());
client.upload(file);
}
private List<File> mUploadFiles = new ArrayList<File>();
private void uploadFolder(final File file) {
KiiCloudClient client = KiiCloudClient.getInstance(getActivity());
getRecursiveFiles(file);
for (File f : mUploadFiles) {
client.upload(f);
}
mUploadFiles.clear();
}
private void getRecursiveFiles(File file) {
File[] list = file.listFiles();
for (File f : list) {
if (f.isDirectory()) {
getRecursiveFiles(f);
} else {
mUploadFiles.add(f);
}
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.add(0, OPTIONS_MENU_SCAN_CHANGE, 0, R.string.scan_change);
menu.add(0, OPTIONS_MENU_DOWNLOAD_ALL, 1, R.string.download_all);
return;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTIONS_MENU_SCAN_CHANGE:
new ScanTask().execute();
break;
case OPTIONS_MENU_DOWNLOAD_ALL:
downloadAll();
break;
default:
break;
}
return true;
}
private void downloadAll() {
new Thread(new Runnable() {
@Override
public void run() {
try {
List<KiiFile> files = KiiFile
.listWorkingFiles(Constants.ANDROID_EXT);
for (KiiFile file : files) {
KiiCloudClient.getInstance(getActivity()).download(
file, null);
}
} catch (CloudExecutionException e) {
// TODO: Fix this - auto generated
e.printStackTrace();
} catch (IOException e) {
// TODO: Fix this - auto generated
e.printStackTrace();
}
}
}).start();
}
@Override
public void onResume() {
refreshFilesList();
super.onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private class FilePickerListAdapter extends BaseAdapter {
private List<File> mObjects;
public FilePickerListAdapter(Context context, List<File> objects) {
super();
mObjects = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
File file = mObjects.get(position);
Drawable icon = null;
if (ICON_CACHE.containsKey(file.getAbsolutePath())) {
icon = ICON_CACHE.get(file.getAbsolutePath());
} else {
icon = Utils.getThumbnailDrawableByFilename(
file.getAbsolutePath(), getActivity());
ICON_CACHE.put(file.getAbsolutePath(), icon);
}
KiiListItemView v;
if (convertView == null) {
v = new KiiListItemView(getActivity(), file,
KiiCloudClient.getInstance(getActivity()), icon,
mClickListener);
return v;
} else {
v = (KiiListItemView) convertView;
v.refreshWithNewFile(file, icon);
return v;
}
}
@Override
public int getCount() {
return mObjects.size();
}
@Override
public Object getItem(int position) {
return mObjects.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
}
private static HashMap<String, Drawable> ICON_CACHE = new HashMap<String, Drawable>();
private class FileComparator implements Comparator<File> {
@Override
public int compare(File f1, File f2) {
if (f1 == f2) {
return 0;
}
if (f1.isDirectory() && f2.isFile()) {
// Show directories above files
return -1;
}
if (f1.isFile() && f2.isDirectory()) {
// Show files below directories
return 1;
}
// Sort the directories alphabetically
return f1.getName().compareToIgnoreCase(f2.getName());
}
}
private class ExtensionFilenameFilter implements FilenameFilter {
private String[] mExtensions;
public ExtensionFilenameFilter(String[] extensions) {
super();
mExtensions = extensions;
}
@Override
public boolean accept(File dir, String filename) {
if (new File(dir, filename).isDirectory()) {
// Accept all directory names
return true;
}
if ((mExtensions != null) && (mExtensions.length > 0)) {
for (int i = 0; i < mExtensions.length; i++) {
if (filename.endsWith(mExtensions[i])) {
// The filename ends with the extension
return true;
}
}
// The filename did not match any of the extensions
return false;
}
// No extensions has been set. Accept all file extensions.
return true;
}
}
public void refreshFilesList() {
// Clear the files ArrayList
mFiles.clear();
// Set the extension file filter
ExtensionFilenameFilter filter = new ExtensionFilenameFilter(
acceptedFileExtensions);
// Get the files in the directory
File[] files = mDirectory.listFiles(filter);
if ((files != null) && (files.length > 0)) {
for (File f : files) {
if (f.isHidden() && !mShowHiddenFiles) {
// Don't add the file
continue;
}
// Add the file the ArrayAdapter
mFiles.add(f);
}
Collections.sort(mFiles, new FileComparator());
}
mAdapter.notifyDataSetChanged();
Button b = (Button) mView.findViewById(R.id.button_right);
if (isAtSdHome()) {
// at SD card home, disable Up button
b.setEnabled(false);
} else {
b.setEnabled(true);
}
TextView tv = (TextView) mView.findViewById(R.id.header_text);
tv.setText(getString(R.string.header_text_path) + mDirectory.getPath());
}
private boolean isAtSdHome() {
return mDirectory.compareTo(Environment.getExternalStorageDirectory()
.getAbsoluteFile()) == 0;
}
View.OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_left:
mDirectory = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
refreshFilesList();
break;
case R.id.button_right:
mDirectory = mDirectory.getParentFile();
refreshFilesList();
break;
case R.id.list_complex_more_button:
View row = (View) v.getTag();
final File f = (File) row.getTag();
mQuickAction = new QuickAction(getActivity());
if (f.isFile()) {
mQuickAction.addActionItem(new ActionItem(
ACTION_ITEM_UPLOAD,
getString(R.string.menu_item_upload_file)));
} else if (f.isDirectory()) {
mQuickAction.addActionItem(new ActionItem(
ACTION_ITEM_UPLOAD_FOLDER,
getString(R.string.menu_item_upload_folder)));
}
mQuickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
@Override
public void onItemClick(QuickAction source,
int pos, int actionId) {
switch (actionId) {
case ACTION_ITEM_UPLOAD:
uploadFile(f);
break;
case ACTION_ITEM_UPLOAD_FOLDER:
uploadFolder(f);
break;
}
}
});
if (mQuickAction.getActionItem(0) != null) {
mQuickAction.show(v);
}
break;
}
}
};
private static final int ACTION_ITEM_UPLOAD = 1;
private static final int ACTION_ITEM_UPLOAD_FOLDER = 2;
public class DownloadAllTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
KiiCloudClient client = KiiCloudClient.getInstance(getActivity());
if (client != null) {
KiiFile[] files = client.getBackupFiles();
if (files != null) {
for (KiiFile file : files) {
client.download(file,
Utils.getKiiFileDownloadPath(file));
}
}
}
return null;
}
}
ProgressDialog scanDialog = null;
public class ScanTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPostExecute(Void result) {
if (scanDialog != null) {
scanDialog.dismiss();
scanDialog = null;
}
if (!scanChange.isEmpty()) {
getActivity().showDialog(DIALOG_UPDATE);
} else {
UiUtils.showToast(getActivity(), "No update is found.");
}
}
@Override
protected void onPreExecute() {
if (scanDialog == null) {
scanDialog = ProgressDialog.show(getActivity(), "",
"Scanning for update. Please wait...", true);
} else {
if (scanTotalCount > 0) {
scanDialog.setMessage(String.format("Scan %d out of %d",
scanCurCount, scanTotalCount));
}
}
}
@Override
protected Void doInBackground(Void... params) {
scanFileChange();
return null;
}
}
static ArrayList<KiiFile> scanChange = null;
int scanTotalCount = -1;
int scanCurCount = 0;
private void scanFileChange() {
scanChange = new ArrayList<KiiFile>();
scanTotalCount = -1;
scanCurCount = 0;
KiiCloudClient kiiClient = KiiCloudClient.getInstance(getActivity());
KiiFile[] files = kiiClient.getBackupFiles();
scanTotalCount = files.length;
scanCurCount = 0;
for (; scanCurCount < files.length; scanCurCount++) {
if (!Utils.bodySameAsLocal(files[scanCurCount])) {
scanChange.add(files[scanCurCount]);
}
}
}
public static List<KiiFile> getLocalChanges() {
return scanChange;
}
public static final int DIALOG_UPDATE = 101;
}
| {'content_hash': 'fd17c680099a4713eaa42dd2637f7d7f', 'timestamp': '', 'source': 'github', 'line_count': 469, 'max_line_length': 103, 'avg_line_length': 34.072494669509595, 'alnum_prop': 0.5319148936170213, 'repo_name': 'kii-dev-jenkins/KiiFileStorageSampleApp', 'id': 'eb4ea2fc64a5a8a7dbe2c4211f8c1a27875a56de', 'size': '16616', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/kii/demo/ui/fragments/FileListFragment.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '164571'}]} |
define(["require"], function (require)
{
return function (controllerId, stateUrl, name, modulePath)
{
//console.log("Registering " + controllerId);
return {
url: stateUrl,
parent: 'AuthorizeUser',
templateUrl: String.format("{0}View/{1}.html", modulePath, name),
controller: controllerId,
resolve:
{
LazyLoad: function ($q)
{
//console.log("Lazyload initiated for " + name);
var defer = $q.defer();
require([String.format("{0}Controller/{1}.js", modulePath, name)], function ()
{
defer.resolve();
//console.log("Lazyload completed for " + name);
});
return defer.promise;
}
}
};
};
}); | {'content_hash': 'aa87689398205e99efd6063f1a982472', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 83, 'avg_line_length': 23.17241379310345, 'alnum_prop': 0.6026785714285714, 'repo_name': 'AgronKabashi/SimpleCMS', 'id': '1999eea9c6d5d8c25a5c2786a82408c79d082067', 'size': '674', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Dependencies/angularJS/LazyRouteState.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '40836'}, {'name': 'HTML', 'bytes': '12113'}, {'name': 'JavaScript', 'bytes': '42620'}]} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:iosched="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/menu_search"
android:icon="@drawable/ic_action_search"
android:title="@string/compose_search"
android:orderInCategory="0"
iosched:actionViewClass="android.support.v7.widget.SearchView"
iosched:showAsAction="always" />
</menu> | {'content_hash': '2d154c580ce6e46a7ff6cb5ef9410cc4', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 70, 'avg_line_length': 46.44444444444444, 'alnum_prop': 0.6889952153110048, 'repo_name': 'ShoppingAlerts/android', 'id': 'd62fb5bdbe7ec89edff32001c3d3ca172dcaed28', 'size': '418', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SmartShoppingList/app/src/main/res/menu/search.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '117555'}]} |
package com.facebook.buck.rules.keys;
import com.facebook.buck.log.Logger;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.PathSourcePath;
import com.facebook.buck.rules.RuleKeyBuilder;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import java.lang.reflect.Field;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
class StringifyAlterRuleKey extends AbstractAlterRuleKey {
private static final Logger LOG = Logger.get(StringifyAlterRuleKey.class);
private static final Function<Object, Iterable<Path>> FIND_ABSOLUTE_PATHS =
new Function<Object, Iterable<Path>>() {
@Override
public Iterable<Path> apply(Object val) {
return findAbsolutePaths(val);
}
};
public StringifyAlterRuleKey(Field field) {
super(field);
}
@VisibleForTesting
static Iterable<Path> findAbsolutePaths(Object val) {
if (val instanceof Path) {
Path path = (Path) val;
if (path.isAbsolute()) {
return Collections.singleton(path);
}
} else if (val instanceof PathSourcePath) {
return findAbsolutePaths(((PathSourcePath) val).getRelativePath());
} else if (val instanceof Iterable) {
return FluentIterable.from((Iterable<?>) val)
.transformAndConcat(FIND_ABSOLUTE_PATHS);
} else if (val instanceof Map) {
Map<?, ?> map = (Map<?, ?>) val;
Iterable<?> allSubValues = Iterables.concat(map.keySet(), map.values());
return FluentIterable.from(allSubValues)
.transformAndConcat(FIND_ABSOLUTE_PATHS);
} else if (val instanceof Optional) {
Optional<?> optional = (Optional<?>) val;
if (optional.isPresent()) {
return findAbsolutePaths(optional.get());
}
}
return ImmutableList.of();
}
@Override
public void amendKey(RuleKeyBuilder builder, BuildRule rule) {
Object val = getValue(field, rule);
builder.setReflectively(
field.getName(),
val == null ? null : String.valueOf(val));
if (val != null) {
Iterable<Path> absolutePaths = findAbsolutePaths(val);
if (!Iterables.isEmpty(absolutePaths)) {
LOG.warn(
"Field %s contains absolute paths %s and it is included in a rule key.",
field.getName(),
ImmutableSet.copyOf(absolutePaths));
}
}
}
}
| {'content_hash': 'c6007279edbfcc9504f7503c3b5a4a56', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 84, 'avg_line_length': 32.13414634146341, 'alnum_prop': 0.6850094876660342, 'repo_name': 'lukw00/buck', 'id': 'd3f21e1f2053de7212c36d7ac3200df2bfab6e81', 'size': '3240', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'src/com/facebook/buck/rules/keys/StringifyAlterRuleKey.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '87'}, {'name': 'Batchfile', 'bytes': '683'}, {'name': 'C', 'bytes': '245856'}, {'name': 'C#', 'bytes': '237'}, {'name': 'C++', 'bytes': '3765'}, {'name': 'CSS', 'bytes': '54863'}, {'name': 'D', 'bytes': '623'}, {'name': 'Go', 'bytes': '419'}, {'name': 'Groff', 'bytes': '440'}, {'name': 'HTML', 'bytes': '4938'}, {'name': 'IDL', 'bytes': '128'}, {'name': 'Java', 'bytes': '10604268'}, {'name': 'JavaScript', 'bytes': '931231'}, {'name': 'Lex', 'bytes': '2442'}, {'name': 'Makefile', 'bytes': '1791'}, {'name': 'Matlab', 'bytes': '47'}, {'name': 'OCaml', 'bytes': '2956'}, {'name': 'Objective-C', 'bytes': '81412'}, {'name': 'Objective-C++', 'bytes': '34'}, {'name': 'PowerShell', 'bytes': '143'}, {'name': 'Python', 'bytes': '203028'}, {'name': 'Rust', 'bytes': '938'}, {'name': 'Shell', 'bytes': '31126'}, {'name': 'Smalltalk', 'bytes': '438'}, {'name': 'Yacc', 'bytes': '323'}]} |
from __future__ import absolute_import, division, print_function
import sys
import threading
import time
from timeit import default_timer
from ..callbacks import Callback
from ..utils import ignoring
def format_time(t):
"""Format seconds into a human readable form.
>>> format_time(10.4)
'10.4s'
>>> format_time(1000.4)
'16min 40.4s'
"""
m, s = divmod(t, 60)
h, m = divmod(m, 60)
if h:
return '{0:2.0f}hr {1:2.0f}min {2:4.1f}s'.format(h, m, s)
elif m:
return '{0:2.0f}min {1:4.1f}s'.format(m, s)
else:
return '{0:4.1f}s'.format(s)
class ProgressBar(Callback):
"""A progress bar for dask.
Parameters
----------
minimum : int, optional
Minimum time threshold in seconds before displaying a progress bar.
Default is 0 (always display)
width : int, optional
Width of the bar
dt : float, optional
Update resolution in seconds, default is 0.1 seconds
Examples
--------
Below we create a progress bar with a minimum threshold of 1 second before
displaying. For cheap computations nothing is shown:
>>> with ProgressBar(minimum=1.0): # doctest: +SKIP
... out = some_fast_computation.compute()
But for expensive computations a full progress bar is displayed:
>>> with ProgressBar(minimum=1.0): # doctest: +SKIP
... out = some_slow_computation.compute()
[########################################] | 100% Completed | 10.4 s
The duration of the last computation is available as an attribute
>>> pbar = ProgressBar()
>>> with pbar: # doctest: +SKIP
... out = some_computation.compute()
[########################################] | 100% Completed | 10.4 s
>>> pbar.last_duration # doctest: +SKIP
10.4
You can also register a progress bar so that it displays for all
computations:
>>> pbar = ProgressBar() # doctest: +SKIP
>>> pbar.register() # doctest: +SKIP
>>> some_slow_computation.compute() # doctest: +SKIP
[########################################] | 100% Completed | 10.4 s
"""
def __init__(self, minimum=0, width=40, dt=0.1):
self._minimum = minimum
self._width = width
self._dt = dt
self.last_duration = 0
def _start(self, dsk):
self._state = None
self._start_time = default_timer()
# Start background thread
self._running = True
self._timer = threading.Thread(target=self._timer_func)
self._timer.daemon = True
self._timer.start()
def _pretask(self, key, dsk, state):
self._state = state
sys.stdout.flush()
def _finish(self, dsk, state, errored):
self._running = False
self._timer.join()
elapsed = default_timer() - self._start_time
self.last_duration = elapsed
if elapsed < self._minimum:
return
if not errored:
self._draw_bar(1, elapsed)
else:
self._update_bar(elapsed)
sys.stdout.write('\n')
sys.stdout.flush()
def _timer_func(self):
"""Background thread for updating the progress bar"""
while self._running:
elapsed = default_timer() - self._start_time
if elapsed > self._minimum:
self._update_bar(elapsed)
time.sleep(self._dt)
def _update_bar(self, elapsed):
s = self._state
if not s:
self._draw_bar(0, elapsed)
return
ndone = len(s['finished'])
ntasks = sum(len(s[k]) for k in ['ready', 'waiting', 'running']) + ndone
self._draw_bar(ndone / ntasks if ntasks else 0, elapsed)
def _draw_bar(self, frac, elapsed):
bar = '#' * int(self._width * frac)
percent = int(100 * frac)
elapsed = format_time(elapsed)
msg = '\r[{0:<{1}}] | {2}% Completed | {3}'.format(bar, self._width,
percent, elapsed)
with ignoring(ValueError):
sys.stdout.write(msg)
sys.stdout.flush()
| {'content_hash': 'c746b373715bb3939c3baf35a58e63e4', 'timestamp': '', 'source': 'github', 'line_count': 134, 'max_line_length': 80, 'avg_line_length': 31.365671641791046, 'alnum_prop': 0.5424696645253391, 'repo_name': 'cpcloud/dask', 'id': 'e3783b6a49d9127ede372b415d1f4e162da07b7d', 'size': '4203', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'dask/diagnostics/progress.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '4934'}, {'name': 'Python', 'bytes': '1701377'}]} |
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Security.Cryptography.Encryption.Tests.Asymmetric
{
public static partial class CryptoStreamTests
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public static async Task DisposeAsync_DataFlushedCorrectly(bool explicitFlushFinalBeforeDispose)
{
const string Text = "hello";
var stream = new MemoryStream();
using (CryptoStream encryptStream = new CryptoStream(stream, new IdentityTransform(64, 64, true), CryptoStreamMode.Write))
{
Assert.Equal(0, stream.Position);
byte[] toWrite = Encoding.UTF8.GetBytes(Text);
encryptStream.Write(toWrite, 0, toWrite.Length);
Assert.False(encryptStream.HasFlushedFinalBlock);
Assert.Equal(0, stream.Position);
if (explicitFlushFinalBeforeDispose)
{
encryptStream.FlushFinalBlock();
}
await encryptStream.DisposeAsync();
Assert.True(encryptStream.HasFlushedFinalBlock);
Assert.Equal(5, stream.ToArray().Length);
Assert.True(encryptStream.DisposeAsync().IsCompletedSuccessfully);
}
stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
using (CryptoStream decryptStream = new CryptoStream(stream, new IdentityTransform(64, 64, true), CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(decryptStream))
{
Assert.Equal(Text, reader.ReadToEnd());
}
Assert.True(decryptStream.DisposeAsync().IsCompletedSuccessfully);
}
}
[Fact]
public static void DisposeAsync_DerivedStream_InvokesDispose()
{
var stream = new MemoryStream();
using (var encryptStream = new DerivedCryptoStream(stream, new IdentityTransform(64, 64, true), CryptoStreamMode.Write))
{
Assert.False(encryptStream.DisposeInvoked);
Assert.True(encryptStream.DisposeAsync().IsCompletedSuccessfully);
Assert.True(encryptStream.DisposeInvoked);
}
}
[Fact]
public static void PaddedAes_PartialRead_Success()
{
using (Aes aes = Aes.Create())
{
aes.Mode = CipherMode.CBC;
aes.Key = aes.IV = new byte[] { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, };
var memoryStream = new MemoryStream();
using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write, leaveOpen: true))
{
cryptoStream.Write(Encoding.ASCII.GetBytes("Sample string that's bigger than cryptoAlg.BlockSize"));
cryptoStream.FlushFinalBlock();
}
memoryStream.Position = 0;
using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
cryptoStream.ReadByte(); // Partially read the CryptoStream before disposing it.
}
// No exception should be thrown.
}
}
private sealed class DerivedCryptoStream : CryptoStream
{
public bool DisposeInvoked;
public DerivedCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) : base(stream, transform, mode) { }
protected override void Dispose(bool disposing)
{
DisposeInvoked = true;
base.Dispose(disposing);
}
}
}
}
| {'content_hash': '0cb2b583ad3bcf21980005f1dfe4b878', 'timestamp': '', 'source': 'github', 'line_count': 99, 'max_line_length': 140, 'avg_line_length': 39.63636363636363, 'alnum_prop': 0.5838430173292558, 'repo_name': 'ViktorHofer/corefx', 'id': '0e30afa60ae59d30e873e0f6b20c2c8f1804cd89', 'size': '4128', 'binary': False, 'copies': '39', 'ref': 'refs/heads/master', 'path': 'src/System.Security.Cryptography.Primitives/tests/CryptoStream.netcoreapp.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': '1C Enterprise', 'bytes': '280724'}, {'name': 'ASP', 'bytes': '1687'}, {'name': 'Batchfile', 'bytes': '11027'}, {'name': 'C', 'bytes': '3803475'}, {'name': 'C#', 'bytes': '181020278'}, {'name': 'C++', 'bytes': '1521'}, {'name': 'CMake', 'bytes': '79434'}, {'name': 'DIGITAL Command Language', 'bytes': '26402'}, {'name': 'HTML', 'bytes': '653'}, {'name': 'Makefile', 'bytes': '13780'}, {'name': 'OpenEdge ABL', 'bytes': '137969'}, {'name': 'Perl', 'bytes': '3895'}, {'name': 'PowerShell', 'bytes': '192578'}, {'name': 'Python', 'bytes': '1535'}, {'name': 'Roff', 'bytes': '9422'}, {'name': 'Shell', 'bytes': '131531'}, {'name': 'TSQL', 'bytes': '96941'}, {'name': 'Visual Basic', 'bytes': '2135320'}, {'name': 'XSLT', 'bytes': '514720'}]} |
<?php
/**
* TDataGridColumn class file
*/
Prado::using('System.Web.UI.WebControls.TDataGridColumn');
/**
* THyperLink class file
*/
Prado::using('System.Web.UI.WebControls.THyperLink');
/**
* THyperLinkColumn class
*
* THyperLinkColumn contains a hyperlink for each item in the column.
* You can set the text and the url of the hyperlink by {@link setText Text}
* and {@link setNavigateUrl NavigateUrl} properties, respectively.
* You can also bind the text and url to specific data field in datasource
* by setting {@link setDataTextField DataTextField} and
* {@link setDataNavigateUrlField DataNavigateUrlField}.
* Both can be formatted before rendering according to the
* {@link setDataTextFormatString DataTextFormatString} and
* and {@link setDataNavigateUrlFormatString DataNavigateUrlFormatString}
* properties, respectively. If both {@link setText Text} and {@link setDataTextField DataTextField}
* are present, the latter takes precedence.
* The same rule applies to {@link setNavigateUrl NavigateUrl} and
* {@link setDataNavigateUrlField DataNavigateUrlField} properties.
*
* The hyperlinks in the column can be accessed by one of the following two methods:
* <code>
* $datagridItem->HyperLinkColumnID->HyperLink
* $datagridItem->HyperLinkColumnID->Controls[0]
* </code>
* The second method is possible because the hyperlink control created within the
* datagrid cell is the first child.
*
* @author Qiang Xue <[email protected]>
* @package System.Web.UI.WebControls
* @since 3.0
*/
class THyperLinkColumn extends TDataGridColumn
{
/**
* @return string the text caption of the hyperlink
*/
public function getText()
{
return $this->getViewState('Text','');
}
/**
* Sets the text caption of the hyperlink.
* @param string the text caption to be set
*/
public function setText($value)
{
$this->setViewState('Text',$value,'');
}
/**
* @return string the field name from the data source to bind to the hyperlink caption
*/
public function getDataTextField()
{
return $this->getViewState('DataTextField','');
}
/**
* @param string the field name from the data source to bind to the hyperlink caption
*/
public function setDataTextField($value)
{
$this->setViewState('DataTextField',$value,'');
}
/**
* @return string the formatting string used to control how the hyperlink caption will be displayed.
*/
public function getDataTextFormatString()
{
return $this->getViewState('DataTextFormatString','');
}
/**
* @param string the formatting string used to control how the hyperlink caption will be displayed.
*/
public function setDataTextFormatString($value)
{
$this->setViewState('DataTextFormatString',$value,'');
}
/**
* @return string height of the image in the THyperLink
*/
public function getImageHeight()
{
return $this->getViewState('ImageHeight','');
}
/**
* @param string height of the image in the THyperLink
*/
public function setImageHeight($value)
{
$this->setViewState('ImageHeight',$value,'');
}
/**
* @return string url of the image in the THyperLink
*/
public function getImageUrl()
{
return $this->getViewState('ImageUrl','');
}
/**
* @param string url of the image in the THyperLink
*/
public function setImageUrl($value)
{
$this->setViewState('ImageUrl',$value,'');
}
/**
* @return string width of the image in the THyperLink
*/
public function getImageWidth()
{
return $this->getViewState('ImageWidth','');
}
/**
* @param string width of the image in the THyperLink
*/
public function setImageWidth($value)
{
$this->setViewState('ImageWidth',$value,'');
}
/**
* @return string the URL to link to when the hyperlink is clicked.
*/
public function getNavigateUrl()
{
return $this->getViewState('NavigateUrl','');
}
/**
* Sets the URL to link to when the hyperlink is clicked.
* @param string the URL
*/
public function setNavigateUrl($value)
{
$this->setViewState('NavigateUrl',$value,'');
}
/**
* @return string the field name from the data source to bind to the navigate url of hyperlink
*/
public function getDataNavigateUrlField()
{
return $this->getViewState('DataNavigateUrlField','');
}
/**
* @param string the field name from the data source to bind to the navigate url of hyperlink
*/
public function setDataNavigateUrlField($value)
{
$this->setViewState('DataNavigateUrlField',$value,'');
}
/**
* @return string the formatting string used to control how the navigate url of hyperlink will be displayed.
*/
public function getDataNavigateUrlFormatString()
{
return $this->getViewState('DataNavigateUrlFormatString','');
}
/**
* @param string the formatting string used to control how the navigate url of hyperlink will be displayed.
*/
public function setDataNavigateUrlFormatString($value)
{
$this->setViewState('DataNavigateUrlFormatString',$value,'');
}
/**
* @return string the target window or frame to display the Web page content linked to when the hyperlink is clicked.
*/
public function getTarget()
{
return $this->getViewState('Target','');
}
/**
* Sets the target window or frame to display the Web page content linked to when the hyperlink is clicked.
* @param string the target window, valid values include '_blank', '_parent', '_self', '_top' and empty string.
*/
public function setTarget($value)
{
$this->setViewState('Target',$value,'');
}
/**
* Initializes the specified cell to its initial values.
* This method overrides the parent implementation.
* It creates a hyperlink within the cell.
* @param TTableCell the cell to be initialized.
* @param integer the index to the Columns property that the cell resides in.
* @param string the type of cell (Header,Footer,Item,AlternatingItem,EditItem,SelectedItem)
*/
public function initializeCell($cell,$columnIndex,$itemType)
{
if($itemType===TListItemType::Item || $itemType===TListItemType::AlternatingItem || $itemType===TListItemType::SelectedItem || $itemType===TListItemType::EditItem)
{
$link=new THyperLink;
if(($url = $this->getImageUrl())!=='')
{
$link->setImageUrl($url);
if(($width=$this->getImageWidth())!=='')
$link->setImageWidth($width);
if(($height=$this->getImageHeight())!=='')
$link->setImageHeight($height);
}
$link->setText($this->getText());
$link->setNavigateUrl($this->getNavigateUrl());
$link->setTarget($this->getTarget());
if($this->getDataTextField()!=='' || $this->getDataNavigateUrlField()!=='')
$link->attachEventHandler('OnDataBinding',array($this,'dataBindColumn'));
$cell->getControls()->add($link);
$cell->registerObject('HyperLink',$link);
}
else
parent::initializeCell($cell,$columnIndex,$itemType);
}
/**
* Databinds a cell in the column.
* This method is invoked when datagrid performs databinding.
* It populates the content of the cell with the relevant data from data source.
*/
public function dataBindColumn($sender,$param)
{
$item=$sender->getNamingContainer();
$data=$item->getData();
if(($field=$this->getDataTextField())!=='')
{
$value=$this->getDataFieldValue($data,$field);
$text=$this->formatDataValue($this->getDataTextFormatString(),$value);
$sender->setText($text);
}
if(($field=$this->getDataNavigateUrlField())!=='')
{
$value=$this->getDataFieldValue($data,$field);
$url=$this->formatDataValue($this->getDataNavigateUrlFormatString(),$value);
$sender->setNavigateUrl($url);
}
}
}
| {'content_hash': 'ec7d30ff39bfb66b12528ab9a8cd4844', 'timestamp': '', 'source': 'github', 'line_count': 263, 'max_line_length': 165, 'avg_line_length': 28.6425855513308, 'alnum_prop': 0.7030399575202443, 'repo_name': 'mmauri04/prado', 'id': '05060ea6f4e26ac62ffbd1f4aeb8725c120c018b', 'size': '7787', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'framework/Web/UI/WebControls/THyperLinkColumn.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '660'}, {'name': 'Batchfile', 'bytes': '5993'}, {'name': 'CSS', 'bytes': '114399'}, {'name': 'HTML', 'bytes': '335465'}, {'name': 'JavaScript', 'bytes': '961554'}, {'name': 'PHP', 'bytes': '6962457'}, {'name': 'Smarty', 'bytes': '123746'}, {'name': 'TeX', 'bytes': '13306'}, {'name': 'XSLT', 'bytes': '252'}]} |
'use strict';
/* Controllers */
angular.module('myApp.controllers', []).
controller('MyCtrl1', [function() {
}])
.controller('patientController', ['$scope','repositoryService', 'notificationService',
function($scope, repositoryService, notificationService) {
repositoryService.getCaseFor('S09-09154 1').then(function (_case) {
$scope.patient = _case.patient;
});
repositoryService.whenPatientChanged(function(patient){
if (!_.isEqual(patient, $scope.patient)) {
var title = 'Patient changed: ';
var message =
'FROM: ' +
$scope.patient.lastname + ', ' +
$scope.patient.firstname +
' gender: ' + $scope.patient.gender +
' TO: ' +
patient.lastname + ', ' + patient.firstname +
' gender: ' + patient.gender ;
notificationService.sendNotification(message, {name:"PatientNotification", title: title}, function(){
$scope.patient = patient;
});
}
});
}]); | {'content_hash': '3cfa66b83ae8a9a987032defd150e413', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 117, 'avg_line_length': 34.911764705882355, 'alnum_prop': 0.5046335299073293, 'repo_name': 'ShettyAshwin/Angular-Push-Notification', 'id': '476bb237facabbb3ecdd72a95efbcbcd416bebb2', 'size': '1187', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/js/controllers.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1874'}, {'name': 'JavaScript', 'bytes': '2298394'}, {'name': 'Ruby', 'bytes': '503'}, {'name': 'Shell', 'bytes': '1113'}]} |
import React from 'react'
import { Route, Switch } from 'react-router-dom'
import { E404, E504 } from '@/components/error'
import Home from '@/views/home'
import HotSell from '@/views/hotsell'
export default () => (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/hotsell" component={HotSell} />
<Route component={E404} />
</Switch>
</div>
)
| {'content_hash': '273589f7cbb81e8e2457d18b5d551ce4', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 51, 'avg_line_length': 23.41176470588235, 'alnum_prop': 0.6231155778894473, 'repo_name': 'vshao/webapp', 'id': '3d38c9bb2432cbaca0d4f7781e974cc33b4191ef', 'size': '398', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/router/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '909'}, {'name': 'JavaScript', 'bytes': '24473'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>tortoise-hare-algorithm: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1+2 / tortoise-hare-algorithm - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
tortoise-hare-algorithm
<small>
8.6.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-02-24 00:36:37 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-02-24 00:36:37 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.11 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-m4 1 Virtual package relying on m4
coq 8.7.1+2 Formal proof management system.
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.0 Official release 4.09.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/tortoise-hare-algorithm"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/TortoiseHareAlgorithm"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [ "keyword: program verification" "keyword: paths" "keyword: cycle detection" "keyword: graphs" "keyword: graph theory" "keyword: finite sets" "keyword: floyd" "category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms" "date: 2007-02" ]
authors: [ "Jean-Christophe Filliâtre" ]
bug-reports: "https://github.com/coq-contribs/tortoise-hare-algorithm/issues"
dev-repo: "git+https://github.com/coq-contribs/tortoise-hare-algorithm.git"
synopsis: "Tortoise and the hare algorithm"
description: """
Correctness proof of Floyd's cycle-finding algorithm, also known as
the "tortoise and the hare"-algorithm.
See http://en.wikipedia.org/wiki/Floyd's_cycle-finding_algorithm"""
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/tortoise-hare-algorithm/archive/v8.6.0.tar.gz"
checksum: "md5=be6227480086d7ee6297ff9d817ff394"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-tortoise-hare-algorithm.8.6.0 coq.8.7.1+2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+2).
The following dependencies couldn't be met:
- coq-tortoise-hare-algorithm -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-tortoise-hare-algorithm.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': '7f8cbeb78995a4f6c86e8f5b7fb1e110', 'timestamp': '', 'source': 'github', 'line_count': 166, 'max_line_length': 380, 'avg_line_length': 44.03012048192771, 'alnum_prop': 0.5569845396087016, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '0e5a9ff9532c430ad6f1fd7054621ec0c6897036', 'size': '7312', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.09.0-2.0.5/released/8.7.1+2/tortoise-hare-algorithm/8.6.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
using System;
namespace Avalonia.Xaml.Interactivity;
/// <summary>
/// A base class for behaviors, implementing the basic plumbing of <seealso cref="ITrigger"/>.
/// </summary>
/// <typeparam name="T">The object type to attach to</typeparam>
public abstract class Trigger<T> : Trigger where T : class, IAvaloniaObject
{
/// <summary>
/// Gets the object to which this behavior is attached.
/// </summary>
public new T? AssociatedObject => base.AssociatedObject as T;
/// <summary>
/// Called after the behavior is attached to the <see cref="Behavior.AssociatedObject"/>.
/// </summary>
/// <remarks>
/// Override this to hook up functionality to the <see cref="Behavior.AssociatedObject"/>
/// </remarks>
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is null && base.AssociatedObject is { })
{
var actualType = base.AssociatedObject?.GetType().FullName;
var expectedType = typeof(T).FullName;
var message = $"AssociatedObject is of type {actualType} but should be of type {expectedType}.";
throw new InvalidOperationException(message);
}
}
} | {'content_hash': '75952bbfe2467230d4e853423d19604b', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 108, 'avg_line_length': 35.61764705882353, 'alnum_prop': 0.6507018992568125, 'repo_name': 'wieslawsoltes/AvaloniaBehaviors', 'id': '4d46f65405fffb90155ec1b1649efb7c047ddfa6', 'size': '1213', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Avalonia.Xaml.Interactivity/TriggerOfT.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '207'}, {'name': 'C#', 'bytes': '227816'}, {'name': 'PowerShell', 'bytes': '2964'}, {'name': 'Shell', 'bytes': '2286'}]} |
using namespace TNT;
class MathUtility
{
public:
MathUtility();
static void printArray2D(Array2D<double> & arr);
};
#endif // MATHUTILITY_H
| {'content_hash': '2927a02da27fa94550d22904e6e17922', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 50, 'avg_line_length': 14.6, 'alnum_prop': 0.7191780821917808, 'repo_name': 'summit4you/NTL-ISS-Robonaut-2-Vision-Algorithm-Challenge', 'id': '4204bb3508493bd9f1affc5460c3439cc6cf6c7b', 'size': '235', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'sdrdis/solution/cpp/robonaut/math/mathutility.h', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
using Examples.FirstProject.Entities;
using FluentNHibernate.Mapping;
namespace Examples.FirstProject.Mappings
{
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
Id(x => x.Id);
Map(x => x.Name);
Map(x => x.Price);
HasManyToMany(x => x.StoresStockedIn)
.Cascade.All()
.Inverse()
.Table("StoreProduct");
Component(x => x.Location);
}
}
} | {'content_hash': 'f700f089cbe0f275727eeec85ac040d6', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 49, 'avg_line_length': 24.761904761904763, 'alnum_prop': 0.49615384615384617, 'repo_name': 'hzhgis/ss', 'id': '657ffe2a2dfbcec2be89c8ab90d1cf6bdaef0bc3', 'size': '520', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'src/Examples.FirstProject/Mappings/ProductMap.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '3032105'}, {'name': 'Ruby', 'bytes': '15968'}, {'name': 'Shell', 'bytes': '306'}]} |
package org.uli.sha2;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.Charset;
public class SHA2_2 {
public String sha2hex(String input) throws NoSuchAlgorithmException, UnsupportedEncodingException {
byte[] bytesOfMessage = input.getBytes(Charset.defaultCharset());
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] thedigest = md.digest(bytesOfMessage);
BigInteger bigInt = new BigInteger(1, thedigest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
static public void main(String[] args) throws Exception {
SHA2_2 sha2_2 = new SHA2_2();
for (String arg : args) {
System.out.println(sha2_2.sha2hex(arg));
}
}
}
| {'content_hash': 'ed9e5f928bcdad2332d96c488017ea04', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 103, 'avg_line_length': 34.8, 'alnum_prop': 0.6695402298850575, 'repo_name': 'uli-heller/uli-gradle', 'id': 'cd45233898a2e67ef295496cdc792a8d32c8246d', 'size': '1044', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '057-findbugs/src/main/java/org/uli/sha2/SHA2_2.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '412'}, {'name': 'Groovy', 'bytes': '552'}, {'name': 'HTML', 'bytes': '6779'}, {'name': 'Java', 'bytes': '45217'}, {'name': 'Shell', 'bytes': '879'}]} |
gfx = require 'gfx.js'
-- initialize context / server
gfx.listservers()
-- exit
os.exit()
| {'content_hash': 'f9171cc6679293507e8b1b19bf08fabd', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 30, 'avg_line_length': 13.142857142857142, 'alnum_prop': 0.6739130434782609, 'repo_name': 'soumith/gfx.js', 'id': '42b15ecc2984c8256bf77ff12b0b33dd59fd0f4b', 'size': '173', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'clients/torch/ps.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '29084'}, {'name': 'JavaScript', 'bytes': '1582017'}, {'name': 'Lua', 'bytes': '15737'}, {'name': 'Perl', 'bytes': '1473'}, {'name': 'Python', 'bytes': '4753'}, {'name': 'Shell', 'bytes': '1882'}]} |
jest.mock('child_process');
jest.mock('../../models/meeting.accessors');
jest.mock('../../models/issue.accessors');
jest.mock('../../models/vote.accessors');
jest.mock('../../models/user.accessors');
jest.mock('../../utils/socketAction');
const { execSync } = require('child_process');
execSync.mockImplementation(() => Buffer.from('fake_git_hash'));
const connection = require('../connection');
const { getActiveGenfors } = require('../../models/meeting.accessors');
const { getAnonymousUser, getUsers } = require('../../models/user.accessors');
const { getVotes, getUserVote, getAnonymousUserVote } = require('../../models/vote.accessors');
const { getActiveQuestion, getIssueWithAlternatives, getConcludedIssues, getIssueById } = require('../../models/issue.accessors');
const { waitForAction } = require('../../utils/socketAction');
const { generateSocket, generateGenfors, generateAnonymousUser, generateIssue, generateVote, generateUser } = require('../../utils/generateTestData');
const permissionLevels = require('../../../common/auth/permissions');
const { VOTING_FINISHED } = require('../../../common/actionTypes/issues');
describe('connection', () => {
beforeEach(() => {
getActiveGenfors.mockImplementation(async () => generateGenfors());
getAnonymousUser.mockImplementation(
async (passwordHash, onlinewebId, meetingId) => generateAnonymousUser({
passwordHash,
meetingId,
},
));
getActiveQuestion.mockImplementation(async () => generateIssue());
getIssueWithAlternatives.mockImplementation(async () => generateIssue({ id: '2' }));
getConcludedIssues.mockImplementation(async meetingId => [
generateIssue({ meetingId, id: '2' }),
generateIssue({ meetingId, id: '2' }),
generateIssue({ meetingId, id: '2' }),
generateIssue({ meetingId, id: '2' }),
]);
getVotes.mockImplementation(async issueId => [
generateVote({ issueId, id: '1' }),
generateVote({ issueId, id: '2' }),
generateVote({ issueId, id: '3' }),
generateVote({ issueId, id: '4' }),
]);
getUserVote.mockImplementation(
async () => null,
);
getAnonymousUserVote.mockImplementation(
async () => null,
);
getUsers.mockImplementation(async () => [generateUser()]);
getIssueById.mockImplementation(async id => generateIssue({ id }));
waitForAction.mockImplementation(async () => ({ passwordHash: 'fake_password_hash' }));
});
it('emits correct actions when signed in and active genfors', async () => {
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when signed in and no active genfors', async () => {
getActiveGenfors.mockImplementation(async () => null);
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when user has not completed registration and no genfors is active', async () => {
getActiveGenfors.mockImplementation(async () => null);
const socket = generateSocket({ completedRegistration: false });
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when validation of password hash returns false', async () => {
getAnonymousUser.mockImplementation(async () => null);
const socket = generateSocket({ completedRegistration: true });
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when validation of password hash returns throws error', async () => {
getAnonymousUser.mockImplementation(async () => { throw new Error('Failed'); });
getActiveGenfors.mockImplementation(async () => null);
const socket = generateSocket({ completedRegistration: false });
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when there is no active question', async () => {
getActiveQuestion.mockImplementation(async () => null);
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when retrieving votes fails', async () => {
getVotes.mockImplementation(async () => { throw new Error('Failed'); });
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when active question is secret', async () => {
getActiveQuestion.mockImplementation(async () => generateIssue({ secret: true }));
getIssueById.mockImplementation(async id => generateIssue({ id, secret: true }));
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when user has already voted', async () => {
getUserVote.mockImplementation(
async (issueId, userId) => generateVote({ issueId, userId }),
);
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when retrieving active question fails', async () => {
getActiveQuestion.mockImplementation(async () => { throw new Error('Failed'); });
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when retrieving questions fails', async () => {
getConcludedIssues.mockImplementation(async () => { throw new Error('Failed'); });
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits sensitive data like meeting pin if user is manager', async () => {
const socket = generateSocket({ permissions: permissionLevels.IS_MANAGER });
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits final votes for issue if user is manager and voting is finished', async () => {
getActiveQuestion.mockImplementation(async () => generateIssue({ status: VOTING_FINISHED }));
const socket = generateSocket({ permissions: permissionLevels.IS_MANAGER });
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits question without final votes if voting is finished and user is not manager', async () => {
getActiveQuestion.mockImplementation(async () => generateIssue({ status: VOTING_FINISHED }));
const socket = generateSocket({ permissions: permissionLevels.CAN_VOTE });
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
it('emits correct actions when retrieving active genfors fails', async () => {
getActiveGenfors.mockImplementation(async () => { throw new Error('Failed'); });
const socket = generateSocket();
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
});
describe('connection when no meeting', () => {
it('warns about no active meeting', async () => {
const socket = generateSocket({ meetingId: null });
await connection(socket);
expect(socket.emit.mock.calls).toMatchSnapshot();
expect(socket.broadcast.emit.mock.calls).toEqual([]);
});
});
| {'content_hash': 'b391d17c1e00cec175933edd1af1e233', 'timestamp': '', 'source': 'github', 'line_count': 200, 'max_line_length': 150, 'avg_line_length': 41.28, 'alnum_prop': 0.686531007751938, 'repo_name': 'dotkom/super-duper-fiesta', 'id': 'b53ab045353a209ca44c82cfa9acf1272dc37c9c', 'size': '8256', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'server/channels/__tests__/connection.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '14424'}, {'name': 'HTML', 'bytes': '355'}, {'name': 'JavaScript', 'bytes': '282325'}, {'name': 'Shell', 'bytes': '88'}]} |
/**
*
*/
package com.juxtapose.example.ch11.multithread;
import java.util.List;
import org.springframework.batch.item.ItemWriter;
/**
*
* @author bruce.liu(mailto:[email protected])
* 2013-11-16下午10:58:20
*/
public class ConsoleWriter implements ItemWriter<String> {
public void write(List<? extends String> items) throws Exception {
System.out.print("Write begin:");
for(String item : items){
System.out.print(item + ",");
}
System.out.print("Write end!!");
System.out.println("Job Write Thread name: " + Thread.currentThread().getName());
}
}
| {'content_hash': '12faba1570edef7542c50ecc7a5e66ae', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 83, 'avg_line_length': 23.076923076923077, 'alnum_prop': 0.6616666666666666, 'repo_name': 'lihongjie/spring-tutorial', 'id': '9b6fed2fe66ab498e602af95e364802881c92a4f', 'size': '604', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SpringBatchSample/spring-batch-example/src/main/java/com/juxtapose/example/ch11/multithread/ConsoleWriter.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '25018'}, {'name': 'CSS', 'bytes': '68190'}, {'name': 'CoffeeScript', 'bytes': '4557'}, {'name': 'FreeMarker', 'bytes': '38378'}, {'name': 'Groovy', 'bytes': '319'}, {'name': 'HTML', 'bytes': '306404'}, {'name': 'Java', 'bytes': '1461542'}, {'name': 'JavaScript', 'bytes': '377055'}, {'name': 'PLpgSQL', 'bytes': '1294'}, {'name': 'Roff', 'bytes': '197'}, {'name': 'Shell', 'bytes': '35375'}, {'name': 'TypeScript', 'bytes': '15241'}]} |
// ***********************************************************************
// Assembly : EveLib.ZKillboard
// Author : larsd
// Created : 02-16-2016
//
// Last Modified By : larsd
// Last Modified On : 02-16-2016
// ***********************************************************************
// <copyright file="EntityType.cs" company="Lars Kristian Dahl">
// Copyright © 2015
// </copyright>
// <summary></summary>
// ***********************************************************************
namespace eZet.EveLib.ZKillboardModule {
/// <summary>
/// Enum EntityType
/// </summary>
public enum EntityType {
/// <summary>
/// The character identifier
/// </summary>
CharacterId,
/// <summary>
/// The corporation identifier
/// </summary>
CorporationId,
/// <summary>
/// The alliance identifier
/// </summary>
AllianceId,
/// <summary>
/// The faction identifier
/// </summary>
FactionId,
/// <summary>
/// The ship type identifier
/// </summary>
ShipTypeId,
/// <summary>
/// The group identifier
/// </summary>
GroupId,
/// <summary>
/// The solar system identifier
/// </summary>
SolarSystemId,
/// <summary>
/// The region identifier
/// </summary>
RegionId
}
} | {'content_hash': 'b79f59b75efc738fd5d688df7408050b', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 75, 'avg_line_length': 27.735849056603772, 'alnum_prop': 0.4217687074829932, 'repo_name': 'ezet/evelib', 'id': '6ab55dbfdd320367c497d67d5e6fd06f286420cb', 'size': '1473', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'EveLib.ZKillboard/EntityType.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1164'}, {'name': 'C#', 'bytes': '1315646'}]} |
var _ = require('lodash');
var buildConfig = require('../../../config/build.config.js');
// We don't need to publish all of a doc's data to the app, that will
// add many kilobytes of loading overhead.
function publicDocData(doc, extraData) {
var options = _.assign(extraData || {}, { hasDemo: (doc.docType === 'directive') });
// This RegEx always retrieves the last source descriptor.
// For example it retrieves from `/opt/material/src/core/services/ripple/ripple.js` the following
// source descriptor: `src/core/`.
// This is needed because components are not only located in `src/components`.
var descriptor = doc.fileInfo.filePath.toString().match(/src\/.*?\//g).pop();
if (descriptor) {
descriptor = descriptor.substring(descriptor.indexOf('/') + 1, descriptor.lastIndexOf('/'));
}
return buildDocData(doc, options, descriptor || 'components');
}
function coreServiceData(doc, extraData) {
var options = _.assign(extraData || {}, { hasDemo: false });
return buildDocData(doc, options, 'core');
}
function buildDocData(doc, extraData, descriptor) {
var module = 'material.' + descriptor;
var githubBaseUrl = buildConfig.repository + '/blob/master/src/' + descriptor + '/';
var jsName = doc.module.split(module + '.').pop();
var basePathFromProjectRoot = 'src/' + descriptor + '/';
var filePath = doc.fileInfo.filePath;
var indexOfBasePath = filePath.indexOf(basePathFromProjectRoot);
var path = filePath.substr(indexOfBasePath + basePathFromProjectRoot.length, filePath.length);
return _.assign({
name: doc.name,
type: doc.docType,
outputPath: doc.outputPath,
url: doc.path,
label: doc.label || doc.name,
module: module,
githubUrl: githubBaseUrl + path
}, extraData);
}
module.exports = function componentsGenerateProcessor(log, moduleMap) {
return {
$runAfter: ['paths-computed'],
$runBefore: ['rendering-docs'],
$process: process
};
function process(docs) {
var components = _(docs)
.filter(function(doc) {
// We are not interested in docs that are not in a module
// We are only interested in pages that are not landing pages
return doc.docType !== 'componentGroup' && doc.module;
})
.filter('module')
.groupBy('module')
.map(function(moduleDocs, moduleName) {
var moduleDoc = _.find(docs, {
docType: 'module',
name: moduleName
});
if (!moduleDoc) return;
return publicDocData(moduleDoc, {
docs: moduleDocs
.filter(function(doc) {
// Private isn't set to true, just to an empty string if @private is supplied
return doc.docType !== 'module';
})
.map(publicDocData)
});
})
.filter() //remove null items
.value();
var EXPOSED_CORE_SERVICES = '$mdMedia';
var services = _(docs).filter(function(doc) {
return doc.docType == 'service' &&
doc.module == 'material.core' &&
EXPOSED_CORE_SERVICES.indexOf(doc.name) != -1;
}).map(coreServiceData).value();
docs.push({
name: 'SERVICES',
template: 'constant-data.template.js',
outputPath: 'js/services-data.js',
items: services
});
docs.push({
name: 'COMPONENTS',
template: 'constant-data.template.js',
outputPath: 'js/components-data.js',
items: components
});
}
};
| {'content_hash': '710c97a6ad7d7ff0c77a90557897e12c', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 99, 'avg_line_length': 31.787037037037038, 'alnum_prop': 0.6318089134867463, 'repo_name': 'colinskow/material', 'id': '6aa846d8274d72733e96124e1bea1af24838cc6f', 'size': '3433', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'docs/config/processors/componentsData.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '194915'}, {'name': 'HTML', 'bytes': '110461'}, {'name': 'JavaScript', 'bytes': '1291628'}, {'name': 'PHP', 'bytes': '7211'}, {'name': 'Shell', 'bytes': '7811'}]} |
source $DETA/util.sh
source $DETA/asset.sh
THIS_PATH=$(dirname $(pwd)) # we execute in bin/
cp $THIS_PATH/blog/tumblr.html /tmp/
cp $THIS_PATH/assets/css/reset.css /tmp/
cp $THIS_PATH/assets/css/u1m.css /tmp/
cp $THIS_PATH/assets/css/highlight.css /tmp/
# Assets pipeline
COMPRESSOR_JS="yuicompressor"
COMPRESSOR_CSS="yuicompressor"
myth /tmp/reset.css /tmp/reset.css
myth /tmp/u1m.css /tmp/u1m.css
myth /tmp/highlight.css /tmp/highlight.css
compress_css /tmp/reset.css /tmp/reset.css
compress_css /tmp/u1m.css /tmp/u1m.css
compress_css /tmp/highlight.css /tmp/highlight.css
fill "../img/bg2.png" "http://static.tumblr.com/5za9i77/x4Inc7ltk/bg2.png" /tmp/u1m.css
fill "../img/bg2dark.png" "http://static.tumblr.com/5za9i77/Qtnnc7lwb/bg2dark.png" /tmp/u1m.css
fill __YEAR__ $(date +%Y) /tmp/tumblr.html
# This is pretty hacky, but I currently see
# no better solution to work arround sed's limitations (escaping).
php -r "echo str_replace('__STYLES_RESET__', file_get_contents('/tmp/reset.css'), file_get_contents('/tmp/tumblr.html'));" > /tmp/tumblr_temp.html
mv -v /tmp/tumblr_temp.html /tmp/tumblr.html
php -r "echo str_replace('__STYLES_U1M__', file_get_contents('/tmp/u1m.css'), file_get_contents('/tmp/tumblr.html'));" > /tmp/tumblr_temp.html
mv -v /tmp/tumblr_temp.html /tmp/tumblr.html
php -r "echo str_replace('__STYLES_HIGHLIGHT__', file_get_contents('/tmp/highlight.css'), file_get_contents('/tmp/tumblr.html'));" > /tmp/tumblr_temp.html
mv -v /tmp/tumblr_temp.html /tmp/tumblr.html
cat /tmp/tumblr.html
| {'content_hash': '72745393c2e6d06ca87f0a6facd24c1f', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 154, 'avg_line_length': 40.10526315789474, 'alnum_prop': 0.7204724409448819, 'repo_name': 'UnionOfRAD/site', 'id': 'c62eabab973ae46b605bd06995162f72ef365a16', 'size': '1726', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'bin/task/generate-tumblr-theme.sh', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '32902'}, {'name': 'HTML', 'bytes': '6605'}, {'name': 'Hack', 'bytes': '139'}, {'name': 'JavaScript', 'bytes': '18153'}, {'name': 'PHP', 'bytes': '125955'}, {'name': 'Shell', 'bytes': '5584'}]} |
package org.elasticsearch.http.netty;
import org.elasticsearch.http.netty.pipelining.OrderedUpstreamMessageEvent;
import org.elasticsearch.rest.support.RestUtils;
import org.jboss.netty.channel.*;
import org.jboss.netty.handler.codec.http.HttpRequest;
import java.util.regex.Pattern;
/**
*
*/
@ChannelHandler.Sharable
public class HttpRequestHandler extends SimpleChannelUpstreamHandler {
private final NettyHttpServerTransport serverTransport;
private final Pattern corsPattern;
private final boolean httpPipeliningEnabled;
public HttpRequestHandler(NettyHttpServerTransport serverTransport) {
this.serverTransport = serverTransport;
this.corsPattern = RestUtils.getCorsSettingRegex(serverTransport.settings());
this.httpPipeliningEnabled = serverTransport.pipelining;
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
HttpRequest request;
OrderedUpstreamMessageEvent oue = null;
if (this.httpPipeliningEnabled && e instanceof OrderedUpstreamMessageEvent) {
oue = (OrderedUpstreamMessageEvent) e;
request = (HttpRequest) oue.getMessage();
} else {
request = (HttpRequest) e.getMessage();
}
// the netty HTTP handling always copy over the buffer to its own buffer, either in NioWorker internally
// when reading, or using a cumalation buffer
NettyHttpRequest httpRequest = new NettyHttpRequest(request, e.getChannel());
if (oue != null) {
serverTransport.dispatchRequest(httpRequest, new NettyHttpChannel(serverTransport, httpRequest, corsPattern, oue));
} else {
serverTransport.dispatchRequest(httpRequest, new NettyHttpChannel(serverTransport, httpRequest, corsPattern));
}
super.messageReceived(ctx, e);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
serverTransport.exceptionCaught(ctx, e);
}
}
| {'content_hash': '5e9295e3f2a750137254df77918a4ae0', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 127, 'avg_line_length': 37.345454545454544, 'alnum_prop': 0.7278481012658228, 'repo_name': 'aparo/elasticsearch', 'id': 'd62dc0abbda90dbd5eaf79745488eba28580ce9e', 'size': '2842', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/elasticsearch/http/netty/HttpRequestHandler.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '87'}, {'name': 'Groovy', 'bytes': '299'}, {'name': 'HTML', 'bytes': '5724'}, {'name': 'Java', 'bytes': '27297320'}, {'name': 'Perl', 'bytes': '6858'}, {'name': 'Python', 'bytes': '64133'}, {'name': 'Ruby', 'bytes': '32034'}, {'name': 'Shell', 'bytes': '34718'}]} |
module Azure::NetApp::Mgmt::V2019_07_01
module Models
#
# List of NetApp account resources
#
class NetAppAccountList
include MsRestAzure
# @return [Array<NetAppAccount>] Multiple NetApp accounts
attr_accessor :value
#
# Mapper for NetAppAccountList class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'netAppAccountList',
type: {
name: 'Composite',
class_name: 'NetAppAccountList',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'NetAppAccountElementType',
type: {
name: 'Composite',
class_name: 'NetAppAccount'
}
}
}
}
}
}
}
end
end
end
end
| {'content_hash': '1e66bb474c6777cf6a80f44c02855151', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 66, 'avg_line_length': 26.46, 'alnum_prop': 0.4595616024187453, 'repo_name': 'Azure/azure-sdk-for-ruby', 'id': 'c69e6a4b7ea0833797c762263ae61810a339c00d', 'size': '1487', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'management/azure_mgmt_netapp/lib/2019-07-01/generated/azure_mgmt_netapp/models/net_app_account_list.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '345216400'}, {'name': 'Shell', 'bytes': '305'}]} |
// 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.cloudstack.framework.events;
public interface EventSubscriber {
/**
* Callback method. EventBus calls this method on occurrence of subscribed event
*
* @param event details of the event
*/
void onEvent(Event event);
}
| {'content_hash': '97730898f54684c5e6b9e7ec4ea5c5ea', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 84, 'avg_line_length': 38.17857142857143, 'alnum_prop': 0.7408793264733395, 'repo_name': 'GabrielBrascher/cloudstack', 'id': '511ebff17d22a6961856097c07b3e66291e3d37e', 'size': '1069', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'framework/events/src/main/java/org/apache/cloudstack/framework/events/EventSubscriber.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '9979'}, {'name': 'C#', 'bytes': '2356211'}, {'name': 'CSS', 'bytes': '42504'}, {'name': 'Dockerfile', 'bytes': '4189'}, {'name': 'FreeMarker', 'bytes': '4887'}, {'name': 'Groovy', 'bytes': '146420'}, {'name': 'HTML', 'bytes': '53626'}, {'name': 'Java', 'bytes': '38859783'}, {'name': 'JavaScript', 'bytes': '995137'}, {'name': 'Less', 'bytes': '28250'}, {'name': 'Makefile', 'bytes': '871'}, {'name': 'Python', 'bytes': '12977377'}, {'name': 'Ruby', 'bytes': '22732'}, {'name': 'Shell', 'bytes': '744445'}, {'name': 'Vue', 'bytes': '2012353'}, {'name': 'XSLT', 'bytes': '57835'}]} |
<?xml version="1.0"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ctA022.xsd"/>
| {'content_hash': 'e38e5b8bbe6ccccd3d19986f244ab9a2', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 104, 'avg_line_length': 64.5, 'alnum_prop': 0.7286821705426356, 'repo_name': 'Schematron/schematron', 'id': '84f47f069911c4a508fff4b63d4134f5de7c2a6b', 'size': '129', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'trunk/xsd2sch/test/msData/complexType/ctA022.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2510'}, {'name': 'HTML', 'bytes': '1740763'}, {'name': 'Java', 'bytes': '70415'}, {'name': 'PHP', 'bytes': '43485'}, {'name': 'Red', 'bytes': '9274'}, {'name': 'XProc', 'bytes': '16202'}, {'name': 'XSLT', 'bytes': '1001682'}]} |
package org.apache.airavata.registry.core.experiment.catalog.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class UserPK implements Serializable {
private final static Logger logger = LoggerFactory.getLogger(UserPK.class);
private String gatewayId;
private String userName;
@Id
@Column(name = "GATEWAY_ID")
public String getGatewayId() {
return gatewayId;
}
public void setGatewayId(String gatewayId) {
this.gatewayId = gatewayId;
}
@Id
@Column(name = "USER_NAME")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserPK that = (UserPK) o;
if (getGatewayId() != null ? !getGatewayId().equals(that.getGatewayId()) : that.getGatewayId() != null) return false;
if (getUserName() != null ? !getUserName().equals(that.getUserName()) : that.getUserName() != null) return false;
return true;
}
@Override
public int hashCode() {
int result = getGatewayId() != null ? getGatewayId().hashCode() : 0;
result = 31 * result + (getUserName() != null ? getUserName().hashCode() : 0);
return result;
}
} | {'content_hash': '28cb62f8e37da3abe8257e3bc1835a50', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 125, 'avg_line_length': 26.892857142857142, 'alnum_prop': 0.6401062416998672, 'repo_name': 'gouravshenoy/airavata', 'id': 'ea01588112791e77c860e5a1b45509b603836dba', 'size': '2317', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/registry/registry-core/src/main/java/org/apache/airavata/registry/core/experiment/catalog/model/UserPK.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5598'}, {'name': 'C', 'bytes': '53885'}, {'name': 'C++', 'bytes': '7147253'}, {'name': 'CSS', 'bytes': '26656'}, {'name': 'HTML', 'bytes': '84328'}, {'name': 'Java', 'bytes': '34853075'}, {'name': 'PHP', 'bytes': '294193'}, {'name': 'Python', 'bytes': '295765'}, {'name': 'Shell', 'bytes': '58504'}, {'name': 'Thrift', 'bytes': '423314'}, {'name': 'XSLT', 'bytes': '34643'}]} |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>PageIndicator Tests</title>
<title>PageIndicator Tests</title>
<link href="css/PageIndicatorTests.css" rel="stylesheet"/>
<script type="text/javascript" src="../../deviceTheme.js" data-dojo-config="mblThemeFiles: ['base','PageIndicator']"></script>
<script type="text/javascript" src="../../../../dojo/dojo.js" data-dojo-config="async: true, parseOnLoad: true"></script>
<script language="JavaScript" type="text/javascript">
var WIDGET_PROGRAMMATICALLY = 2;
</script>
<script type="text/javascript" src="PageIndicatorTests.js"></script>
</head>
<body style="visibility:hidden;background-color:#6D6D6D">
<div data-dojo-type="dojox.mobile.SwapView">
<h1>View 1</h1>
</div>
<div data-dojo-type="dojox.mobile.SwapView">
<h1>View 2</h1>
</div>
<div data-dojo-type="dojox.mobile.SwapView">
<h1>View 3</h1>
</div>
<div data-dojo-type="dojox.mobile.SwapView">
<h1>View 4</h1>
</div>
<div data-dojo-type="dojox.mobile.SwapView">
<h1>View 5</h1>
</div>
<div id="dojox_mobile_PageIndicator_0" fixed="bottom"></div>
</body>
</html>
| {'content_hash': 'a0bbc7f7799d141faea3e371948984bb', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 126, 'avg_line_length': 33.25, 'alnum_prop': 0.7022556390977444, 'repo_name': 'kitsonk/expo', 'id': 'afc46372d426d85b2fd9817115e409a8e378b6cf', 'size': '1330', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/dojox/mobile/tests/doh/PageIndicatorTests3.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '3364228'}, {'name': 'PHP', 'bytes': '40456'}, {'name': 'Shell', 'bytes': '2197'}]} |
from .dense_ import *
from .dropout_ import *
from .gated import *
__all__ = [
'as_gated', 'dense', 'dropout',
]
| {'content_hash': '296afbb6770ced2dc449c9a9dd93c996', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 35, 'avg_line_length': 16.857142857142858, 'alnum_prop': 0.5847457627118644, 'repo_name': 'korepwx/tfsnippet', 'id': 'f273c8f96367239f6bd6370d191cf474e71928c6', 'size': '118', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dependabot/pip/tensorflow-2.5.3', 'path': 'tfsnippet/layers/core/__init__.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '471912'}]} |
#ifndef ARM_EX_TABLES_H
#define ARM_EX_TABLES_H
typedef enum arm_exbuf_cmd {
ARM_EXIDX_CMD_FINISH,
ARM_EXIDX_CMD_DATA_PUSH,
ARM_EXIDX_CMD_DATA_POP,
ARM_EXIDX_CMD_REG_POP,
ARM_EXIDX_CMD_REG_TO_SP,
ARM_EXIDX_CMD_VFP_POP,
ARM_EXIDX_CMD_WREG_POP,
ARM_EXIDX_CMD_WCGR_POP,
ARM_EXIDX_CMD_RESERVED,
ARM_EXIDX_CMD_REFUSED,
} arm_exbuf_cmd_t;
struct arm_exbuf_data
{
arm_exbuf_cmd_t cmd;
uint32_t data;
};
#define arm_exidx_extract UNW_OBJ(arm_exidx_extract)
#define arm_exidx_decode UNW_OBJ(arm_exidx_decode)
#define arm_exidx_apply_cmd UNW_OBJ(arm_exidx_apply_cmd)
int arm_exidx_extract (struct dwarf_cursor *c, uint8_t *buf);
int arm_exidx_decode (const uint8_t *buf, uint8_t len, struct dwarf_cursor *c);
int arm_exidx_apply_cmd (struct arm_exbuf_data *edata, struct dwarf_cursor *c);
#endif // ARM_EX_TABLES_H
| {'content_hash': 'e27ab45c06a112dae21097467e6aed4f', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 79, 'avg_line_length': 25.848484848484848, 'alnum_prop': 0.7022274325908558, 'repo_name': 'krytarowski/libunwind', 'id': '9df5e0a9fa4b9b224bd9efdb3edf0e1c0cdec301', 'size': '1999', 'binary': False, 'copies': '96', 'ref': 'refs/heads/master', 'path': 'include/tdep-arm/ex_tables.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '93631'}, {'name': 'C', 'bytes': '1688551'}, {'name': 'C++', 'bytes': '5044'}, {'name': 'Shell', 'bytes': '157354'}]} |
set -e
# With env variable WITH_XDEBUG=1 xdebug extension will be enabled
[ ! -z "$WITH_XDEBUG" ] && docker-php-ext-enable xdebug
# Provide github token if you are using composer a lot in non-interactive mode
# Otherwise one day it will get stuck with request for authorization
# https://github.com/settings/tokens
if [[ ! -z "$COMPOSER_GITHUB" ]]
then
composer config --global github-oauth.github.com "$COMPOSER_GITHUB"
fi
#
# If $TIMEZONE variable is passed to the image - it will set system timezone
# and php.ini date.timezone value as well
# Overwise the default system Etc/UTC timezone will be used
#
# Also you can set the php timezone with direct setting it in php.ini
# within your .gitlab-ci.yml like
# before_script:
# - echo "America/New_York" > /usr/local/etc/php/conf.d/timezone.ini
if [[ ! -z "$TIMEZONE" ]]
then
echo "$TIMEZONE" > /etc/timezone
dpkg-reconfigure -f noninteractive tzdata
fi
echo "date.timezone=`cat /etc/timezone`" > /usr/local/etc/php/conf.d/timezone.ini
# print PHP version
echo "PHP: "
php --version
# print NodeJs version
echo "NodeJs: "
node --version
# print Yarn version
echo "Yarn: "
yarn --version
exec "$@"
| {'content_hash': '68eb7b48d26a41a28e6ceb3dff6285c8', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 81, 'avg_line_length': 28.317073170731707, 'alnum_prop': 0.7243755383290267, 'repo_name': 'ambroisemaupate/docker', 'id': 'c4819dd1491aea261c64c163928a981cef163b1c', 'size': '1173', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'php74-runner/entrypoint.sh', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '64760'}, {'name': 'Makefile', 'bytes': '972'}, {'name': 'Shell', 'bytes': '31533'}]} |
import akka.actor.{ActorSystem, Props}
import database.DatabaseContext
import scala.concurrent.ExecutionContext.Implicits.global
/**
* Created by franblas on 25/03/17.
*/
object Main extends App {
DatabaseContext
val system = ActorSystem()
system.actorOf(Props(new Server()))
system.whenTerminated.onComplete(res => {
println(res)
DatabaseContext.closeClient()
})
} | {'content_hash': '8f3f436e802aef9f0d8f02ed4c7bd48e', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 57, 'avg_line_length': 22.88235294117647, 'alnum_prop': 0.7403598971722365, 'repo_name': 'franblas/NAOC', 'id': '82820ee6d0a08a804e920e9c9050e125e235c7fe', 'size': '389', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/scala/App.scala', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Makefile', 'bytes': '94'}, {'name': 'Scala', 'bytes': '160701'}]} |
/*******************************************************************************
* OpenAjax.js
*
* Reference implementation of the OpenAjax Hub, as specified by OpenAjax Alliance.
* Specification is under development at:
*
* http://www.openajax.org/member/wiki/OpenAjax_Hub_Specification
*
* Copyright 2006-2007 OpenAjax Alliance
*
* 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.
*
******************************************************************************/
// prevent re-definition of the OpenAjax object
if(!window["OpenAjax"]){
OpenAjax = new function(){
// summary: the OpenAjax hub
// description: see http://www.openajax.org/member/wiki/OpenAjax_Hub_Specification
var t = true;
var f = false;
var g = window;
var libs;
var ooh = "org.openajax.hub.";
var h = {};
this.hub = h;
h.implementer = "http://openajax.org";
h.implVersion = "0.6";
h.specVersion = "0.6";
h.implExtraData = {};
var libs = {};
h.libraries = libs;
h.registerLibrary = function(prefix, nsURL, version, extra){
libs[prefix] = {
prefix: prefix,
namespaceURI: nsURL,
version: version,
extraData: extra
};
this.publish(ooh+"registerLibrary", libs[prefix]);
}
h.unregisterLibrary = function(prefix){
this.publish(ooh+"unregisterLibrary", libs[prefix]);
delete libs[prefix];
}
h._subscriptions = { c:{}, s:[] };
h._cleanup = [];
h._subIndex = 0;
h._pubDepth = 0;
h.subscribe = function(name, callback, scope, subscriberData, filter){
if(!scope){
scope = window;
}
var handle = name + "." + this._subIndex;
var sub = { scope: scope, cb: callback, fcb: filter, data: subscriberData, sid: this._subIndex++, hdl: handle };
var path = name.split(".");
this._subscribe(this._subscriptions, path, 0, sub);
return handle;
}
h.publish = function(name, message){
var path = name.split(".");
this._pubDepth++;
this._publish(this._subscriptions, path, 0, name, message);
this._pubDepth--;
if((this._cleanup.length > 0) && (this._pubDepth == 0)){
for(var i = 0; i < this._cleanup.length; i++){
this.unsubscribe(this._cleanup[i].hdl);
}
delete(this._cleanup);
this._cleanup = [];
}
}
h.unsubscribe = function(sub){
var path = sub.split(".");
var sid = path.pop();
this._unsubscribe(this._subscriptions, path, 0, sid);
}
h._subscribe = function(tree, path, index, sub){
var token = path[index];
if(index == path.length){
tree.s.push(sub);
}else{
if(typeof tree.c == "undefined"){
tree.c = {};
}
if(typeof tree.c[token] == "undefined"){
tree.c[token] = { c: {}, s: [] };
this._subscribe(tree.c[token], path, index + 1, sub);
}else{
this._subscribe( tree.c[token], path, index + 1, sub);
}
}
}
h._publish = function(tree, path, index, name, msg){
if(typeof tree != "undefined"){
var node;
if(index == path.length) {
node = tree;
}else{
this._publish(tree.c[path[index]], path, index + 1, name, msg);
this._publish(tree.c["*"], path, index + 1, name, msg);
node = tree.c["**"];
}
if(typeof node != "undefined"){
var callbacks = node.s;
var max = callbacks.length;
for(var i = 0; i < max; i++){
if(callbacks[i].cb){
var sc = callbacks[i].scope;
var cb = callbacks[i].cb;
var fcb = callbacks[i].fcb;
var d = callbacks[i].data;
if(typeof cb == "string"){
// get a function object
cb = sc[cb];
}
if(typeof fcb == "string"){
// get a function object
fcb = sc[fcb];
}
if((!fcb) ||
(fcb.call(sc, name, msg, d))) {
cb.call(sc, name, msg, d);
}
}
}
}
}
}
h._unsubscribe = function(tree, path, index, sid) {
if(typeof tree != "undefined") {
if(index < path.length) {
var childNode = tree.c[path[index]];
this._unsubscribe(childNode, path, index + 1, sid);
if(childNode.s.length == 0) {
for(var x in childNode.c)
return;
delete tree.c[path[index]];
}
return;
}
else {
var callbacks = tree.s;
var max = callbacks.length;
for(var i = 0; i < max; i++)
if(sid == callbacks[i].sid) {
if(this._pubDepth > 0) {
callbacks[i].cb = null;
this._cleanup.push(callbacks[i]);
}
else
callbacks.splice(i, 1);
return;
}
}
}
}
// The following function is provided for automatic testing purposes.
// It is not expected to be deployed in run-time OpenAjax Hub implementations.
h.reinit = function()
{
for (var lib in OpenAjax.hub.libraries) {
delete OpenAjax.hub.libraries[lib];
}
OpenAjax.hub.registerLibrary("OpenAjax", "http://openajax.org/hub", "0.6", {});
delete OpenAjax._subscriptions;
OpenAjax._subscriptions = {c:{},s:[]};
delete OpenAjax._cleanup;
OpenAjax._cleanup = [];
OpenAjax._subIndex = 0;
OpenAjax._pubDepth = 0;
}
};
// Register the OpenAjax Hub itself as a library.
OpenAjax.hub.registerLibrary("OpenAjax", "http://openajax.org/hub", "0.6", {});
}
| {'content_hash': 'b6252b9b62aae7a0f97cb10bd55267f6', 'timestamp': '', 'source': 'github', 'line_count': 197, 'max_line_length': 115, 'avg_line_length': 29.79695431472081, 'alnum_prop': 0.559114139693356, 'repo_name': 'ozoneplatform/owf-framework', 'id': '77ba79122bd9a03348e848c50c1d4359d1b787e0', 'size': '6068', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'web-app/js-lib/dojo-release-1.5.0/dojo/OpenAjax.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '8025'}, {'name': 'ActionScript', 'bytes': '117109'}, {'name': 'ApacheConf', 'bytes': '40'}, {'name': 'Batchfile', 'bytes': '7669'}, {'name': 'C#', 'bytes': '18527'}, {'name': 'CSS', 'bytes': '3315352'}, {'name': 'Groff', 'bytes': '456'}, {'name': 'Groovy', 'bytes': '2314003'}, {'name': 'HTML', 'bytes': '12985047'}, {'name': 'Java', 'bytes': '425033'}, {'name': 'JavaScript', 'bytes': '65568257'}, {'name': 'PHP', 'bytes': '571015'}, {'name': 'PLSQL', 'bytes': '404579'}, {'name': 'PLpgSQL', 'bytes': '191325'}, {'name': 'Perl', 'bytes': '6881'}, {'name': 'Python', 'bytes': '3351'}, {'name': 'Ruby', 'bytes': '19203'}, {'name': 'SQLPL', 'bytes': '111737'}, {'name': 'Shell', 'bytes': '27016'}, {'name': 'XSLT', 'bytes': '151867'}]} |
require 'fixtures'
require "seedu"
include Seedu
describe Card, '#initialize' do
it "creates" do
expect(Card.new(Fixtures.card_complete)).to be_a Card
expect(Card.new(Fixtures.card_incomplete)).to be_a Card
end
end
describe Card, '#add_action' do
before :each do
@card = Card.new(Fixtures.card_complete)
end
it "raises error when adding non action" do
expect {
@card.add_action('Not an action')
}.to raise_error(NotASeeduAction)
end
it "adds an action" do
expect {
@card.add_action(Action::Link.new(Fixtures.link_action))
}.not_to raise_error
end
end
describe Card, '#as_json' do
it "serialises" do
card = Card.new(Fixtures.card_complete)
action = Action::Link.new(Fixtures.link_action)
card.add_action(action)
expect(card.as_json).to eq({
title: 'Busker Sam',
description: 'A bit about me',
image_uri: 'http://richardson.co.nz/sam.jpg',
duration: 1800,
coordinates: {
latitude: -37,
longitude: 144
},
actions: [action.as_json]
})
end
end
describe Card, '#to_json' do
it "serialises" do
card = Card.new(Fixtures.card_complete)
action = Action::Link.new(Fixtures.link_action)
card.add_action(action)
expect(card.to_json).to eq('{"title":"Busker Sam","description":"A bit about me","image_uri":"http://richardson.co.nz/sam.jpg","duration":1800,"coordinates":{"latitude":-37,"longitude":144},"actions":[{"title":"Soundcloud","url":"https://soundcloud.com/samuelrichardson","icon":"soundcloud"}]}')
end
end
describe Card, '#send' do
it "sends when card complete" do
stub_request(:post, 'http://www.example.com/cards.json').to_return({body: Fixtures.card_response.to_json, headers: {'Content-Type' => 'application/json'}}) # TODO - json response here
card = Card.new(Fixtures.card_complete)
response = card.send!('http://www.example.com')
expect(response).to be_a Card::Response
expect(response.body['uuid']).to eq(Fixtures.card_response[:uuid])
end
it "errors when card incomplete" do
card = Card.new(Fixtures.card_incomplete)
error = expect {
card.send!('http://www.example.com/create.json')
}.to raise_error(IncompleteCardDetails).with_message('Missing field: coordinates')
end
it "sends to default url" do
stub_request(:post, 'http://www.seeduapp.com/api/cards.json').to_return({body: Fixtures.card_response.to_json, headers: {'Content-Type' => 'application/json'}}) # TODO - json response here
card = Card.new(Fixtures.card_complete)
response = card.send!
expect(response).to be_a Card::Response
expect(response.body['uuid']).to eq(Fixtures.card_response[:uuid])
end
end
| {'content_hash': '3ff362a599a91322850b3160c998f6ef', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 299, 'avg_line_length': 31.905882352941177, 'alnum_prop': 0.6707227138643068, 'repo_name': 'Rodeoclash/SeeduGem', 'id': 'cebb4f698430bbe4ee2a80f52dcbad41689f1abb', 'size': '2712', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/seedu/card_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '10939'}]} |
/**
* @license Highcharts JS v6.0.2 (2017-10-20)
* Client side exporting module
*
* (c) 2015 Torstein Honsi / Oystein Moseng
*
* License: www.highcharts.com/license
*/
'use strict';
(function(factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function(Highcharts) {
(function(Highcharts) {
/**
* Client side exporting module
*
* (c) 2015 Torstein Honsi / Oystein Moseng
*
* License: www.highcharts.com/license
*/
/* global MSBlobBuilder */
var merge = Highcharts.merge,
win = Highcharts.win,
nav = win.navigator,
doc = win.document,
each = Highcharts.each,
domurl = win.URL || win.webkitURL || win,
isMSBrowser = /Edge\/|Trident\/|MSIE /.test(nav.userAgent),
isEdgeBrowser = /Edge\/\d+/.test(nav.userAgent),
// Milliseconds to defer image load event handlers to offset IE bug
loadEventDeferDelay = isMSBrowser ? 150 : 0;
// Dummy object so we can reuse our canvas-tools.js without errors
Highcharts.CanVGRenderer = {};
/**
* Downloads a script and executes a callback when done.
* @param {String} scriptLocation
* @param {Function} callback
*/
function getScript(scriptLocation, callback) {
var head = doc.getElementsByTagName('head')[0],
script = doc.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocation;
script.onload = callback;
script.onerror = function() {
Highcharts.error('Error loading script ' + scriptLocation);
};
head.appendChild(script);
}
// Convert dataURL to Blob if supported, otherwise returns undefined
Highcharts.dataURLtoBlob = function(dataURL) {
if (
win.atob &&
win.ArrayBuffer &&
win.Uint8Array &&
win.Blob &&
domurl.createObjectURL
) {
// Try to convert data URL to Blob
var parts = dataURL.match(/data:([^;]*)(;base64)?,([0-9A-Za-z+/]+)/),
binStr = win.atob(parts[3]), // Assume base64 encoding
buf = new win.ArrayBuffer(binStr.length),
binary = new win.Uint8Array(buf),
blob;
for (var i = 0; i < binary.length; ++i) {
binary[i] = binStr.charCodeAt(i);
}
blob = new win.Blob([binary], {
'type': parts[1]
});
return domurl.createObjectURL(blob);
}
};
// Download contents by dataURL/blob
Highcharts.downloadURL = function(dataURL, filename) {
var a = doc.createElement('a'),
windowRef;
// IE specific blob implementation
// Don't use for normal dataURLs
if (
typeof dataURL !== 'string' &&
!(dataURL instanceof String) &&
nav.msSaveOrOpenBlob
) {
nav.msSaveOrOpenBlob(dataURL, filename);
return;
}
// Some browsers have limitations for data URL lengths. Try to convert to
// Blob or fall back. Edge always needs that blob.
if (isEdgeBrowser || dataURL.length > 2000000) {
dataURL = Highcharts.dataURLtoBlob(dataURL);
if (!dataURL) {
throw 'Data URL length limit reached';
}
}
// Try HTML5 download attr if supported
if (a.download !== undefined) {
a.href = dataURL;
a.download = filename; // HTML5 download attribute
doc.body.appendChild(a);
a.click();
doc.body.removeChild(a);
} else {
// No download attr, just opening data URI
try {
windowRef = win.open(dataURL, 'chart');
if (windowRef === undefined || windowRef === null) {
throw 'Failed to open window';
}
} catch (e) {
// window.open failed, trying location.href
win.location.href = dataURL;
}
}
};
// Get blob URL from SVG code. Falls back to normal data URI.
Highcharts.svgToDataUrl = function(svg) {
// Webkit and not chrome
var webKit = (
nav.userAgent.indexOf('WebKit') > -1 &&
nav.userAgent.indexOf('Chrome') < 0
);
try {
// Safari requires data URI since it doesn't allow navigation to blob
// URLs. Firefox has an issue with Blobs and internal references,
// leading to gradients not working using Blobs (#4550)
if (!webKit && nav.userAgent.toLowerCase().indexOf('firefox') < 0) {
return domurl.createObjectURL(new win.Blob([svg], {
type: 'image/svg+xml;charset-utf-16'
}));
}
} catch (e) {
// Ignore
}
return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
};
// Get data:URL from image URL
// Pass in callbacks to handle results. finallyCallback is always called at the
// end of the process. Supplying this callback is optional. All callbacks
// receive four arguments: imageURL, imageType, callbackArgs and scale.
// callbackArgs is used only by callbacks and can contain whatever.
Highcharts.imageToDataUrl = function(
imageURL,
imageType,
callbackArgs,
scale,
successCallback,
taintedCallback,
noCanvasSupportCallback,
failedLoadCallback,
finallyCallback
) {
var img = new win.Image(),
taintedHandler,
loadHandler = function() {
setTimeout(function() {
var canvas = doc.createElement('canvas'),
ctx = canvas.getContext && canvas.getContext('2d'),
dataURL;
try {
if (!ctx) {
noCanvasSupportCallback(
imageURL,
imageType,
callbackArgs,
scale
);
} else {
canvas.height = img.height * scale;
canvas.width = img.width * scale;
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
// Now we try to get the contents of the canvas.
try {
dataURL = canvas.toDataURL(imageType);
successCallback(
dataURL,
imageType,
callbackArgs,
scale
);
} catch (e) {
taintedHandler(
imageURL,
imageType,
callbackArgs,
scale
);
}
}
} finally {
if (finallyCallback) {
finallyCallback(
imageURL,
imageType,
callbackArgs,
scale
);
}
}
// IE bug where image is not always ready despite calling load
// event.
}, loadEventDeferDelay);
},
// Image load failed (e.g. invalid URL)
errorHandler = function() {
failedLoadCallback(imageURL, imageType, callbackArgs, scale);
if (finallyCallback) {
finallyCallback(imageURL, imageType, callbackArgs, scale);
}
};
// This is called on load if the image drawing to canvas failed with a
// security error. We retry the drawing with crossOrigin set to Anonymous.
taintedHandler = function() {
img = new win.Image();
taintedHandler = taintedCallback;
// Must be set prior to loading image source
img.crossOrigin = 'Anonymous';
img.onload = loadHandler;
img.onerror = errorHandler;
img.src = imageURL;
};
img.onload = loadHandler;
img.onerror = errorHandler;
img.src = imageURL;
};
/**
* Get data URL to an image of an SVG and call download on it
*
* options object:
* - filename: Name of resulting downloaded file without extension
* - type: File type of resulting download
* - scale: Scaling factor of downloaded image compared to source
* - libURL: URL pointing to location of dependency scripts to download on
* demand
*/
Highcharts.downloadSVGLocal = function(
svg,
options,
failCallback,
successCallback
) {
var svgurl,
blob,
objectURLRevoke = true,
finallyHandler,
libURL = options.libURL || Highcharts.getOptions().exporting.libURL,
dummySVGContainer = doc.createElement('div'),
imageType = options.type || 'image/png',
filename = (
(options.filename || 'chart') +
'.' +
(imageType === 'image/svg+xml' ? 'svg' : imageType.split('/')[1])
),
scale = options.scale || 1;
// Allow libURL to end with or without fordward slash
libURL = libURL.slice(-1) !== '/' ? libURL + '/' : libURL;
function svgToPdf(svgElement, margin) {
var width = svgElement.width.baseVal.value + 2 * margin,
height = svgElement.height.baseVal.value + 2 * margin,
pdf = new win.jsPDF( // eslint-disable-line new-cap
'l',
'pt', [width, height]
);
// Workaround for #7090, hidden elements were drawn anyway. It comes
// down to https://github.com/yWorks/svg2pdf.js/issues/28. Check this
// later.
each(
svgElement.querySelectorAll('*[visibility="hidden"]'),
function(node) {
node.parentNode.removeChild(node);
}
);
win.svg2pdf(svgElement, pdf, {
removeInvalid: true
});
return pdf.output('datauristring');
}
function downloadPDF() {
dummySVGContainer.innerHTML = svg;
var textElements = dummySVGContainer.getElementsByTagName('text'),
titleElements,
svgData,
svgElementStyle = dummySVGContainer
.getElementsByTagName('svg')[0].style;
// Workaround for the text styling. Making sure it does pick up the root
// element
each(textElements, function(el) {
// Workaround for the text styling. making sure it does pick up the
// root element
each(['font-family', 'font-size'], function(property) {
if (!el.style[property] && svgElementStyle[property]) {
el.style[property] = svgElementStyle[property];
}
});
el.style['font-family'] = (
el.style['font-family'] &&
el.style['font-family'].split(' ').splice(-1)
);
// Workaround for plotband with width, removing title from text
// nodes
titleElements = el.getElementsByTagName('title');
each(titleElements, function(titleElement) {
el.removeChild(titleElement);
});
});
svgData = svgToPdf(dummySVGContainer.firstChild, 0);
try {
Highcharts.downloadURL(svgData, filename);
if (successCallback) {
successCallback();
}
} catch (e) {
failCallback();
}
}
// Initiate download depending on file type
if (imageType === 'image/svg+xml') {
// SVG download. In this case, we want to use Microsoft specific Blob if
// available
try {
if (nav.msSaveOrOpenBlob) {
blob = new MSBlobBuilder();
blob.append(svg);
svgurl = blob.getBlob('image/svg+xml');
} else {
svgurl = Highcharts.svgToDataUrl(svg);
}
Highcharts.downloadURL(svgurl, filename);
if (successCallback) {
successCallback();
}
} catch (e) {
failCallback();
}
} else if (imageType === 'application/pdf') {
if (win.jsPDF && win.svg2pdf) {
downloadPDF();
} else {
// Must load pdf libraries first. // Don't destroy the object URL
// yet since we are doing things asynchronously. A cleaner solution
// would be nice, but this will do for now.
objectURLRevoke = true;
getScript(libURL + 'jspdf.js', function() {
getScript(libURL + 'svg2pdf.js', function() {
downloadPDF();
});
});
}
} else {
// PNG/JPEG download - create bitmap from SVG
svgurl = Highcharts.svgToDataUrl(svg);
finallyHandler = function() {
try {
domurl.revokeObjectURL(svgurl);
} catch (e) {
// Ignore
}
};
// First, try to get PNG by rendering on canvas
Highcharts.imageToDataUrl(
svgurl,
imageType, { /* args */ },
scale,
function(imageURL) {
// Success
try {
Highcharts.downloadURL(imageURL, filename);
if (successCallback) {
successCallback();
}
} catch (e) {
failCallback();
}
},
function() {
// Failed due to tainted canvas
// Create new and untainted canvas
var canvas = doc.createElement('canvas'),
ctx = canvas.getContext('2d'),
imageWidth = svg.match(
/^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/
)[1] * scale,
imageHeight = svg.match(
/^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/
)[1] * scale,
downloadWithCanVG = function() {
ctx.drawSvg(svg, 0, 0, imageWidth, imageHeight);
try {
Highcharts.downloadURL(
nav.msSaveOrOpenBlob ?
canvas.msToBlob() :
canvas.toDataURL(imageType),
filename
);
if (successCallback) {
successCallback();
}
} catch (e) {
failCallback();
} finally {
finallyHandler();
}
};
canvas.width = imageWidth;
canvas.height = imageHeight;
if (win.canvg) {
// Use preloaded canvg
downloadWithCanVG();
} else {
// Must load canVG first. // Don't destroy the object URL
// yet since we are doing things asynchronously. A cleaner
// solution would be nice, but this will do for now.
objectURLRevoke = true;
// Get RGBColor.js first, then canvg
getScript(libURL + 'rgbcolor.js', function() {
getScript(libURL + 'canvg.js', function() {
downloadWithCanVG();
});
});
}
},
// No canvas support
failCallback,
// Failed to load image
failCallback,
// Finally
function() {
if (objectURLRevoke) {
finallyHandler();
}
}
);
}
};
// Get SVG of chart prepared for client side export. This converts embedded
// images in the SVG to data URIs. The options and chartOptions arguments are
// passed to the getSVGForExport function.
Highcharts.Chart.prototype.getSVGForLocalExport = function(
options,
chartOptions,
failCallback,
successCallback
) {
var chart = this,
images,
imagesEmbedded = 0,
chartCopyContainer,
chartCopyOptions,
el,
i,
l,
// After grabbing the SVG of the chart's copy container we need to do
// sanitation on the SVG
sanitize = function(svg) {
return chart.sanitizeSVG(svg, chartCopyOptions);
},
// Success handler, we converted image to base64!
embeddedSuccess = function(imageURL, imageType, callbackArgs) {
++imagesEmbedded;
// Change image href in chart copy
callbackArgs.imageElement.setAttributeNS(
'http://www.w3.org/1999/xlink',
'href',
imageURL
);
// When done with last image we have our SVG
if (imagesEmbedded === images.length) {
successCallback(sanitize(chartCopyContainer.innerHTML));
}
};
// Hook into getSVG to get a copy of the chart copy's container
Highcharts.wrap(
Highcharts.Chart.prototype,
'getChartHTML',
function(proceed) {
var ret = proceed.apply(
this,
Array.prototype.slice.call(arguments, 1)
);
chartCopyOptions = this.options;
chartCopyContainer = this.container.cloneNode(true);
return ret;
}
);
// Trigger hook to get chart copy
chart.getSVGForExport(options, chartOptions);
images = chartCopyContainer.getElementsByTagName('image');
try {
// If there are no images to embed, the SVG is okay now.
if (!images.length) {
// Use SVG of chart copy
successCallback(sanitize(chartCopyContainer.innerHTML));
return;
}
// Go through the images we want to embed
for (i = 0, l = images.length; i < l; ++i) {
el = images[i];
Highcharts.imageToDataUrl(el.getAttributeNS(
'http://www.w3.org/1999/xlink',
'href'
), 'image/png', {
imageElement: el
}, options.scale,
embeddedSuccess,
// Tainted canvas
failCallback,
// No canvas support
failCallback,
// Failed to load source
failCallback
);
}
} catch (e) {
failCallback();
}
};
/**
* Exporting and offline-exporting modules required. Export a chart to an image
* locally in the user's browser.
*
* @param {Object} exportingOptions
* Exporting options, the same as in {@link
* Highcharts.Chart#exportChart}.
* @param {Options} chartOptions
* Additional chart options for the exported chart. For example a
* different background color can be added here, or `dataLabels`
* for export only.
*/
Highcharts.Chart.prototype.exportChartLocal = function(
exportingOptions,
chartOptions
) {
var chart = this,
options = Highcharts.merge(chart.options.exporting, exportingOptions),
fallbackToExportServer = function() {
if (options.fallbackToExportServer === false) {
if (options.error) {
options.error(options);
} else {
throw 'Fallback to export server disabled';
}
} else {
chart.exportChart(options);
}
},
svgSuccess = function(svg) {
// If SVG contains foreignObjects all exports except SVG will fail,
// as both CanVG and svg2pdf choke on this. Gracefully fall back.
if (
svg.indexOf('<foreignObject') > -1 &&
options.type !== 'image/svg+xml'
) {
fallbackToExportServer();
} else {
Highcharts.downloadSVGLocal(
svg,
options,
fallbackToExportServer
);
}
};
// If we are on IE and in styled mode, add a whitelist to the renderer for
// inline styles that we want to pass through. There are so many styles by
// default in IE that we don't want to blacklist them all.
if (isMSBrowser) {
Highcharts.SVGRenderer.prototype.inlineWhitelist = [
/^blockSize/,
/^border/,
/^caretColor/,
/^color/,
/^columnRule/,
/^columnRuleColor/,
/^cssFloat/,
/^cursor/,
/^fill$/,
/^fillOpacity/,
/^font/,
/^inlineSize/,
/^length/,
/^lineHeight/,
/^opacity/,
/^outline/,
/^parentRule/,
/^rx$/,
/^ry$/,
/^stroke/,
/^textAlign/,
/^textAnchor/,
/^textDecoration/,
/^transform/,
/^vectorEffect/,
/^visibility/,
/^x$/,
/^y$/
];
}
// Always fall back on:
// - MS browsers: Embedded images JPEG/PNG, or any PDF
// - Embedded images and PDF
if (
(
isMSBrowser &&
(
options.type === 'application/pdf' ||
chart.container.getElementsByTagName('image').length &&
options.type !== 'image/svg+xml'
)
) || (
options.type === 'application/pdf' &&
chart.container.getElementsByTagName('image').length
)
) {
fallbackToExportServer();
return;
}
chart.getSVGForLocalExport(
options,
chartOptions,
fallbackToExportServer,
svgSuccess
);
};
// Extend the default options to use the local exporter logic
merge(true, Highcharts.getOptions().exporting, {
libURL: 'https://code.highcharts.com/6.0.2/lib/',
// When offline-exporting is loaded, redefine the menu item definitions
// related to download.
menuItemDefinitions: {
downloadPNG: {
textKey: 'downloadPNG',
onclick: function() {
this.exportChartLocal();
}
},
downloadJPEG: {
textKey: 'downloadJPEG',
onclick: function() {
this.exportChartLocal({
type: 'image/jpeg'
});
}
},
downloadSVG: {
textKey: 'downloadSVG',
onclick: function() {
this.exportChartLocal({
type: 'image/svg+xml'
});
}
},
downloadPDF: {
textKey: 'downloadPDF',
onclick: function() {
this.exportChartLocal({
type: 'application/pdf'
});
}
}
}
});
}(Highcharts));
}));
| {'content_hash': 'fff7fe923d2c494069f668d732c3f015', 'timestamp': '', 'source': 'github', 'line_count': 713, 'max_line_length': 88, 'avg_line_length': 39.87517531556802, 'alnum_prop': 0.411557806619535, 'repo_name': 'sufuf3/cdnjs', 'id': 'df808f14fbc89d2ea7ab8afb96b9a2e75e8dd0c7', 'size': '28431', 'binary': False, 'copies': '47', 'ref': 'refs/heads/master', 'path': 'ajax/libs/highmaps/6.0.2/js/modules/offline-exporting.src.js', 'mode': '33188', 'license': 'mit', 'language': []} |
<?xml version="1.0" encoding="UTF-8"?>
<Erxl xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="erxl.xsd" >
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/2003/xbrl-instance-2003-12-31.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2003/instance</Namespace>
<Prefix>xbrli</Prefix>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/2003/xbrl-linkbase-2003-12-31.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2003/linkbase</Namespace>
<Prefix>link</Prefix>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/2003/xl-2003-12-31.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2003/XLink</Namespace>
<Prefix>xl</Prefix>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/2003/xlink-2003-12-31.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.w3.org/1999/xlink</Namespace>
<Prefix>xlink</Prefix>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/2005/xbrldt-2005.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://xbrl.org/2005/xbrldt</Namespace>
<Prefix>xbrldt</Prefix>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/2006/xbrldi-2006.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://xbrl.org/2006/xbrldi</Namespace>
<Prefix>xbrldi</Prefix>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/lrr/role/negated-2009-12-16.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Roles/Arcroles</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2009/role/negated</Namespace>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/dtr/type/nonNumeric-2009-12-16.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/dtr/type/non-numeric</Namespace>
<Prefix>nonnum</Prefix>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/dtr/type/numeric-2009-12-16.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/dtr/type/numeric</Namespace>
<Prefix>num</Prefix>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/2006/ref-2006-02-27.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2006/ref</Namespace>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/2004/ref-2004-08-10.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2004/ref</Namespace>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/lrr/role/net-2009-12-16.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Roles/Arcroles</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2009/role/net</Namespace>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/lrr/arcrole/factExplanatory-2009-12-16.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Roles/Arcroles</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2009/arcrole/fact-explanatoryFact</Namespace>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/lrr/role/negated-2008-03-31.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Roles/Arcroles</FileTypeName>
<Elements>0</Elements>
<Namespace>http://xbrl.us/us-gaap/negated/2008-03-31</Namespace>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/lrr/arcrole/deprecated-2009-12-16.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Roles/Arcroles</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2009/arcrole/deprecated</Namespace>
</Loc>
<Loc>
<Family>BASE</Family>
<Version>2010</Version>
<Href>http://www.xbrl.org/lrr/role/deprecated-2009-12-16.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Roles/Arcroles</FileTypeName>
<Elements>0</Elements>
<Namespace>http://www.xbrl.org/2009/role/deprecated</Namespace>
</Loc>
<Loc>
<Family>IFRS</Family>
<Version>2010</Version>
<Href>http://xbrl.iasb.org/taxonomy/2010-04-30/ifrs-cor_2010-04-30.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://xbrl.iasb.org/taxonomy/2010-04-30/ifrs</Namespace>
<Prefix>ifrs</Prefix>
</Loc>
<Loc>
<Family>IFRS</Family>
<Version>2011</Version>
<Href>http://xbrl.iasb.org/taxonomy/2011-03-15/ifrs-cor_2010-03-25.xsd</Href>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://xbrl.ifrs.org/taxonomy/2011-03-25/ifrs</Namespace>
<Prefix>ifrs</Prefix>
</Loc>
<!-- other UK files seen in test cases, namespaces needed to be recognized as standard taxonomy -->
<!-- mark all these as BASE to block schema validation in test cases -->
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct/2006-07-03</Namespace>
<Prefix>ct</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-CaseI/2006-07-03</Namespace>
<Prefix>ct-CaseI</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-CaseV/2006-07-03</Namespace>
<Prefix>ct-CaseV</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-CG/2006-07-03</Namespace>
<Prefix>ct-CG</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-CT/2006-07-03</Namespace>
<Prefix>ct-CT</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-default/2006-07-03</Namespace>
<Prefix>ct-default</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-DR/2006-07-03</Namespace>
<Prefix>ct-DR</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-FixedAss/2006-07-03</Namespace>
<Prefix>ct-FixedAss</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-OtherInc/2006-07-03</Namespace>
<Prefix>ct-OtherInc</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-PL/2006-07-03</Namespace>
<Prefix>ct-PL</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-roles/2006-07-03</Namespace>
<Prefix>ct-roles</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-SchA/2006-07-03</Namespace>
<Prefix>ct-SchA</Prefix>
</Loc>
<Loc><Family>BASE</Family>
<Version>2006</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.govtalk.gov.uk/uk/fr/tax/uk-hmrc-ct-Tax/2006-07-03</Namespace>
<Prefix>ct-Tax</Prefix>
</Loc>
<Loc><Family>UKGAAP</Family>
<Version>2005</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.companieshouse.gov.uk/ef/xbrl/gaap/ae/2005-06-01
</Namespace>
<Prefix>uk-gaap-ae</Prefix>
</Loc>
<Loc><Family>UKGAAP</Family>
<Version>2004</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.xbrl.org/uk/fr/gaap/ci/2004-12-01</Namespace>
<Prefix>uk-gaap-ci</Prefix>
</Loc>
<Loc><Family>UKGAAP</Family>
<Version>2004</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.xbrl.org/uk/fr/gcd/2004-12-01</Namespace>
<Prefix>uk-gcd</Prefix>
</Loc>
<Loc><Family>UKGAAP</Family>
<Version>2004</Version>
<AttType>SCH</AttType>
<FileTypeName>Schema</FileTypeName>
<Elements>1</Elements>
<Namespace>http://www.xbrl.org/uk/fr/gaap/pt/2004-12-01</Namespace>
<Prefix>uk-gaap-pt</Prefix>
</Loc>
</Erxl>
| {'content_hash': '46106c7d48c31a1cf09d4cf5d82e9296', 'timestamp': '', 'source': 'github', 'line_count': 317, 'max_line_length': 104, 'avg_line_length': 30.305993690851736, 'alnum_prop': 0.7412303528677007, 'repo_name': 'sternshus/Arelle', 'id': 'e2659b6363f4c028c4d925036c7decb83d39d1aa', 'size': '9607', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'arelle/config/hmrc-taxonomies.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '31873'}, {'name': 'C#', 'bytes': '850'}, {'name': 'HTML', 'bytes': '8640'}, {'name': 'Java', 'bytes': '4663'}, {'name': 'Makefile', 'bytes': '5565'}, {'name': 'NSIS', 'bytes': '9050'}, {'name': 'PLSQL', 'bytes': '1056360'}, {'name': 'Python', 'bytes': '5523072'}, {'name': 'Shell', 'bytes': '13921'}]} |
package imageprune
import (
"bytes"
"errors"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"regexp"
"sort"
"sync"
"testing"
"time"
"github.com/golang/glog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/diff"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/rest/fake"
clientgotesting "k8s.io/client-go/testing"
kapi "k8s.io/kubernetes/pkg/apis/core"
kapisext "k8s.io/kubernetes/pkg/apis/extensions"
appsapi "github.com/openshift/origin/pkg/apps/apis/apps"
buildapi "github.com/openshift/origin/pkg/build/apis/build"
imageapi "github.com/openshift/origin/pkg/image/apis/image"
fakeimageclient "github.com/openshift/origin/pkg/image/generated/internalclientset/fake"
imageclient "github.com/openshift/origin/pkg/image/generated/internalclientset/typed/image/internalversion"
"github.com/openshift/origin/pkg/oc/admin/prune/imageprune/testutil"
"github.com/openshift/origin/pkg/oc/graph/genericgraph"
imagegraph "github.com/openshift/origin/pkg/oc/graph/imagegraph/nodes"
// these are needed to make kapiref.GetReference work in the prune.go file
_ "github.com/openshift/origin/pkg/apps/apis/apps/install"
_ "github.com/openshift/origin/pkg/build/apis/build/install"
_ "github.com/openshift/origin/pkg/image/apis/image/install"
_ "k8s.io/kubernetes/pkg/apis/core/install"
_ "k8s.io/kubernetes/pkg/apis/extensions/install"
)
var logLevel = flag.Int("loglevel", 0, "")
func TestImagePruning(t *testing.T) {
flag.Lookup("v").Value.Set(fmt.Sprint(*logLevel))
registryHost := "registry.io"
registryURL := "https://" + registryHost
tests := []struct {
name string
pruneOverSizeLimit *bool
allImages *bool
pruneRegistry *bool
ignoreInvalidRefs *bool
keepTagRevisions *int
namespace string
images imageapi.ImageList
pods kapi.PodList
streams imageapi.ImageStreamList
rcs kapi.ReplicationControllerList
bcs buildapi.BuildConfigList
builds buildapi.BuildList
dss kapisext.DaemonSetList
deployments kapisext.DeploymentList
dcs appsapi.DeploymentConfigList
rss kapisext.ReplicaSetList
limits map[string][]*kapi.LimitRange
imageDeleterErr error
imageStreamDeleterErr error
layerDeleterErr error
manifestDeleterErr error
blobDeleterErrorGetter errorForSHA
expectedImageDeletions []string
expectedStreamUpdates []string
expectedLayerLinkDeletions []string
expectedManifestLinkDeletions []string
expectedBlobDeletions []string
expectedFailures []string
expectedErrorString string
}{
{
name: "1 pod - phase pending - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(testutil.Pod("foo", "pod1", kapi.PodPending, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "3 pods - last phase pending - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(
testutil.Pod("foo", "pod1", kapi.PodSucceeded, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Pod("foo", "pod2", kapi.PodSucceeded, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Pod("foo", "pod3", kapi.PodPending, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
),
expectedImageDeletions: []string{},
},
{
name: "1 pod - phase running - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(testutil.Pod("foo", "pod1", kapi.PodRunning, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "3 pods - last phase running - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(
testutil.Pod("foo", "pod1", kapi.PodSucceeded, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Pod("foo", "pod2", kapi.PodSucceeded, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Pod("foo", "pod3", kapi.PodRunning, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
),
expectedImageDeletions: []string{},
},
{
name: "pod phase succeeded - prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(testutil.Pod("foo", "pod1", kapi.PodSucceeded, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000",
registryURL + "|" + testutil.Layer1,
registryURL + "|" + testutil.Layer2,
registryURL + "|" + testutil.Layer3,
registryURL + "|" + testutil.Layer4,
registryURL + "|" + testutil.Layer5,
},
},
{
name: "pod phase succeeded - prune leave registry alone",
pruneRegistry: newBool(false),
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(testutil.Pod("foo", "pod1", kapi.PodSucceeded, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedBlobDeletions: []string{},
},
{
name: "pod phase succeeded, pod less than min pruning age - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(testutil.AgedPod("foo", "pod1", kapi.PodSucceeded, 5, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "pod phase succeeded, image less than min pruning age - don't prune",
images: testutil.ImageList(testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", 5)),
pods: testutil.PodList(testutil.Pod("foo", "pod1", kapi.PodSucceeded, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "pod phase failed - prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(
testutil.Pod("foo", "pod1", kapi.PodFailed, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Pod("foo", "pod2", kapi.PodFailed, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Pod("foo", "pod3", kapi.PodFailed, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000",
registryURL + "|" + testutil.Layer1,
registryURL + "|" + testutil.Layer2,
registryURL + "|" + testutil.Layer3,
registryURL + "|" + testutil.Layer4,
registryURL + "|" + testutil.Layer5,
},
},
{
name: "pod phase unknown - prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(
testutil.Pod("foo", "pod1", kapi.PodUnknown, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Pod("foo", "pod2", kapi.PodUnknown, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Pod("foo", "pod3", kapi.PodUnknown, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000",
registryURL + "|" + testutil.Layer1,
registryURL + "|" + testutil.Layer2,
registryURL + "|" + testutil.Layer3,
registryURL + "|" + testutil.Layer4,
registryURL + "|" + testutil.Layer5,
},
},
{
name: "pod container image not parsable",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(
testutil.Pod("foo", "pod1", kapi.PodRunning, "a/b/c/d/e"),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000",
registryURL + "|" + testutil.Layer1,
registryURL + "|" + testutil.Layer2,
registryURL + "|" + testutil.Layer3,
registryURL + "|" + testutil.Layer4,
registryURL + "|" + testutil.Layer5,
},
},
{
name: "pod container image doesn't have an id",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(
testutil.Pod("foo", "pod1", kapi.PodRunning, "foo/bar:latest"),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000",
registryURL + "|" + testutil.Layer1,
registryURL + "|" + testutil.Layer2,
registryURL + "|" + testutil.Layer3,
registryURL + "|" + testutil.Layer4,
registryURL + "|" + testutil.Layer5,
},
},
{
name: "pod refers to image not in graph",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
pods: testutil.PodList(
testutil.Pod("foo", "pod1", kapi.PodRunning, registryHost+"/foo/bar@sha256:ABC0000000000000000000000000000000000000000000000000000000000002"),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000",
registryURL + "|" + testutil.Layer1,
registryURL + "|" + testutil.Layer2,
registryURL + "|" + testutil.Layer3,
registryURL + "|" + testutil.Layer4,
registryURL + "|" + testutil.Layer5,
},
},
{
name: "referenced by rc - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
rcs: testutil.RCList(testutil.RC("foo", "rc1", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by dc - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
dcs: testutil.DCList(testutil.DC("foo", "rc1", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by daemonset - don't prune",
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
dss: testutil.DSList(testutil.DS("foo", "rc1", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000001"},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000001"},
},
{
name: "referenced by replicaset - don't prune",
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
rss: testutil.RSList(testutil.RS("foo", "rc1", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000001"},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000001"},
},
{
name: "referenced by upstream deployment - don't prune",
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
deployments: testutil.DeploymentList(testutil.Deployment("foo", "rc1", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000001"},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000001"},
},
{
name: "referenced by bc - sti - ImageStreamImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
bcs: testutil.BCList(testutil.BC("foo", "bc1", "source", "ImageStreamImage", "foo", "bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by bc - docker - ImageStreamImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
bcs: testutil.BCList(testutil.BC("foo", "bc1", "docker", "ImageStreamImage", "foo", "bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by bc - custom - ImageStreamImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
bcs: testutil.BCList(testutil.BC("foo", "bc1", "custom", "ImageStreamImage", "foo", "bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by bc - sti - DockerImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
bcs: testutil.BCList(testutil.BC("foo", "bc1", "source", "DockerImage", "foo", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by bc - docker - DockerImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
bcs: testutil.BCList(testutil.BC("foo", "bc1", "docker", "DockerImage", "foo", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by bc - custom - DockerImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
bcs: testutil.BCList(testutil.BC("foo", "bc1", "custom", "DockerImage", "foo", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by build - sti - ImageStreamImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
builds: testutil.BuildList(testutil.Build("foo", "build1", "source", "ImageStreamImage", "foo", "bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by build - docker - ImageStreamImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
builds: testutil.BuildList(testutil.Build("foo", "build1", "docker", "ImageStreamImage", "foo", "bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by build - custom - ImageStreamImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
builds: testutil.BuildList(testutil.Build("foo", "build1", "custom", "ImageStreamImage", "foo", "bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by build - sti - DockerImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
builds: testutil.BuildList(testutil.Build("foo", "build1", "source", "DockerImage", "foo", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by build - docker - DockerImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
builds: testutil.BuildList(testutil.Build("foo", "build1", "docker", "DockerImage", "foo", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "referenced by build - custom - DockerImage - don't prune",
images: testutil.ImageList(testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
builds: testutil.BuildList(testutil.Build("foo", "build1", "custom", "DockerImage", "foo", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
},
{
name: "image stream - keep most recent n images",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedBlobDeletions: []string{registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000004"},
},
{
name: "continue on blob deletion failure",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004", nil, "layer1", "layer2"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
blobDeleterErrorGetter: func(dgst string) error {
if dgst == "layer1" {
return errors.New("err")
}
return nil
},
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedLayerLinkDeletions: []string{registryURL + "|foo/bar|layer1", registryURL + "|foo/bar|layer2"},
expectedBlobDeletions: []string{
registryURL + "|" + "layer1",
registryURL + "|" + "layer2",
registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000004",
},
expectedFailures: []string{registryURL + "|" + "layer1|err"},
},
{
name: "keep image when all blob deletions fail",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004", nil, "layer1", "layer2"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
blobDeleterErrorGetter: func(dgst string) error { return errors.New("err") },
expectedImageDeletions: []string{},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedLayerLinkDeletions: []string{registryURL + "|foo/bar|layer1", registryURL + "|foo/bar|layer2"},
expectedBlobDeletions: []string{registryURL + "|layer1", registryURL + "|layer2", registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedFailures: []string{registryURL + "|" + "layer1|err", registryURL + "|" + "layer2|err", registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000004|err"},
},
{
name: "continue on manifest link deletion failure",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
manifestDeleterErr: fmt.Errorf("err"),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedBlobDeletions: []string{registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedFailures: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004|err"},
},
{
name: "stop on image stream update failure",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
imageStreamDeleterErr: fmt.Errorf("err"),
expectedFailures: []string{"foo/bar|err"},
},
{
name: "image stream - same manifest listed multiple times in tag history",
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
)),
),
},
{
name: "image stream age less than min pruning age - don't prune",
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
streams: testutil.StreamList(
testutil.AgedStream(registryHost, "foo", "bar", 5, testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
expectedImageDeletions: []string{},
expectedStreamUpdates: []string{},
},
{
name: "image stream - unreference absent image",
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
)),
),
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000000"},
},
{
name: "image stream with dangling references - delete tags",
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", nil, "layer1"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
),
testutil.Tag("tag",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
)),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000001"},
expectedStreamUpdates: []string{
"foo/bar:latest",
"foo/bar:tag",
"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000000",
"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000002",
},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000001", registryURL + "|layer1"},
},
{
name: "image stream - keep reference to a young absent image",
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", nil),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.YoungTagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", metav1.Now()),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
)),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000002"},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000002"},
},
{
name: "images referenced by istag - keep",
keepTagRevisions: keepTagRevisions(0),
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000005", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000005"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000006", registryHost+"/foo/baz@sha256:0000000000000000000000000000000000000000000000000000000000000006"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000005", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000005"),
),
testutil.Tag("dummy", // removed because no object references the image (the nm/dcfoo has mismatched repository name)
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000005", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000005"),
),
)),
testutil.Stream(registryHost, "foo", "baz", testutil.Tags(
testutil.Tag("late", // kept because replicaset references the tagged image
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
testutil.Tag("keepme", // kept because a deployment references the tagged image
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000006", registryHost+"/foo/baz@sha256:0000000000000000000000000000000000000000000000000000000000000006"),
),
)),
),
dss: testutil.DSList(testutil.DS("nm", "dsfoo", fmt.Sprintf("%s/%s/%s:%s", registryHost, "foo", "bar", "latest"))),
dcs: testutil.DCList(testutil.DC("nm", "dcfoo", fmt.Sprintf("%s/%s/%s:%s", registryHost, "foo", "repo", "dummy"))),
rss: testutil.RSList(testutil.RS("nm", "rsfoo", fmt.Sprintf("%s/%s/%s:%s", registryHost, "foo", "baz", "late"))),
// ignore different registry hostname
deployments: testutil.DeploymentList(testutil.Deployment("nm", "depfoo", fmt.Sprintf("%s/%s/%s:%s", "external.registry:5000", "foo", "baz", "keepme"))),
expectedImageDeletions: []string{
"sha256:0000000000000000000000000000000000000000000000000000000000000001",
"sha256:0000000000000000000000000000000000000000000000000000000000000003",
"sha256:0000000000000000000000000000000000000000000000000000000000000004",
"sha256:0000000000000000000000000000000000000000000000000000000000000005",
},
expectedStreamUpdates: []string{
"foo/bar:dummy",
"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000000",
"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000001",
"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000003",
"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004",
"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000005",
},
expectedManifestLinkDeletions: []string{
registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000001",
registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000003",
registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004",
registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000005",
},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000001",
registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000003",
registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000004",
registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000005",
},
},
{
name: "multiple resources pointing to image - don't prune",
images: testutil.ImageList(
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.Image("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
)),
),
rcs: testutil.RCList(testutil.RC("foo", "rc1", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002")),
pods: testutil.PodList(testutil.Pod("foo", "pod1", kapi.PodRunning, registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002")),
dcs: testutil.DCList(testutil.DC("foo", "rc1", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
bcs: testutil.BCList(testutil.BC("foo", "bc1", "source", "DockerImage", "foo", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
builds: testutil.BuildList(testutil.Build("foo", "build1", "custom", "ImageStreamImage", "foo", "bar@sha256:0000000000000000000000000000000000000000000000000000000000000000")),
expectedImageDeletions: []string{},
expectedStreamUpdates: []string{},
},
{
name: "image with nil annotations",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedStreamUpdates: []string{},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000"},
},
{
name: "prune all-images=true image with nil annotations",
allImages: newBool(true),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedStreamUpdates: []string{},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000"},
},
{
name: "prune all-images=false image with nil annotations",
allImages: newBool(false),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
),
expectedImageDeletions: []string{},
expectedStreamUpdates: []string{},
},
{
name: "image missing managed annotation",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, "foo", "bar"),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedStreamUpdates: []string{},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000"},
},
{
name: "image with managed annotation != true",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "false"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000001", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "0"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "1"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "True"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000004", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "yes"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000005", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "Yes"),
),
expectedImageDeletions: []string{
"sha256:0000000000000000000000000000000000000000000000000000000000000000",
"sha256:0000000000000000000000000000000000000000000000000000000000000001",
"sha256:0000000000000000000000000000000000000000000000000000000000000002",
"sha256:0000000000000000000000000000000000000000000000000000000000000003",
"sha256:0000000000000000000000000000000000000000000000000000000000000004",
"sha256:0000000000000000000000000000000000000000000000000000000000000005",
},
expectedStreamUpdates: []string{},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000001",
registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000002",
registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000003",
registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000004",
registryURL + "|" + "sha256:0000000000000000000000000000000000000000000000000000000000000005",
},
},
{
name: "prune all-images=true with image missing managed annotation",
allImages: newBool(true),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, "foo", "bar"),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000000"},
expectedStreamUpdates: []string{},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000"},
},
{
name: "prune all-images=true with image with managed annotation != true",
allImages: newBool(true),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "false"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000001", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "0"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "1"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "True"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000004", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "yes"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000005", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "Yes"),
),
expectedImageDeletions: []string{
"sha256:0000000000000000000000000000000000000000000000000000000000000000",
"sha256:0000000000000000000000000000000000000000000000000000000000000001",
"sha256:0000000000000000000000000000000000000000000000000000000000000002",
"sha256:0000000000000000000000000000000000000000000000000000000000000003",
"sha256:0000000000000000000000000000000000000000000000000000000000000004",
"sha256:0000000000000000000000000000000000000000000000000000000000000005",
},
expectedStreamUpdates: []string{},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000000",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000001",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000002",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000003",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000004",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000005",
},
},
{
name: "prune all-images=false with image missing managed annotation",
allImages: newBool(false),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, "foo", "bar"),
),
expectedImageDeletions: []string{},
expectedStreamUpdates: []string{},
},
{
name: "prune all-images=false with image with managed annotation != true",
allImages: newBool(false),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "false"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000001", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "0"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "1"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "True"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000004", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "yes"),
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000005", "someregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", true, imageapi.ManagedByOpenShiftAnnotation, "Yes"),
),
expectedImageDeletions: []string{},
expectedStreamUpdates: []string{},
},
{
name: "image with layers",
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", &testutil.Config2, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", nil, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004", nil, "layer5", "layer6", "layer7", "layer8"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedLayerLinkDeletions: []string{
registryURL + "|foo/bar|layer5",
registryURL + "|foo/bar|layer6",
registryURL + "|foo/bar|layer7",
registryURL + "|foo/bar|layer8",
},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000004",
registryURL + "|layer5",
registryURL + "|layer6",
registryURL + "|layer7",
registryURL + "|layer8",
},
},
{
name: "continue on layer link error",
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", &testutil.Config2, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", nil, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004", nil, "layer5", "layer6", "layer7", "layer8"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
layerDeleterErr: fmt.Errorf("err"),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000004",
registryURL + "|layer5",
registryURL + "|layer6",
registryURL + "|layer7",
registryURL + "|layer8",
},
expectedLayerLinkDeletions: []string{
registryURL + "|foo/bar|layer5",
registryURL + "|foo/bar|layer6",
registryURL + "|foo/bar|layer7",
registryURL + "|foo/bar|layer8",
},
expectedFailures: []string{
registryURL + "|foo/bar|layer5|err",
registryURL + "|foo/bar|layer6|err",
registryURL + "|foo/bar|layer7|err",
registryURL + "|foo/bar|layer8|err",
},
},
{
name: "images with duplicate layers and configs",
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004", &testutil.Config2, "layer5", "layer6", "layer7", "layer8"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000005", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000005", &testutil.Config2, "layer5", "layer6", "layer9", "layerX"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000004", "sha256:0000000000000000000000000000000000000000000000000000000000000005"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedLayerLinkDeletions: []string{
registryURL + "|foo/bar|" + testutil.Config2,
registryURL + "|foo/bar|layer5",
registryURL + "|foo/bar|layer6",
registryURL + "|foo/bar|layer7",
registryURL + "|foo/bar|layer8",
},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000004",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000005",
registryURL + "|" + testutil.Config2,
registryURL + "|layer5",
registryURL + "|layer6",
registryURL + "|layer7",
registryURL + "|layer8",
registryURL + "|layer9",
registryURL + "|layerX",
},
},
{
name: "continue on image deletion failure",
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004", &testutil.Config2, "layer5", "layer6", "layer7", "layer8"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000005", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000005", &testutil.Config2, "layer5", "layer6", "layer9", "layerX"),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
imageDeleterErr: fmt.Errorf("err"),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000004", "sha256:0000000000000000000000000000000000000000000000000000000000000005"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedLayerLinkDeletions: []string{
registryURL + "|foo/bar|" + testutil.Config2,
registryURL + "|foo/bar|layer5",
registryURL + "|foo/bar|layer6",
registryURL + "|foo/bar|layer7",
registryURL + "|foo/bar|layer8",
},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000004",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000005",
registryURL + "|layer7",
registryURL + "|layer8",
registryURL + "|layer9",
registryURL + "|layerX",
},
expectedFailures: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000004|err", "sha256:0000000000000000000000000000000000000000000000000000000000000005|err"},
},
{
name: "layers shared with young images are not pruned",
images: testutil.ImageList(
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", 43200),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 5),
),
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000001"},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000001"},
},
{
name: "image exceeding limits",
pruneOverSizeLimit: newBool(true),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 100, nil),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 200, nil),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
),
)),
),
limits: map[string][]*kapi.LimitRange{
"foo": testutil.LimitList(100, 200),
},
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000003"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000003"},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000003"},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000003"},
},
{
name: "multiple images in different namespaces exceeding different limits",
pruneOverSizeLimit: newBool(true),
images: testutil.ImageList(
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", 100, nil),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 200, nil),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/bar/foo@sha256:0000000000000000000000000000000000000000000000000000000000000003", 500, nil),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/bar/foo@sha256:0000000000000000000000000000000000000000000000000000000000000004", 600, nil),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
)),
testutil.Stream(registryHost, "bar", "foo", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/bar/foo@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", registryHost+"/bar/foo@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
),
)),
),
limits: map[string][]*kapi.LimitRange{
"foo": testutil.LimitList(150),
"bar": testutil.LimitList(550),
},
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000002", "sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000002", "bar/foo|sha256:0000000000000000000000000000000000000000000000000000000000000004"},
expectedManifestLinkDeletions: []string{
registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000002",
registryURL + "|bar/foo|sha256:0000000000000000000000000000000000000000000000000000000000000004",
},
expectedBlobDeletions: []string{
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000002",
registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000004",
},
},
{
name: "image within allowed limits",
pruneOverSizeLimit: newBool(true),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 100, nil),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 200, nil),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
),
)),
),
limits: map[string][]*kapi.LimitRange{
"foo": testutil.LimitList(300),
},
expectedImageDeletions: []string{},
expectedStreamUpdates: []string{},
},
{
name: "image exceeding limits with namespace specified",
pruneOverSizeLimit: newBool(true),
namespace: "foo",
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 100, nil),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 200, nil),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
),
)),
),
limits: map[string][]*kapi.LimitRange{
"foo": testutil.LimitList(100, 200),
},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000003"},
},
{
name: "build with ignored bad image reference",
pruneOverSizeLimit: newBool(true),
ignoreInvalidRefs: newBool(true),
images: testutil.ImageList(
testutil.UnmanagedImage("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000", false, "", ""),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 100, nil),
testutil.SizedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 200, nil),
),
streams: testutil.StreamList(
testutil.Stream(registryHost, "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "otherregistry/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", registryHost+"/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
),
)),
),
builds: testutil.BuildList(
testutil.Build("foo", "build1", "source", "DockerImage", "foo", registryHost+"/foo/bar@sha256:many-zeros-and-3"),
),
limits: map[string][]*kapi.LimitRange{
"foo": testutil.LimitList(100, 200),
},
expectedImageDeletions: []string{"sha256:0000000000000000000000000000000000000000000000000000000000000003"},
expectedManifestLinkDeletions: []string{registryURL + "|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000003"},
expectedBlobDeletions: []string{registryURL + "|sha256:0000000000000000000000000000000000000000000000000000000000000003"},
expectedStreamUpdates: []string{"foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000003"},
},
{
name: "build with bad image reference",
builds: testutil.BuildList(testutil.Build("foo", "build1", "source", "DockerImage", "foo", registryHost+"/foo/bar@invalid-digest")),
expectedErrorString: fmt.Sprintf(`Build[foo/build1]: invalid docker image reference "%s/foo/bar@invalid-digest": invalid reference format`, registryHost),
},
{
name: "buildconfig with bad imagestreamtag",
bcs: testutil.BCList(testutil.BC("foo", "bc1", "source", "ImageStreamTag", "ns", "bad/tag@name")),
expectedErrorString: `BuildConfig[foo/bc1]: invalid ImageStreamTag reference "bad/tag@name":` +
` "bad/tag@name" is an image stream image, not an image stream tag`,
},
{
name: "more parsing errors",
bcs: testutil.BCList(testutil.BC("foo", "bc1", "source", "ImageStreamImage", "ns", "bad:isi")),
deployments: testutil.DeploymentList(testutil.Deployment("nm", "dep1", "garbage")),
rss: testutil.RSList(testutil.RS("nm", "rs1", "I am certainly a valid reference")),
expectedErrorString: `[BuildConfig[foo/bc1]: invalid ImageStreamImage reference "bad:isi":` +
` expected exactly one @ in the isimage name "bad:isi",` +
` ReplicaSet[nm/rs1]: invalid docker image reference "I am certainly a valid reference":` +
` invalid reference format]`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
options := PrunerOptions{
Namespace: test.namespace,
AllImages: test.allImages,
Images: &test.images,
ImageWatcher: watch.NewFake(),
Streams: &test.streams,
StreamWatcher: watch.NewFake(),
Pods: &test.pods,
RCs: &test.rcs,
BCs: &test.bcs,
Builds: &test.builds,
DSs: &test.dss,
Deployments: &test.deployments,
DCs: &test.dcs,
RSs: &test.rss,
LimitRanges: test.limits,
RegistryClientFactory: FakeRegistryClientFactory,
RegistryURL: &url.URL{Scheme: "https", Host: registryHost},
}
if test.pruneOverSizeLimit != nil {
options.PruneOverSizeLimit = test.pruneOverSizeLimit
} else {
youngerThan := time.Hour
tagRevisions := 3
if test.keepTagRevisions != nil {
tagRevisions = *test.keepTagRevisions
}
options.KeepYoungerThan = &youngerThan
options.KeepTagRevisions = &tagRevisions
}
if test.pruneRegistry != nil {
options.PruneRegistry = test.pruneRegistry
}
if test.ignoreInvalidRefs != nil {
options.IgnoreInvalidRefs = *test.ignoreInvalidRefs
}
p, err := NewPruner(options)
if err != nil {
if len(test.expectedErrorString) > 0 {
if a, e := err.Error(), test.expectedErrorString; a != e {
t.Fatalf("got unexpected error: %q != %q", a, e)
}
} else {
t.Fatalf("got unexpected error: %v", err)
}
return
} else if len(test.expectedErrorString) > 0 {
t.Fatalf("got no error while expecting: %s", test.expectedErrorString)
return
}
imageDeleter, imageDeleterFactory := newFakeImageDeleter(test.imageDeleterErr)
streamDeleter := &fakeImageStreamDeleter{err: test.imageStreamDeleterErr, invocations: sets.NewString()}
layerLinkDeleter := &fakeLayerLinkDeleter{err: test.layerDeleterErr, invocations: sets.NewString()}
blobDeleter := &fakeBlobDeleter{getError: test.blobDeleterErrorGetter, invocations: sets.NewString()}
manifestDeleter := &fakeManifestDeleter{err: test.manifestDeleterErr, invocations: sets.NewString()}
deletions, failures := p.Prune(imageDeleterFactory, streamDeleter, layerLinkDeleter, blobDeleter, manifestDeleter)
expectedFailures := sets.NewString(test.expectedFailures...)
renderedFailures := sets.NewString()
for _, f := range failures {
rendered := renderFailure(registryURL, &f)
if renderedFailures.Has(rendered) {
t.Errorf("got the following failure more than once: %v", rendered)
continue
}
renderedFailures.Insert(rendered)
}
for f := range renderedFailures {
if expectedFailures.Has(f) {
expectedFailures.Delete(f)
continue
}
t.Errorf("got unexpected failure: %v", f)
}
for f := range expectedFailures {
t.Errorf("the following expected failure was not returned: %v", f)
}
expectedImageDeletions := sets.NewString(test.expectedImageDeletions...)
if a, e := imageDeleter.invocations, expectedImageDeletions; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected image deletions: %s", diff.ObjectDiff(a, e))
}
expectedStreamUpdates := sets.NewString(test.expectedStreamUpdates...)
if a, e := streamDeleter.invocations, expectedStreamUpdates; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected stream updates: %s", diff.ObjectDiff(a, e))
}
expectedLayerLinkDeletions := sets.NewString(test.expectedLayerLinkDeletions...)
if a, e := layerLinkDeleter.invocations, expectedLayerLinkDeletions; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected layer link deletions: %s", diff.ObjectDiff(a, e))
}
expectedManifestLinkDeletions := sets.NewString(test.expectedManifestLinkDeletions...)
if a, e := manifestDeleter.invocations, expectedManifestLinkDeletions; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected manifest link deletions: %s", diff.ObjectDiff(a, e))
}
expectedBlobDeletions := sets.NewString(test.expectedBlobDeletions...)
if a, e := blobDeleter.invocations, expectedBlobDeletions; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected blob deletions: %s", diff.ObjectDiff(a, e))
}
// TODO: shall we return deletion for each layer link unlinked from the image stream??
imageStreamUpdates := sets.NewString()
expectedAllDeletions := sets.NewString()
for _, s := range []sets.String{expectedImageDeletions, expectedLayerLinkDeletions, expectedBlobDeletions} {
expectedAllDeletions.Insert(s.List()...)
}
for _, d := range deletions {
rendered, isImageStreamUpdate, isManifestLinkDeletion := renderDeletion(registryURL, &d)
if isManifestLinkDeletion {
continue
}
if isImageStreamUpdate {
imageStreamUpdates.Insert(rendered)
continue
}
if expectedAllDeletions.Has(rendered) {
expectedAllDeletions.Delete(rendered)
} else {
t.Errorf("got unexpected deletion: %#+v (rendered: %q)", d, rendered)
}
}
for _, f := range failures {
rendered, _, _ := renderDeletion(registryURL, &Deletion{Node: f.Node, Parent: f.Parent})
expectedAllDeletions.Delete(rendered)
}
for del, ok := expectedAllDeletions.PopAny(); ok; del, ok = expectedAllDeletions.PopAny() {
t.Errorf("expected deletion %q did not happen", del)
}
expectedStreamUpdateNames := sets.NewString()
for u := range expectedStreamUpdates {
expectedStreamUpdateNames.Insert(regexp.MustCompile(`[@|:]`).Split(u, 2)[0])
}
if a, e := imageStreamUpdates, expectedStreamUpdateNames; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected image stream updates in deletions: %s", diff.ObjectDiff(a, e))
}
})
}
}
func renderDeletion(registryURL string, deletion *Deletion) (rendered string, isImageStreamUpdate, isManifestLinkDeletion bool) {
switch t := deletion.Node.(type) {
case *imagegraph.ImageNode:
return t.Image.Name, false, false
case *imagegraph.ImageComponentNode:
// deleting blob
if deletion.Parent == nil {
return fmt.Sprintf("%s|%s", registryURL, t.Component), false, false
}
streamName := "unknown"
if sn, ok := deletion.Parent.(*imagegraph.ImageStreamNode); ok {
streamName = getName(sn.ImageStream)
}
return fmt.Sprintf("%s|%s|%s", registryURL, streamName, t.Component), false, t.Type == imagegraph.ImageComponentTypeManifest
case *imagegraph.ImageStreamNode:
return getName(t.ImageStream), true, false
}
return "unknown", false, false
}
func renderFailure(registryURL string, failure *Failure) string {
rendered, _, _ := renderDeletion(registryURL, &Deletion{Node: failure.Node, Parent: failure.Parent})
return rendered + "|" + failure.Err.Error()
}
func TestImageDeleter(t *testing.T) {
flag.Lookup("v").Value.Set(fmt.Sprint(*logLevel))
tests := map[string]struct {
imageDeletionError error
}{
"no error": {},
"delete error": {
imageDeletionError: fmt.Errorf("foo"),
},
}
for name, test := range tests {
imageClient := fakeimageclient.Clientset{}
imageClient.AddReactor("delete", "images", func(action clientgotesting.Action) (handled bool, ret runtime.Object, err error) {
return true, nil, test.imageDeletionError
})
imageDeleter := NewImageDeleter(imageClient.Image())
err := imageDeleter.DeleteImage(&imageapi.Image{ObjectMeta: metav1.ObjectMeta{Name: "sha256:0000000000000000000000000000000000000000000000000000000000000002"}})
if test.imageDeletionError != nil {
if e, a := test.imageDeletionError, err; e != a {
t.Errorf("%s: err: expected %v, got %v", name, e, a)
}
continue
}
if e, a := 1, len(imageClient.Actions()); e != a {
t.Errorf("%s: expected %d actions, got %d: %#v", name, e, a, imageClient.Actions())
continue
}
if !imageClient.Actions()[0].Matches("delete", "images") {
t.Errorf("%s: expected action %s, got %v", name, "delete-images", imageClient.Actions()[0])
}
}
}
func TestLayerDeleter(t *testing.T) {
flag.Lookup("v").Value.Set(fmt.Sprint(*logLevel))
var actions []string
client := fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
actions = append(actions, req.Method+":"+req.URL.String())
return &http.Response{StatusCode: http.StatusServiceUnavailable, Body: ioutil.NopCloser(bytes.NewReader([]byte{}))}, nil
})
layerLinkDeleter := NewLayerLinkDeleter()
layerLinkDeleter.DeleteLayerLink(client, &url.URL{Scheme: "http", Host: "registry1"}, "repo", "layer1")
if e := []string{"DELETE:http://registry1/v2/repo/blobs/layer1"}; !reflect.DeepEqual(actions, e) {
t.Errorf("unexpected actions: %s", diff.ObjectDiff(actions, e))
}
}
func TestNotFoundLayerDeleter(t *testing.T) {
flag.Lookup("v").Value.Set(fmt.Sprint(*logLevel))
var actions []string
client := fake.CreateHTTPClient(func(req *http.Request) (*http.Response, error) {
actions = append(actions, req.Method+":"+req.URL.String())
return &http.Response{StatusCode: http.StatusNotFound, Body: ioutil.NopCloser(bytes.NewReader([]byte{}))}, nil
})
layerLinkDeleter := NewLayerLinkDeleter()
layerLinkDeleter.DeleteLayerLink(client, &url.URL{Scheme: "https", Host: "registry1"}, "repo", "layer1")
if e := []string{"DELETE:https://registry1/v2/repo/blobs/layer1"}; !reflect.DeepEqual(actions, e) {
t.Errorf("unexpected actions: %s", diff.ObjectDiff(actions, e))
}
}
func TestRegistryPruning(t *testing.T) {
flag.Lookup("v").Value.Set(fmt.Sprint(*logLevel))
tests := []struct {
name string
images imageapi.ImageList
streams imageapi.ImageStreamList
expectedLayerLinkDeletions sets.String
expectedBlobDeletions sets.String
expectedManifestDeletions sets.String
pruneRegistry bool
pingErr error
}{
{
name: "layers unique to id1 pruned",
pruneRegistry: true,
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", &testutil.Config2, "layer3", "layer4", "layer5", "layer6"),
),
streams: testutil.StreamList(
testutil.Stream("registry1.io", "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
)),
testutil.Stream("registry1.io", "foo", "other", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/other@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
)),
),
expectedLayerLinkDeletions: sets.NewString(
"https://registry1.io|foo/bar|"+testutil.Config1,
"https://registry1.io|foo/bar|layer1",
"https://registry1.io|foo/bar|layer2",
),
expectedBlobDeletions: sets.NewString(
"https://registry1.io|sha256:0000000000000000000000000000000000000000000000000000000000000001",
"https://registry1.io|"+testutil.Config1,
"https://registry1.io|layer1",
"https://registry1.io|layer2",
),
expectedManifestDeletions: sets.NewString(
"https://registry1.io|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000001",
),
},
{
name: "no pruning when no images are pruned",
pruneRegistry: true,
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
),
streams: testutil.StreamList(
testutil.Stream("registry1.io", "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
)),
),
expectedLayerLinkDeletions: sets.NewString(),
expectedBlobDeletions: sets.NewString(),
expectedManifestDeletions: sets.NewString(),
},
{
name: "blobs pruned when streams have already been deleted",
pruneRegistry: true,
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", "layer4"),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", &testutil.Config2, "layer3", "layer4", "layer5", "layer6"),
),
expectedLayerLinkDeletions: sets.NewString(),
expectedBlobDeletions: sets.NewString(
"https://registry1.io|sha256:0000000000000000000000000000000000000000000000000000000000000001",
"https://registry1.io|sha256:0000000000000000000000000000000000000000000000000000000000000002",
"https://registry1.io|"+testutil.Config1,
"https://registry1.io|"+testutil.Config2,
"https://registry1.io|layer1",
"https://registry1.io|layer2",
"https://registry1.io|layer3",
"https://registry1.io|layer4",
"https://registry1.io|layer5",
"https://registry1.io|layer6",
),
expectedManifestDeletions: sets.NewString(),
},
{
name: "config used as a layer",
pruneRegistry: true,
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", testutil.Config1),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", &testutil.Config2, "layer3", "layer4", "layer5", testutil.Config1),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000003", "registry1.io/foo/other@sha256:0000000000000000000000000000000000000000000000000000000000000003", nil, "layer3", "layer4", "layer6", testutil.Config1),
),
streams: testutil.StreamList(
testutil.Stream("registry1.io", "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
)),
testutil.Stream("registry1.io", "foo", "other", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", "registry1.io/foo/other@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
)),
),
expectedLayerLinkDeletions: sets.NewString(
"https://registry1.io|foo/bar|layer1",
"https://registry1.io|foo/bar|layer2",
),
expectedBlobDeletions: sets.NewString(
"https://registry1.io|sha256:0000000000000000000000000000000000000000000000000000000000000001",
"https://registry1.io|layer1",
"https://registry1.io|layer2",
),
expectedManifestDeletions: sets.NewString(
"https://registry1.io|foo/bar|sha256:0000000000000000000000000000000000000000000000000000000000000001",
),
},
{
name: "config used as a layer, but leave registry alone",
pruneRegistry: false,
images: testutil.ImageList(
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", &testutil.Config1, "layer1", "layer2", "layer3", testutil.Config1),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", &testutil.Config2, "layer3", "layer4", "layer5", testutil.Config1),
testutil.ImageWithLayers("sha256:0000000000000000000000000000000000000000000000000000000000000003", "registry1.io/foo/other@sha256:0000000000000000000000000000000000000000000000000000000000000003", nil, "layer3", "layer4", "layer6", testutil.Config1),
),
streams: testutil.StreamList(
testutil.Stream("registry1.io", "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
)),
testutil.Stream("registry1.io", "foo", "other", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000003", "registry1.io/foo/other@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
),
)),
),
expectedLayerLinkDeletions: sets.NewString(),
expectedBlobDeletions: sets.NewString(),
expectedManifestDeletions: sets.NewString(),
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
keepYoungerThan := 60 * time.Minute
keepTagRevisions := 1
options := PrunerOptions{
KeepYoungerThan: &keepYoungerThan,
KeepTagRevisions: &keepTagRevisions,
PruneRegistry: &test.pruneRegistry,
Images: &test.images,
ImageWatcher: watch.NewFake(),
Streams: &test.streams,
StreamWatcher: watch.NewFake(),
Pods: &kapi.PodList{},
RCs: &kapi.ReplicationControllerList{},
BCs: &buildapi.BuildConfigList{},
Builds: &buildapi.BuildList{},
DSs: &kapisext.DaemonSetList{},
Deployments: &kapisext.DeploymentList{},
DCs: &appsapi.DeploymentConfigList{},
RSs: &kapisext.ReplicaSetList{},
RegistryClientFactory: FakeRegistryClientFactory,
RegistryURL: &url.URL{Scheme: "https", Host: "registry1.io"},
}
p, err := NewPruner(options)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, imageDeleterFactory := newFakeImageDeleter(nil)
streamDeleter := &fakeImageStreamDeleter{invocations: sets.NewString()}
layerLinkDeleter := &fakeLayerLinkDeleter{invocations: sets.NewString()}
blobDeleter := &fakeBlobDeleter{invocations: sets.NewString()}
manifestDeleter := &fakeManifestDeleter{invocations: sets.NewString()}
p.Prune(imageDeleterFactory, streamDeleter, layerLinkDeleter, blobDeleter, manifestDeleter)
if a, e := layerLinkDeleter.invocations, test.expectedLayerLinkDeletions; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected layer link deletions: %s", diff.ObjectDiff(a, e))
}
if a, e := blobDeleter.invocations, test.expectedBlobDeletions; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected blob deletions: %s", diff.ObjectDiff(a, e))
}
if a, e := manifestDeleter.invocations, test.expectedManifestDeletions; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected manifest deletions: %s", diff.ObjectDiff(a, e))
}
})
}
}
func newBool(a bool) *bool {
r := new(bool)
*r = a
return r
}
func TestImageWithStrongAndWeakRefsIsNotPruned(t *testing.T) {
flag.Lookup("v").Value.Set(fmt.Sprint(*logLevel))
images := testutil.ImageList(
testutil.AgedImage("0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", 1540),
testutil.AgedImage("0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 1540),
testutil.AgedImage("0000000000000000000000000000000000000000000000000000000000000003", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 1540),
)
streams := testutil.StreamList(
testutil.Stream("registry1", "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("0000000000000000000000000000000000000000000000000000000000000003", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003"),
testutil.TagEvent("0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
testutil.TagEvent("0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
testutil.Tag("strong",
testutil.TagEvent("0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001"),
),
)),
)
pods := testutil.PodList()
rcs := testutil.RCList()
bcs := testutil.BCList()
builds := testutil.BuildList()
dss := testutil.DSList()
deployments := testutil.DeploymentList()
dcs := testutil.DCList()
rss := testutil.RSList()
options := PrunerOptions{
Images: &images,
ImageWatcher: watch.NewFake(),
Streams: &streams,
StreamWatcher: watch.NewFake(),
Pods: &pods,
RCs: &rcs,
BCs: &bcs,
Builds: &builds,
DSs: &dss,
Deployments: &deployments,
DCs: &dcs,
RSs: &rss,
}
keepYoungerThan := 24 * time.Hour
keepTagRevisions := 2
options.KeepYoungerThan = &keepYoungerThan
options.KeepTagRevisions = &keepTagRevisions
p, err := NewPruner(options)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
imageDeleter, imageDeleterFactory := newFakeImageDeleter(nil)
streamDeleter := &fakeImageStreamDeleter{invocations: sets.NewString()}
layerLinkDeleter := &fakeLayerLinkDeleter{invocations: sets.NewString()}
blobDeleter := &fakeBlobDeleter{invocations: sets.NewString()}
manifestDeleter := &fakeManifestDeleter{invocations: sets.NewString()}
deletions, failures := p.Prune(imageDeleterFactory, streamDeleter, layerLinkDeleter, blobDeleter, manifestDeleter)
if len(failures) != 0 {
t.Errorf("got unexpected failures: %#+v", failures)
}
if len(deletions) > 0 {
t.Fatalf("got unexpected deletions: %#+v", deletions)
}
if imageDeleter.invocations.Len() > 0 {
t.Fatalf("unexpected imageDeleter invocations: %v", imageDeleter.invocations)
}
if streamDeleter.invocations.Len() > 0 {
t.Fatalf("unexpected streamDeleter invocations: %v", streamDeleter.invocations)
}
if layerLinkDeleter.invocations.Len() > 0 {
t.Fatalf("unexpected layerLinkDeleter invocations: %v", layerLinkDeleter.invocations)
}
if blobDeleter.invocations.Len() > 0 {
t.Fatalf("unexpected blobDeleter invocations: %v", blobDeleter.invocations)
}
if manifestDeleter.invocations.Len() > 0 {
t.Fatalf("unexpected manifestDeleter invocations: %v", manifestDeleter.invocations)
}
}
func TestImageIsPrunable(t *testing.T) {
g := genericgraph.New()
imageNode := imagegraph.EnsureImageNode(g, &imageapi.Image{ObjectMeta: metav1.ObjectMeta{Name: "myImage"}})
streamNode := imagegraph.EnsureImageStreamNode(g, &imageapi.ImageStream{ObjectMeta: metav1.ObjectMeta{Name: "myStream"}})
g.AddEdge(streamNode, imageNode, ReferencedImageEdgeKind)
g.AddEdge(streamNode, imageNode, WeakReferencedImageEdgeKind)
if imageIsPrunable(g, imageNode.(*imagegraph.ImageNode), pruneAlgorithm{}) {
t.Fatalf("Image is prunable although it should not")
}
}
func TestPrunerGetNextJob(t *testing.T) {
flag.Lookup("v").Value.Set(fmt.Sprint(*logLevel))
glog.V(2).Infof("debug")
algo := pruneAlgorithm{
keepYoungerThan: time.Now(),
}
p := &pruner{algorithm: algo, processedImages: make(map[*imagegraph.ImageNode]*Job)}
images := testutil.ImageList(
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 1, "layer1"),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 2, "layer1", "layer2"),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", 3, "Layer1", "Layer2", "Layer3"),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000013", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000013", 4, "Layer1", "LayeR2", "LayeR3"),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000012", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000012", 5, "LayeR1", "LayeR2"),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000011", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000011", 6, "layer1", "Layer2", "LAYER3", "LAYER4"),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000010", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000010", 7, "layer1", "layer2", "layer3", "layer4"),
)
p.g = genericgraph.New()
err := p.addImagesToGraph(&images)
if err != nil {
t.Fatalf("failed to add images: %v", err)
}
is := images.Items
imageStreams := testutil.StreamList(
testutil.Stream("example.com", "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent(is[3].Name, is[3].DockerImageReference),
testutil.TagEvent(is[4].Name, is[4].DockerImageReference),
testutil.TagEvent(is[5].Name, is[5].DockerImageReference)))),
testutil.Stream("example.com", "foo", "baz", testutil.Tags(
testutil.Tag("devel",
testutil.TagEvent(is[3].Name, is[3].DockerImageReference),
testutil.TagEvent(is[2].Name, is[2].DockerImageReference),
testutil.TagEvent(is[1].Name, is[1].DockerImageReference)),
testutil.Tag("prod",
testutil.TagEvent(is[2].Name, is[2].DockerImageReference)))))
if err := p.addImageStreamsToGraph(&imageStreams, nil); err != nil {
t.Fatalf("failed to add image streams: %v", err)
}
imageNodes := getImageNodes(p.g.Nodes())
if len(imageNodes) == 0 {
t.Fatalf("not images nodes")
}
prunable := calculatePrunableImages(p.g, imageNodes, algo)
sort.Sort(byLayerCountAndAge(prunable))
p.queue = makeQueue(prunable)
checkQueue := func(desc string, expected ...*imageapi.Image) {
for i, item := 0, p.queue; i < len(expected) || item != nil; i++ {
if i >= len(expected) {
t.Errorf("[%s] unexpected image at #%d: %s", desc, i, item.node.Image.Name)
} else if item == nil {
t.Errorf("[%s] expected image %q not found at #%d", desc, expected[i].Name, i)
} else if item.node.Image.Name != expected[i].Name {
t.Errorf("[%s] unexpected image at #%d: %s != %s", desc, i, item.node.Image.Name, expected[i].Name)
}
if item != nil {
item = item.next
}
}
if t.Failed() {
t.FailNow()
}
}
/* layerrefs: layer1:4, Layer1:2, LayeR1:1, layer2:2, Layer2:2, LayeR2:2,
* layer3:1, Layer3:1, LayeR3:1, LAYER3:1, layer4:1, LAYER4:1 */
checkQueue("initial state", &is[6], &is[5], &is[3], &is[2], &is[4], &is[1], &is[0])
job := expectBlockedOrJob(t, p, "pop first", false, &is[6], []string{"layer4", "layer3"})(p.getNextJob())
p.processedImages[job.Image] = job
imgnd6 := job.Image
/* layerrefs: layer1:3, Layer1:2, LayeR1:1, layer2:1, Layer2:2, LayeR2:2,
* layer3:0, Layer3:1, LayeR3:1, LAYER3:1, layer4:0, LAYER4:1 */
checkQueue("1 removed", &is[5], &is[3], &is[2], &is[4], &is[1], &is[0])
job = expectBlockedOrJob(t, p, "pop second", false, &is[5], []string{"LAYER3", "LAYER4"})(p.getNextJob())
p.processedImages[job.Image] = job
imgnd5 := job.Image
/* layerrefs: layer1:2, Layer1:2, LayeR1:1, layer2:1, Layer2:1, LayeR2:2,
* Layer3:1, LayeR3:1, LAYER3:0, LAYER4:0 */
checkQueue("2 removed", &is[3], &is[2], &is[4], &is[1], &is[0])
job = expectBlockedOrJob(t, p, "pop third", false, &is[3], []string{"LayeR3"})(p.getNextJob())
p.processedImages[job.Image] = job
imgnd3 := job.Image
// layerrefs: layer1:2, Layer1:1, LayeR1:1, layer2:1, Layer2:1, LayeR2:1, Layer3:1, LayeR3:0
checkQueue("3 removed", &is[2], &is[4], &is[1], &is[0])
// all the remaining images are blocked now except for the is[0]
job = expectBlockedOrJob(t, p, "pop fourth", false, &is[0], nil)(p.getNextJob())
p.processedImages[job.Image] = job
imgnd0 := job.Image
// layerrefs: layer1:1, Layer1:1, LayeR1:1, layer2:1, Layer2:1, LayeR2:1, Layer3:1
checkQueue("4 removed and blocked", &is[2], &is[4], &is[1])
// all the remaining images are blocked now
expectBlockedOrJob(t, p, "blocked", true, nil, nil)(p.getNextJob())
// layerrefs: layer1:1, Layer1:2, LayeR1:1, layer2:1, Layer2:1, LayeR2:1, Layer3:1
checkQueue("3 to go", &is[2], &is[4], &is[1])
// unblock one of the images
p.g.RemoveNode(imgnd3)
job = expectBlockedOrJob(t, p, "pop fifth", false, &is[4],
[]string{"LayeR1", "LayeR2"})(p.getNextJob())
p.processedImages[job.Image] = job
imgnd4 := job.Image
// layerrefs: layer1:1, Layer1:2, LayeR1:0, layer2:1, Layer2:1, LayeR2:0, Layer3:1
checkQueue("2 to go", &is[2], &is[1])
expectBlockedOrJob(t, p, "blocked with two items#1", true, nil, nil)(p.getNextJob())
checkQueue("still 2 to go", &is[2], &is[1])
p.g.RemoveNode(imgnd0)
delete(p.processedImages, imgnd0)
expectBlockedOrJob(t, p, "blocked with two items#2", true, nil, nil)(p.getNextJob())
p.g.RemoveNode(imgnd6)
delete(p.processedImages, imgnd6)
expectBlockedOrJob(t, p, "blocked with two items#3", true, nil, nil)(p.getNextJob())
p.g.RemoveNode(imgnd4)
delete(p.processedImages, imgnd4)
expectBlockedOrJob(t, p, "blocked with two items#4", true, nil, nil)(p.getNextJob())
p.g.RemoveNode(imgnd5)
delete(p.processedImages, imgnd5)
job = expectBlockedOrJob(t, p, "pop sixth", false, &is[2],
[]string{"Layer1", "Layer2", "Layer3"})(p.getNextJob())
p.processedImages[job.Image] = job
// layerrefs: layer1:1, Layer1:0, layer2:1, Layer2:0, Layer3:0
checkQueue("1 to go", &is[1])
job = expectBlockedOrJob(t, p, "pop last", false, &is[1],
[]string{"layer1", "layer2"})(p.getNextJob())
p.processedImages[job.Image] = job
// layerrefs: layer1:0, layer2:0
checkQueue("queue empty")
expectBlockedOrJob(t, p, "empty", false, nil, nil)(p.getNextJob())
}
func expectBlockedOrJob(
t *testing.T,
p *pruner,
desc string,
blocked bool,
image *imageapi.Image,
layers []string,
) func(job *Job, blocked bool) *Job {
return func(job *Job, b bool) *Job {
if b != blocked {
t.Fatalf("[%s] unexpected blocked: %t != %t", desc, b, blocked)
}
if blocked {
return job
}
if image == nil && job != nil {
t.Fatalf("[%s] got unexpected job %#+v", desc, job)
}
if image != nil && job == nil {
t.Fatalf("[%s] got nil instead of job", desc)
}
if job == nil {
return nil
}
if a, e := job.Image.Image.Name, image.Name; a != e {
t.Errorf("[%s] unexpected image in job: %s != %s", desc, a, e)
}
expLayers := sets.NewString(imagegraph.EnsureImageComponentManifestNode(
p.g, job.Image.Image.Name).(*imagegraph.ImageComponentNode).String())
for _, l := range layers {
expLayers.Insert(imagegraph.EnsureImageComponentLayerNode(
p.g, l).(*imagegraph.ImageComponentNode).String())
}
actLayers := sets.NewString()
for c, ret := range job.Components {
if ret.PrunableGlobally {
actLayers.Insert(c.String())
}
}
if a, e := actLayers, expLayers; !reflect.DeepEqual(a, e) {
t.Errorf("[%s] unexpected image components: %s", desc, diff.ObjectDiff(a.List(), e.List()))
}
if t.Failed() {
t.FailNow()
}
return job
}
}
func TestChangeImageStreamsWhilePruning(t *testing.T) {
t.Skip("failed after commenting out")
flag.Lookup("v").Value.Set(fmt.Sprint(*logLevel))
images := testutil.ImageList(
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000001", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000001", 5),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000002", 4),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000003", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 3),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000004", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 2),
testutil.AgedImage("sha256:0000000000000000000000000000000000000000000000000000000000000005", "registry1.io/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000003", 1),
)
streams := testutil.StreamList(testutil.Stream("registry1", "foo", "bar", testutil.Tags()))
streamWatcher := watch.NewFake()
pods := testutil.PodList()
rcs := testutil.RCList()
bcs := testutil.BCList()
builds := testutil.BuildList()
dss := testutil.DSList()
deployments := testutil.DeploymentList()
dcs := testutil.DCList()
rss := testutil.RSList()
options := PrunerOptions{
Images: &images,
ImageWatcher: watch.NewFake(),
Streams: &streams,
StreamWatcher: streamWatcher,
Pods: &pods,
RCs: &rcs,
BCs: &bcs,
Builds: &builds,
DSs: &dss,
Deployments: &deployments,
DCs: &dcs,
RSs: &rss,
RegistryClientFactory: FakeRegistryClientFactory,
RegistryURL: &url.URL{Scheme: "https", Host: "registry1.io"},
NumWorkers: 1,
}
keepYoungerThan := 30 * time.Second
keepTagRevisions := 2
options.KeepYoungerThan = &keepYoungerThan
options.KeepTagRevisions = &keepTagRevisions
p, err := NewPruner(options)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
pruneFinished := make(chan struct{})
deletions, failures := []Deletion{}, []Failure{}
imageDeleter, imageDeleterFactory := newBlockingImageDeleter(t)
// run the pruning loop in a go routine
go func() {
deletions, failures = p.Prune(
imageDeleterFactory,
&fakeImageStreamDeleter{invocations: sets.NewString()},
&fakeLayerLinkDeleter{invocations: sets.NewString()},
&fakeBlobDeleter{invocations: sets.NewString()},
&fakeManifestDeleter{invocations: sets.NewString()},
)
if len(failures) != 0 {
t.Errorf("got unexpected failures: %#+v", failures)
}
close(pruneFinished)
}()
expectedImageDeletions := sets.NewString()
expectedBlobDeletions := sets.NewString()
img := imageDeleter.waitForRequest()
if a, e := img.Name, images.Items[0].Name; a != e {
t.Fatalf("got unexpected image deletion request: %s != %s", a, e)
}
expectedImageDeletions.Insert(images.Items[0].Name)
expectedBlobDeletions.Insert("registry1|" + images.Items[0].Name)
// let the pruner wait for reply and meanwhile reference an image with a new image stream
stream := testutil.Stream("registry1", "foo", "new", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000002", "registry1/foo/new@sha256:0000000000000000000000000000000000000000000000000000000000000002"),
)))
streamWatcher.Add(&stream)
imageDeleter.unblock()
// the pruner shall skip the newly referenced image
img = imageDeleter.waitForRequest()
if a, e := img.Name, images.Items[2].Name; a != e {
t.Fatalf("got unexpected image deletion request: %s != %s", a, e)
}
expectedImageDeletions.Insert(images.Items[2].Name)
expectedBlobDeletions.Insert("registry1|" + images.Items[2].Name)
// now lets modify the existing image stream to reference some more images
stream = testutil.Stream("registry1", "foo", "bar", testutil.Tags(
testutil.Tag("latest",
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000000", "registry1/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000000"),
testutil.TagEvent("sha256:0000000000000000000000000000000000000000000000000000000000000004", "registry1/foo/bar@sha256:0000000000000000000000000000000000000000000000000000000000000004"),
)))
streamWatcher.Modify(&stream)
imageDeleter.unblock()
// the pruner shall skip the newly referenced image
img = imageDeleter.waitForRequest()
if a, e := img.Name, images.Items[4].Name; a != e {
t.Fatalf("got unexpected image deletion request: %s != %s", a, e)
}
expectedImageDeletions.Insert(images.Items[4].Name)
expectedBlobDeletions.Insert("registry1|" + images.Items[4].Name)
imageDeleter.unblock()
// no more images - wait for the pruner to finish
select {
case <-pruneFinished:
case <-time.After(time.Second):
t.Errorf("tester: timeout while waiting for pruner to finish")
}
if a, e := imageDeleter.d.invocations, expectedImageDeletions; !reflect.DeepEqual(a, e) {
t.Errorf("unexpected image deletions: %s", diff.ObjectDiff(a, e))
}
expectedAllDeletions := sets.NewString(
append(expectedImageDeletions.List(), expectedBlobDeletions.List()...)...)
for _, d := range deletions {
rendered, _, isManifestLinkDeletion := renderDeletion("registry1", &d)
if isManifestLinkDeletion {
// TODO: update tests to count and verify the number of manifest link deletions
continue
}
if expectedAllDeletions.Has(rendered) {
expectedAllDeletions.Delete(rendered)
} else {
t.Errorf("got unexpected deletion: %#+v (rendered: %q)", d, rendered)
}
}
for del, ok := expectedAllDeletions.PopAny(); ok; del, ok = expectedAllDeletions.PopAny() {
t.Errorf("expected deletion %q did not happen", del)
}
}
func streamListToClient(list *imageapi.ImageStreamList) imageclient.ImageStreamsGetter {
streams := make([]runtime.Object, 0, len(list.Items))
for i := range list.Items {
streams = append(streams, &list.Items[i])
}
return fakeimageclient.NewSimpleClientset(streams...).Image()
}
func keepTagRevisions(n int) *int {
return &n
}
type fakeImageDeleter struct {
mutex sync.Mutex
invocations sets.String
err error
}
var _ ImageDeleter = &fakeImageDeleter{}
func (p *fakeImageDeleter) DeleteImage(image *imageapi.Image) error {
p.mutex.Lock()
defer p.mutex.Unlock()
p.invocations.Insert(image.Name)
return p.err
}
func newFakeImageDeleter(err error) (*fakeImageDeleter, ImagePrunerFactoryFunc) {
deleter := &fakeImageDeleter{
err: err,
invocations: sets.NewString(),
}
return deleter, func() (ImageDeleter, error) {
return deleter, nil
}
}
type blockingImageDeleter struct {
t *testing.T
d *fakeImageDeleter
requests chan *imageapi.Image
reply chan struct{}
}
func (bid *blockingImageDeleter) DeleteImage(img *imageapi.Image) error {
bid.requests <- img
select {
case <-bid.reply:
case <-time.After(time.Second):
bid.t.Fatalf("worker: timeout while waiting for image deletion confirmation")
}
return bid.d.DeleteImage(img)
}
func (bid *blockingImageDeleter) waitForRequest() *imageapi.Image {
select {
case img := <-bid.requests:
return img
case <-time.After(time.Second):
bid.t.Fatalf("tester: timeout while waiting on worker's request")
return nil
}
}
func (bid *blockingImageDeleter) unblock() {
bid.reply <- struct{}{}
}
func newBlockingImageDeleter(t *testing.T) (*blockingImageDeleter, ImagePrunerFactoryFunc) {
deleter, _ := newFakeImageDeleter(nil)
blocking := blockingImageDeleter{
t: t,
d: deleter,
requests: make(chan *imageapi.Image),
reply: make(chan struct{}),
}
return &blocking, func() (ImageDeleter, error) {
return &blocking, nil
}
}
type fakeImageStreamDeleter struct {
mutex sync.Mutex
invocations sets.String
err error
streamImages map[string][]string
streamTags map[string][]string
}
var _ ImageStreamDeleter = &fakeImageStreamDeleter{}
func (p *fakeImageStreamDeleter) GetImageStream(stream *imageapi.ImageStream) (*imageapi.ImageStream, error) {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.streamImages == nil {
p.streamImages = make(map[string][]string)
}
if p.streamTags == nil {
p.streamTags = make(map[string][]string)
}
for tag, history := range stream.Status.Tags {
streamName := fmt.Sprintf("%s/%s", stream.Namespace, stream.Name)
p.streamTags[streamName] = append(p.streamTags[streamName], tag)
for _, tagEvent := range history.Items {
p.streamImages[streamName] = append(p.streamImages[streamName], tagEvent.Image)
}
}
return stream, p.err
}
func (p *fakeImageStreamDeleter) UpdateImageStream(stream *imageapi.ImageStream) (*imageapi.ImageStream, error) {
streamImages := make(map[string]struct{})
streamTags := make(map[string]struct{})
for tag, history := range stream.Status.Tags {
streamTags[tag] = struct{}{}
for _, tagEvent := range history.Items {
streamImages[tagEvent.Image] = struct{}{}
}
}
streamName := fmt.Sprintf("%s/%s", stream.Namespace, stream.Name)
for _, tag := range p.streamTags[streamName] {
if _, ok := streamTags[tag]; !ok {
p.invocations.Insert(fmt.Sprintf("%s:%s", streamName, tag))
}
}
for _, imageName := range p.streamImages[streamName] {
if _, ok := streamImages[imageName]; !ok {
p.invocations.Insert(fmt.Sprintf("%s|%s", streamName, imageName))
}
}
return stream, p.err
}
func (p *fakeImageStreamDeleter) NotifyImageStreamPrune(stream *imageapi.ImageStream, updatedTags []string, deletedTags []string) {
return
}
type errorForSHA func(dgst string) error
type fakeBlobDeleter struct {
mutex sync.Mutex
invocations sets.String
getError errorForSHA
}
var _ BlobDeleter = &fakeBlobDeleter{}
func (p *fakeBlobDeleter) DeleteBlob(registryClient *http.Client, registryURL *url.URL, blob string) error {
p.mutex.Lock()
defer p.mutex.Unlock()
p.invocations.Insert(fmt.Sprintf("%s|%s", registryURL.String(), blob))
if p.getError == nil {
return nil
}
return p.getError(blob)
}
type fakeLayerLinkDeleter struct {
mutex sync.Mutex
invocations sets.String
err error
}
var _ LayerLinkDeleter = &fakeLayerLinkDeleter{}
func (p *fakeLayerLinkDeleter) DeleteLayerLink(registryClient *http.Client, registryURL *url.URL, repo, layer string) error {
p.mutex.Lock()
defer p.mutex.Unlock()
p.invocations.Insert(fmt.Sprintf("%s|%s|%s", registryURL.String(), repo, layer))
return p.err
}
type fakeManifestDeleter struct {
mutex sync.Mutex
invocations sets.String
err error
}
var _ ManifestDeleter = &fakeManifestDeleter{}
func (p *fakeManifestDeleter) DeleteManifest(registryClient *http.Client, registryURL *url.URL, repo, manifest string) error {
p.mutex.Lock()
defer p.mutex.Unlock()
p.invocations.Insert(fmt.Sprintf("%s|%s|%s", registryURL.String(), repo, manifest))
return p.err
}
| {'content_hash': '16c61555494a60a5b1f22915542af954', 'timestamp': '', 'source': 'github', 'line_count': 2256, 'max_line_length': 267, 'avg_line_length': 58.552304964539005, 'alnum_prop': 0.7743349432979545, 'repo_name': 'legionus/origin', 'id': '9b777651d2dea1357cddda5415ce9192fbac5b8e', 'size': '132094', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'pkg/oc/admin/prune/imageprune/prune_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '1842'}, {'name': 'DIGITAL Command Language', 'bytes': '117'}, {'name': 'Go', 'bytes': '18908374'}, {'name': 'Groovy', 'bytes': '5288'}, {'name': 'HTML', 'bytes': '74732'}, {'name': 'Makefile', 'bytes': '21890'}, {'name': 'Protocol Buffer', 'bytes': '635763'}, {'name': 'Python', 'bytes': '33408'}, {'name': 'Roff', 'bytes': '2049'}, {'name': 'Ruby', 'bytes': '484'}, {'name': 'Shell', 'bytes': '2159344'}, {'name': 'Smarty', 'bytes': '626'}]} |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>IParticleID | hifi</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
<script src="../assets/js/modernizr.js"></script>
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">hifi</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-private" checked />
<label class="tsd-widget" for="tsd-filter-private">Private</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/hifi.html">hifi</a>
</li>
<li>
<a href="hifi.iparticleid.html">IParticleID</a>
</li>
</ul>
<h1>Interface IParticleID</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-comment">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Abstract ID for editing particles. Used in Particle JS API - When particles are created in the JS api, they are given a
local creatorTokenID, the actual id for the particle is not known until the server responds to the creator with the
correct mapping. This class works with the scripting API an allows the developer to edit particles they created.
Checked against /libraries/particles/src/Particle.h
September 16th, 2014</p>
</div>
</div>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section ">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="hifi.iparticleid.html#creatortokenid" class="tsd-kind-icon">creator<wbr>TokenID</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="hifi.iparticleid.html#id" class="tsd-kind-icon">id</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="hifi.iparticleid.html#isknownid" class="tsd-kind-icon">is<wbr>KnownID</a></li>
</ul>
</section>
</div>
</section>
</section> <section class="tsd-panel-group tsd-member-group ">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="creatortokenid" class="anchor"></a>
<h3>creator<wbr>TokenID</h3>
<div class="tsd-signature tsd-kind-icon">creator<wbr>TokenID<span class="tsd-signature-symbol">:</span> <a href="hifi.iuint32.html" class="tsd-signature-type">IUInt32</a></div>
<aside class="tsd-sources">
<ul>
<li>Defined in hifi/Particles.d.ts:57</li>
</ul>
</aside>
</section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="id" class="anchor"></a>
<h3>id</h3>
<div class="tsd-signature tsd-kind-icon">id<span class="tsd-signature-symbol">:</span> <a href="hifi.iuint32.html" class="tsd-signature-type">IUInt32</a></div>
<aside class="tsd-sources">
<ul>
<li>Defined in hifi/Particles.d.ts:56</li>
</ul>
</aside>
</section> <section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="isknownid" class="anchor"></a>
<h3>is<wbr>KnownID</h3>
<div class="tsd-signature tsd-kind-icon">is<wbr>KnownID<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">boolean</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in hifi/Particles.d.ts:58</li>
</ul>
</aside>
</section></section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class="current tsd-kind-container">
<a href="../modules/hifi.html">hifi</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-parent-kind-container">
<a href="hifi.iparticleid.html" class="tsd-kind-icon">IParticleID</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="hifi.iparticleid.html#creatortokenid" class="tsd-kind-icon">creator<wbr>TokenID</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="hifi.iparticleid.html#id" class="tsd-kind-icon">id</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="hifi.iparticleid.html#isknownid" class="tsd-kind-icon">is<wbr>KnownID</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-container"><span class="tsd-kind-icon">Container, dynamic module</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-construct-signature"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-call-signature"><span class="tsd-kind-icon">Function, call signature, accessor</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-construct-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Member, accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-construct-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Member, accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li> </li>
<li class="tsd-kind-construct-signature tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited member</span></li>
</ul>
<ul class="tsd-legend">
<li> </li>
<li class="tsd-kind-construct-signature tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private member</span></li>
</ul>
<ul class="tsd-legend">
<li> </li>
<li> </li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static member</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html> | {'content_hash': '874face7f1266cacd7b32134a2994af6', 'timestamp': '', 'source': 'github', 'line_count': 219, 'max_line_length': 189, 'avg_line_length': 46.93150684931507, 'alnum_prop': 0.6484724654602063, 'repo_name': 'JeroMiya/hifi-typescript', 'id': 'c8febfd9e8269d7bb979b6c692ed330bc6be0b4c', 'size': '10280', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'HiFi/docs/interfaces/hifi.iparticleid.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '46500'}, {'name': 'JavaScript', 'bytes': '793569'}, {'name': 'TypeScript', 'bytes': '57695'}]} |
<!DOCTYPE html>
<html>
<head>
<script>
function performTest(api)
{
api.Hierarchy.avoidInlineChildren(document.body);
}
</script>
</head>
<body>
One
<p>Two</p>
Three
</body>
</html>
| {'content_hash': '4c1c36ca351690a0d38d3bc732f3bd9b', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 53, 'avg_line_length': 11.5625, 'alnum_prop': 0.6756756756756757, 'repo_name': 'corinthia/corinthia-editor', 'id': 'f8c82172fef0463e29fbeac74bffeed4b8ce3b27', 'size': '185', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tests/dom/avoidInline04-input.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1240'}, {'name': 'HTML', 'bytes': '2137899'}, {'name': 'JavaScript', 'bytes': '205085'}, {'name': 'Perl', 'bytes': '1558'}, {'name': 'Shell', 'bytes': '1657'}, {'name': 'TypeScript', 'bytes': '648217'}]} |
package com.amazonaws.services.ecs.model;
import java.io.Serializable;
/**
*
*/
public class UpdateContainerAgentResult implements Serializable, Cloneable {
/**
* An Amazon EC2 instance that is running the Amazon ECS agent and has
* been registered with a cluster.
*/
private ContainerInstance containerInstance;
/**
* An Amazon EC2 instance that is running the Amazon ECS agent and has
* been registered with a cluster.
*
* @return An Amazon EC2 instance that is running the Amazon ECS agent and has
* been registered with a cluster.
*/
public ContainerInstance getContainerInstance() {
return containerInstance;
}
/**
* An Amazon EC2 instance that is running the Amazon ECS agent and has
* been registered with a cluster.
*
* @param containerInstance An Amazon EC2 instance that is running the Amazon ECS agent and has
* been registered with a cluster.
*/
public void setContainerInstance(ContainerInstance containerInstance) {
this.containerInstance = containerInstance;
}
/**
* An Amazon EC2 instance that is running the Amazon ECS agent and has
* been registered with a cluster.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param containerInstance An Amazon EC2 instance that is running the Amazon ECS agent and has
* been registered with a cluster.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UpdateContainerAgentResult withContainerInstance(ContainerInstance containerInstance) {
this.containerInstance = containerInstance;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getContainerInstance() != null) sb.append("ContainerInstance: " + getContainerInstance() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getContainerInstance() == null) ? 0 : getContainerInstance().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof UpdateContainerAgentResult == false) return false;
UpdateContainerAgentResult other = (UpdateContainerAgentResult)obj;
if (other.getContainerInstance() == null ^ this.getContainerInstance() == null) return false;
if (other.getContainerInstance() != null && other.getContainerInstance().equals(this.getContainerInstance()) == false) return false;
return true;
}
@Override
public UpdateContainerAgentResult clone() {
try {
return (UpdateContainerAgentResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!",
e);
}
}
}
| {'content_hash': '2c3072cba71041c4a9ea434fd47916cb', 'timestamp': '', 'source': 'github', 'line_count': 110, 'max_line_length': 141, 'avg_line_length': 32.518181818181816, 'alnum_prop': 0.6304165501817165, 'repo_name': 'malti1yadav/aws-sdk-java', 'id': 'cfbf692f4da3feb551ea4929e0f54007c83f89f5', 'size': '4164', 'binary': False, 'copies': '26', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-ecs/src/main/java/com/amazonaws/services/ecs/model/UpdateContainerAgentResult.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '88235127'}, {'name': 'Scilab', 'bytes': '2354'}]} |
'use strict';
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Any commits to this file should be reviewed with security in mind. *
* Changes to this file can potentially create security vulnerabilities. *
* An approval from 2 Core members with history of modifying *
* this file is required. *
* *
* Does the change somehow allow for arbitrary javascript to be executed? *
* Or allows for someone to change the prototype of built-in objects? *
* Or gives undesired access to variables likes document or window? *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var $parseMinErr = minErr('$parse');
// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct
// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor.
//
// As an example, consider the following Angular expression:
//
// {}.toString.constructor('alert("evil JS code")')
//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
// against the expression language, but not to prevent exploits that were enabled by exposing
// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
// practice and therefore we are not even trying to protect against interaction with an object
// explicitly exposed in this way.
//
// In general, it is not possible to access a Window object from an angular expression unless a
// window or some DOM object that has a reference to window is published onto a Scope.
// Similarly we prevent invocations of function known to be dangerous, as well as assignments to
// native objects.
//
// See https://docs.angularjs.org/guide/security
function ensureSafeMemberName(name, fullExpression) {
if (name === "__defineGetter__" || name === "__defineSetter__"
|| name === "__lookupGetter__" || name === "__lookupSetter__"
|| name === "__proto__") {
throw $parseMinErr('isecfld',
'Attempting to access a disallowed field in Angular expressions! '
+ 'Expression: {0}', fullExpression);
}
return name;
}
function getStringValue(name) {
// Property names must be strings. This means that non-string objects cannot be used
// as keys in an object. Any non-string object, including a number, is typecasted
// into a string via the toString method.
// -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
//
// So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
// to a string. It's not always possible. If `name` is an object and its `toString` method is
// 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
//
// TypeError: Cannot convert object to primitive value
//
// For performance reasons, we don't catch this error here and allow it to propagate up the call
// stack. Note that you'll get the same error in JavaScript if you try to access a property using
// such a 'broken' object as a key.
return name + '';
}
function ensureSafeObject(obj, fullExpression) {
// nifty check if obj is Function that is fast and works across iframes and other contexts
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isWindow(obj)
obj.window === obj) {
throw $parseMinErr('isecwindow',
'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isElement(obj)
obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
throw $parseMinErr('isecdom',
'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// block Object so that we can't get hold of dangerous Object.* methods
obj === Object) {
throw $parseMinErr('isecobj',
'Referencing Object in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
return obj;
}
var CALL = Function.prototype.call;
var APPLY = Function.prototype.apply;
var BIND = Function.prototype.bind;
function ensureSafeFunction(obj, fullExpression) {
if (obj) {
if (obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (obj === CALL || obj === APPLY || obj === BIND) {
throw $parseMinErr('isecff',
'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
}
}
function ensureSafeAssignContext(obj, fullExpression) {
if (obj) {
if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
throw $parseMinErr('isecaf',
'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
}
}
}
var OPERATORS = createMap();
forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
/////////////////////////////////////////
/**
* @constructor
*/
var Lexer = function(options) {
this.options = options;
};
Lexer.prototype = {
constructor: Lexer,
lex: function(text) {
this.text = text;
this.index = 0;
this.tokens = [];
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (ch === '"' || ch === "'") {
this.readString(ch);
} else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
this.readNumber();
} else if (this.isIdent(ch)) {
this.readIdent();
} else if (this.is(ch, '(){}[].,;:?')) {
this.tokens.push({index: this.index, text: ch});
this.index++;
} else if (this.isWhitespace(ch)) {
this.index++;
} else {
var ch2 = ch + this.peek();
var ch3 = ch2 + this.peek(2);
var op1 = OPERATORS[ch];
var op2 = OPERATORS[ch2];
var op3 = OPERATORS[ch3];
if (op1 || op2 || op3) {
var token = op3 ? ch3 : (op2 ? ch2 : ch);
this.tokens.push({index: this.index, text: token, operator: true});
this.index += token.length;
} else {
this.throwError('Unexpected next character ', this.index, this.index + 1);
}
}
}
return this.tokens;
},
is: function(ch, chars) {
return chars.indexOf(ch) !== -1;
},
peek: function(i) {
var num = i || 1;
return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
},
isNumber: function(ch) {
return ('0' <= ch && ch <= '9') && typeof ch === "string";
},
isWhitespace: function(ch) {
// IE treats non-breaking space as \u00A0
return (ch === ' ' || ch === '\r' || ch === '\t' ||
ch === '\n' || ch === '\v' || ch === '\u00A0');
},
isIdent: function(ch) {
return ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' === ch || ch === '$');
},
isExpOperator: function(ch) {
return (ch === '-' || ch === '+' || this.isNumber(ch));
},
throwError: function(error, start, end) {
end = end || this.index;
var colStr = (isDefined(start)
? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
: ' ' + end);
throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
error, colStr, this.text);
},
readNumber: function() {
var number = '';
var start = this.index;
while (this.index < this.text.length) {
var ch = lowercase(this.text.charAt(this.index));
if (ch == '.' || this.isNumber(ch)) {
number += ch;
} else {
var peekCh = this.peek();
if (ch == 'e' && this.isExpOperator(peekCh)) {
number += ch;
} else if (this.isExpOperator(ch) &&
peekCh && this.isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (this.isExpOperator(ch) &&
(!peekCh || !this.isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
this.throwError('Invalid exponent');
} else {
break;
}
}
this.index++;
}
this.tokens.push({
index: start,
text: number,
constant: true,
value: Number(number)
});
},
readIdent: function() {
var start = this.index;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
if (!(this.isIdent(ch) || this.isNumber(ch))) {
break;
}
this.index++;
}
this.tokens.push({
index: start,
text: this.text.slice(start, this.index),
identifier: true
});
},
readString: function(quote) {
var start = this.index;
this.index++;
var string = '';
var rawString = quote;
var escape = false;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
rawString += ch;
if (escape) {
if (ch === 'u') {
var hex = this.text.substring(this.index + 1, this.index + 5);
if (!hex.match(/[\da-f]{4}/i)) {
this.throwError('Invalid unicode escape [\\u' + hex + ']');
}
this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
string = string + (rep || ch);
}
escape = false;
} else if (ch === '\\') {
escape = true;
} else if (ch === quote) {
this.index++;
this.tokens.push({
index: start,
text: rawString,
constant: true,
value: string
});
return;
} else {
string += ch;
}
this.index++;
}
this.throwError('Unterminated quote', start);
}
};
var AST = function(lexer, options) {
this.lexer = lexer;
this.options = options;
};
AST.Program = 'Program';
AST.ExpressionStatement = 'ExpressionStatement';
AST.AssignmentExpression = 'AssignmentExpression';
AST.ConditionalExpression = 'ConditionalExpression';
AST.LogicalExpression = 'LogicalExpression';
AST.BinaryExpression = 'BinaryExpression';
AST.UnaryExpression = 'UnaryExpression';
AST.CallExpression = 'CallExpression';
AST.MemberExpression = 'MemberExpression';
AST.Identifier = 'Identifier';
AST.Literal = 'Literal';
AST.ArrayExpression = 'ArrayExpression';
AST.Property = 'Property';
AST.ObjectExpression = 'ObjectExpression';
AST.ThisExpression = 'ThisExpression';
AST.LocalsExpression = 'LocalsExpression';
// Internal use only
AST.NGValueParameter = 'NGValueParameter';
AST.prototype = {
ast: function(text) {
this.text = text;
this.tokens = this.lexer.lex(text);
var value = this.program();
if (this.tokens.length !== 0) {
this.throwError('is an unexpected token', this.tokens[0]);
}
return value;
},
program: function() {
var body = [];
while (true) {
if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
body.push(this.expressionStatement());
if (!this.expect(';')) {
return { type: AST.Program, body: body};
}
}
},
expressionStatement: function() {
return { type: AST.ExpressionStatement, expression: this.filterChain() };
},
filterChain: function() {
var left = this.expression();
var token;
while ((token = this.expect('|'))) {
left = this.filter(left);
}
return left;
},
expression: function() {
return this.assignment();
},
assignment: function() {
var result = this.ternary();
if (this.expect('=')) {
result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
}
return result;
},
ternary: function() {
var test = this.logicalOR();
var alternate;
var consequent;
if (this.expect('?')) {
alternate = this.expression();
if (this.consume(':')) {
consequent = this.expression();
return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
}
}
return test;
},
logicalOR: function() {
var left = this.logicalAND();
while (this.expect('||')) {
left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
}
return left;
},
logicalAND: function() {
var left = this.equality();
while (this.expect('&&')) {
left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
}
return left;
},
equality: function() {
var left = this.relational();
var token;
while ((token = this.expect('==','!=','===','!=='))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
}
return left;
},
relational: function() {
var left = this.additive();
var token;
while ((token = this.expect('<', '>', '<=', '>='))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
}
return left;
},
additive: function() {
var left = this.multiplicative();
var token;
while ((token = this.expect('+','-'))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
}
return left;
},
multiplicative: function() {
var left = this.unary();
var token;
while ((token = this.expect('*','/','%'))) {
left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
}
return left;
},
unary: function() {
var token;
if ((token = this.expect('+', '-', '!'))) {
return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
} else {
return this.primary();
}
},
primary: function() {
var primary;
if (this.expect('(')) {
primary = this.filterChain();
this.consume(')');
} else if (this.expect('[')) {
primary = this.arrayDeclaration();
} else if (this.expect('{')) {
primary = this.object();
} else if (this.constants.hasOwnProperty(this.peek().text)) {
primary = copy(this.constants[this.consume().text]);
} else if (this.peek().identifier) {
primary = this.identifier();
} else if (this.peek().constant) {
primary = this.constant();
} else {
this.throwError('not a primary expression', this.peek());
}
var next;
while ((next = this.expect('(', '[', '.'))) {
if (next.text === '(') {
primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
this.consume(')');
} else if (next.text === '[') {
primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
this.consume(']');
} else if (next.text === '.') {
primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
} else {
this.throwError('IMPOSSIBLE');
}
}
return primary;
},
filter: function(baseExpression) {
var args = [baseExpression];
var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
while (this.expect(':')) {
args.push(this.expression());
}
return result;
},
parseArguments: function() {
var args = [];
if (this.peekToken().text !== ')') {
do {
args.push(this.expression());
} while (this.expect(','));
}
return args;
},
identifier: function() {
var token = this.consume();
if (!token.identifier) {
this.throwError('is not a valid identifier', token);
}
return { type: AST.Identifier, name: token.text };
},
constant: function() {
// TODO check that it is a constant
return { type: AST.Literal, value: this.consume().value };
},
arrayDeclaration: function() {
var elements = [];
if (this.peekToken().text !== ']') {
do {
if (this.peek(']')) {
// Support trailing commas per ES5.1.
break;
}
elements.push(this.expression());
} while (this.expect(','));
}
this.consume(']');
return { type: AST.ArrayExpression, elements: elements };
},
object: function() {
var properties = [], property;
if (this.peekToken().text !== '}') {
do {
if (this.peek('}')) {
// Support trailing commas per ES5.1.
break;
}
property = {type: AST.Property, kind: 'init'};
if (this.peek().constant) {
property.key = this.constant();
} else if (this.peek().identifier) {
property.key = this.identifier();
} else {
this.throwError("invalid key", this.peek());
}
this.consume(':');
property.value = this.expression();
properties.push(property);
} while (this.expect(','));
}
this.consume('}');
return {type: AST.ObjectExpression, properties: properties };
},
throwError: function(msg, token) {
throw $parseMinErr('syntax',
'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
},
consume: function(e1) {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
var token = this.expect(e1);
if (!token) {
this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
}
return token;
},
peekToken: function() {
if (this.tokens.length === 0) {
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
}
return this.tokens[0];
},
peek: function(e1, e2, e3, e4) {
return this.peekAhead(0, e1, e2, e3, e4);
},
peekAhead: function(i, e1, e2, e3, e4) {
if (this.tokens.length > i) {
var token = this.tokens[i];
var t = token.text;
if (t === e1 || t === e2 || t === e3 || t === e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
},
expect: function(e1, e2, e3, e4) {
var token = this.peek(e1, e2, e3, e4);
if (token) {
this.tokens.shift();
return token;
}
return false;
},
/* `undefined` is not a constant, it is an identifier,
* but using it as an identifier is not supported
*/
constants: {
'true': { type: AST.Literal, value: true },
'false': { type: AST.Literal, value: false },
'null': { type: AST.Literal, value: null },
'undefined': {type: AST.Literal, value: undefined },
'this': {type: AST.ThisExpression },
'$locals': {type: AST.LocalsExpression }
}
};
function ifDefined(v, d) {
return typeof v !== 'undefined' ? v : d;
}
function plusFn(l, r) {
if (typeof l === 'undefined') return r;
if (typeof r === 'undefined') return l;
return l + r;
}
function isStateless($filter, filterName) {
var fn = $filter(filterName);
return !fn.$stateful;
}
function findConstantAndWatchExpressions(ast, $filter) {
var allConstants;
var argsToWatch;
switch (ast.type) {
case AST.Program:
allConstants = true;
forEach(ast.body, function(expr) {
findConstantAndWatchExpressions(expr.expression, $filter);
allConstants = allConstants && expr.expression.constant;
});
ast.constant = allConstants;
break;
case AST.Literal:
ast.constant = true;
ast.toWatch = [];
break;
case AST.UnaryExpression:
findConstantAndWatchExpressions(ast.argument, $filter);
ast.constant = ast.argument.constant;
ast.toWatch = ast.argument.toWatch;
break;
case AST.BinaryExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
break;
case AST.LogicalExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = ast.constant ? [] : [ast];
break;
case AST.ConditionalExpression:
findConstantAndWatchExpressions(ast.test, $filter);
findConstantAndWatchExpressions(ast.alternate, $filter);
findConstantAndWatchExpressions(ast.consequent, $filter);
ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
ast.toWatch = ast.constant ? [] : [ast];
break;
case AST.Identifier:
ast.constant = false;
ast.toWatch = [ast];
break;
case AST.MemberExpression:
findConstantAndWatchExpressions(ast.object, $filter);
if (ast.computed) {
findConstantAndWatchExpressions(ast.property, $filter);
}
ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
ast.toWatch = [ast];
break;
case AST.CallExpression:
allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
argsToWatch = [];
forEach(ast.arguments, function(expr) {
findConstantAndWatchExpressions(expr, $filter);
allConstants = allConstants && expr.constant;
if (!expr.constant) {
argsToWatch.push.apply(argsToWatch, expr.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
break;
case AST.AssignmentExpression:
findConstantAndWatchExpressions(ast.left, $filter);
findConstantAndWatchExpressions(ast.right, $filter);
ast.constant = ast.left.constant && ast.right.constant;
ast.toWatch = [ast];
break;
case AST.ArrayExpression:
allConstants = true;
argsToWatch = [];
forEach(ast.elements, function(expr) {
findConstantAndWatchExpressions(expr, $filter);
allConstants = allConstants && expr.constant;
if (!expr.constant) {
argsToWatch.push.apply(argsToWatch, expr.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = argsToWatch;
break;
case AST.ObjectExpression:
allConstants = true;
argsToWatch = [];
forEach(ast.properties, function(property) {
findConstantAndWatchExpressions(property.value, $filter);
allConstants = allConstants && property.value.constant;
if (!property.value.constant) {
argsToWatch.push.apply(argsToWatch, property.value.toWatch);
}
});
ast.constant = allConstants;
ast.toWatch = argsToWatch;
break;
case AST.ThisExpression:
ast.constant = false;
ast.toWatch = [];
break;
case AST.LocalsExpression:
ast.constant = false;
ast.toWatch = [];
break;
}
}
function getInputs(body) {
if (body.length != 1) return;
var lastExpression = body[0].expression;
var candidate = lastExpression.toWatch;
if (candidate.length !== 1) return candidate;
return candidate[0] !== lastExpression ? candidate : undefined;
}
function isAssignable(ast) {
return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
}
function assignableAST(ast) {
if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
}
}
function isLiteral(ast) {
return ast.body.length === 0 ||
ast.body.length === 1 && (
ast.body[0].expression.type === AST.Literal ||
ast.body[0].expression.type === AST.ArrayExpression ||
ast.body[0].expression.type === AST.ObjectExpression);
}
function isConstant(ast) {
return ast.constant;
}
function ASTCompiler(astBuilder, $filter) {
this.astBuilder = astBuilder;
this.$filter = $filter;
}
ASTCompiler.prototype = {
compile: function(expression, expensiveChecks) {
var self = this;
var ast = this.astBuilder.ast(expression);
this.state = {
nextId: 0,
filters: {},
expensiveChecks: expensiveChecks,
fn: {vars: [], body: [], own: {}},
assign: {vars: [], body: [], own: {}},
inputs: []
};
findConstantAndWatchExpressions(ast, self.$filter);
var extra = '';
var assignable;
this.stage = 'assign';
if ((assignable = assignableAST(ast))) {
this.state.computing = 'assign';
var result = this.nextId();
this.recurse(assignable, result);
this.return_(result);
extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
}
var toWatch = getInputs(ast.body);
self.stage = 'inputs';
forEach(toWatch, function(watch, key) {
var fnKey = 'fn' + key;
self.state[fnKey] = {vars: [], body: [], own: {}};
self.state.computing = fnKey;
var intoId = self.nextId();
self.recurse(watch, intoId);
self.return_(intoId);
self.state.inputs.push(fnKey);
watch.watchId = key;
});
this.state.computing = 'fn';
this.stage = 'main';
this.recurse(ast);
var fnString =
// The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
// This is a workaround for this until we do a better job at only removing the prefix only when we should.
'"' + this.USE + ' ' + this.STRICT + '";\n' +
this.filterPrefix() +
'var fn=' + this.generateFunction('fn', 's,l,a,i') +
extra +
this.watchFns() +
'return fn;';
/* jshint -W054 */
var fn = (new Function('$filter',
'ensureSafeMemberName',
'ensureSafeObject',
'ensureSafeFunction',
'getStringValue',
'ensureSafeAssignContext',
'ifDefined',
'plus',
'text',
fnString))(
this.$filter,
ensureSafeMemberName,
ensureSafeObject,
ensureSafeFunction,
getStringValue,
ensureSafeAssignContext,
ifDefined,
plusFn,
expression);
/* jshint +W054 */
this.state = this.stage = undefined;
fn.literal = isLiteral(ast);
fn.constant = isConstant(ast);
return fn;
},
USE: 'use',
STRICT: 'strict',
watchFns: function() {
var result = [];
var fns = this.state.inputs;
var self = this;
forEach(fns, function(name) {
result.push('var ' + name + '=' + self.generateFunction(name, 's'));
});
if (fns.length) {
result.push('fn.inputs=[' + fns.join(',') + '];');
}
return result.join('');
},
generateFunction: function(name, params) {
return 'function(' + params + '){' +
this.varsPrefix(name) +
this.body(name) +
'};';
},
filterPrefix: function() {
var parts = [];
var self = this;
forEach(this.state.filters, function(id, filter) {
parts.push(id + '=$filter(' + self.escape(filter) + ')');
});
if (parts.length) return 'var ' + parts.join(',') + ';';
return '';
},
varsPrefix: function(section) {
return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
},
body: function(section) {
return this.state[section].body.join('');
},
recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
var left, right, self = this, args, expression;
recursionFn = recursionFn || noop;
if (!skipWatchIdCheck && isDefined(ast.watchId)) {
intoId = intoId || this.nextId();
this.if_('i',
this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
);
return;
}
switch (ast.type) {
case AST.Program:
forEach(ast.body, function(expression, pos) {
self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
if (pos !== ast.body.length - 1) {
self.current().body.push(right, ';');
} else {
self.return_(right);
}
});
break;
case AST.Literal:
expression = this.escape(ast.value);
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.UnaryExpression:
this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.BinaryExpression:
this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
if (ast.operator === '+') {
expression = this.plus(left, right);
} else if (ast.operator === '-') {
expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
} else {
expression = '(' + left + ')' + ast.operator + '(' + right + ')';
}
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.LogicalExpression:
intoId = intoId || this.nextId();
self.recurse(ast.left, intoId);
self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
recursionFn(intoId);
break;
case AST.ConditionalExpression:
intoId = intoId || this.nextId();
self.recurse(ast.test, intoId);
self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
recursionFn(intoId);
break;
case AST.Identifier:
intoId = intoId || this.nextId();
if (nameId) {
nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
nameId.computed = false;
nameId.name = ast.name;
}
ensureSafeMemberName(ast.name);
self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
function() {
self.if_(self.stage === 'inputs' || 's', function() {
if (create && create !== 1) {
self.if_(
self.not(self.nonComputedMember('s', ast.name)),
self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
}
self.assign(intoId, self.nonComputedMember('s', ast.name));
});
}, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
);
if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
self.addEnsureSafeObject(intoId);
}
recursionFn(intoId);
break;
case AST.MemberExpression:
left = nameId && (nameId.context = this.nextId()) || this.nextId();
intoId = intoId || this.nextId();
self.recurse(ast.object, left, undefined, function() {
self.if_(self.notNull(left), function() {
if (create && create !== 1) {
self.addEnsureSafeAssignContext(left);
}
if (ast.computed) {
right = self.nextId();
self.recurse(ast.property, right);
self.getStringValue(right);
self.addEnsureSafeMemberName(right);
if (create && create !== 1) {
self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
}
expression = self.ensureSafeObject(self.computedMember(left, right));
self.assign(intoId, expression);
if (nameId) {
nameId.computed = true;
nameId.name = right;
}
} else {
ensureSafeMemberName(ast.property.name);
if (create && create !== 1) {
self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
}
expression = self.nonComputedMember(left, ast.property.name);
if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
expression = self.ensureSafeObject(expression);
}
self.assign(intoId, expression);
if (nameId) {
nameId.computed = false;
nameId.name = ast.property.name;
}
}
}, function() {
self.assign(intoId, 'undefined');
});
recursionFn(intoId);
}, !!create);
break;
case AST.CallExpression:
intoId = intoId || this.nextId();
if (ast.filter) {
right = self.filter(ast.callee.name);
args = [];
forEach(ast.arguments, function(expr) {
var argument = self.nextId();
self.recurse(expr, argument);
args.push(argument);
});
expression = right + '(' + args.join(',') + ')';
self.assign(intoId, expression);
recursionFn(intoId);
} else {
right = self.nextId();
left = {};
args = [];
self.recurse(ast.callee, right, left, function() {
self.if_(self.notNull(right), function() {
self.addEnsureSafeFunction(right);
forEach(ast.arguments, function(expr) {
self.recurse(expr, self.nextId(), undefined, function(argument) {
args.push(self.ensureSafeObject(argument));
});
});
if (left.name) {
if (!self.state.expensiveChecks) {
self.addEnsureSafeObject(left.context);
}
expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
} else {
expression = right + '(' + args.join(',') + ')';
}
expression = self.ensureSafeObject(expression);
self.assign(intoId, expression);
}, function() {
self.assign(intoId, 'undefined');
});
recursionFn(intoId);
});
}
break;
case AST.AssignmentExpression:
right = this.nextId();
left = {};
if (!isAssignable(ast.left)) {
throw $parseMinErr('lval', 'Trying to assign a value to a non l-value');
}
this.recurse(ast.left, undefined, left, function() {
self.if_(self.notNull(left.context), function() {
self.recurse(ast.right, right);
self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
self.addEnsureSafeAssignContext(left.context);
expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
self.assign(intoId, expression);
recursionFn(intoId || expression);
});
}, 1);
break;
case AST.ArrayExpression:
args = [];
forEach(ast.elements, function(expr) {
self.recurse(expr, self.nextId(), undefined, function(argument) {
args.push(argument);
});
});
expression = '[' + args.join(',') + ']';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.ObjectExpression:
args = [];
forEach(ast.properties, function(property) {
self.recurse(property.value, self.nextId(), undefined, function(expr) {
args.push(self.escape(
property.key.type === AST.Identifier ? property.key.name :
('' + property.key.value)) +
':' + expr);
});
});
expression = '{' + args.join(',') + '}';
this.assign(intoId, expression);
recursionFn(expression);
break;
case AST.ThisExpression:
this.assign(intoId, 's');
recursionFn('s');
break;
case AST.LocalsExpression:
this.assign(intoId, 'l');
recursionFn('l');
break;
case AST.NGValueParameter:
this.assign(intoId, 'v');
recursionFn('v');
break;
}
},
getHasOwnProperty: function(element, property) {
var key = element + '.' + property;
var own = this.current().own;
if (!own.hasOwnProperty(key)) {
own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
}
return own[key];
},
assign: function(id, value) {
if (!id) return;
this.current().body.push(id, '=', value, ';');
return id;
},
filter: function(filterName) {
if (!this.state.filters.hasOwnProperty(filterName)) {
this.state.filters[filterName] = this.nextId(true);
}
return this.state.filters[filterName];
},
ifDefined: function(id, defaultValue) {
return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
},
plus: function(left, right) {
return 'plus(' + left + ',' + right + ')';
},
return_: function(id) {
this.current().body.push('return ', id, ';');
},
if_: function(test, alternate, consequent) {
if (test === true) {
alternate();
} else {
var body = this.current().body;
body.push('if(', test, '){');
alternate();
body.push('}');
if (consequent) {
body.push('else{');
consequent();
body.push('}');
}
}
},
not: function(expression) {
return '!(' + expression + ')';
},
notNull: function(expression) {
return expression + '!=null';
},
nonComputedMember: function(left, right) {
return left + '.' + right;
},
computedMember: function(left, right) {
return left + '[' + right + ']';
},
member: function(left, right, computed) {
if (computed) return this.computedMember(left, right);
return this.nonComputedMember(left, right);
},
addEnsureSafeObject: function(item) {
this.current().body.push(this.ensureSafeObject(item), ';');
},
addEnsureSafeMemberName: function(item) {
this.current().body.push(this.ensureSafeMemberName(item), ';');
},
addEnsureSafeFunction: function(item) {
this.current().body.push(this.ensureSafeFunction(item), ';');
},
addEnsureSafeAssignContext: function(item) {
this.current().body.push(this.ensureSafeAssignContext(item), ';');
},
ensureSafeObject: function(item) {
return 'ensureSafeObject(' + item + ',text)';
},
ensureSafeMemberName: function(item) {
return 'ensureSafeMemberName(' + item + ',text)';
},
ensureSafeFunction: function(item) {
return 'ensureSafeFunction(' + item + ',text)';
},
getStringValue: function(item) {
this.assign(item, 'getStringValue(' + item + ')');
},
ensureSafeAssignContext: function(item) {
return 'ensureSafeAssignContext(' + item + ',text)';
},
lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
var self = this;
return function() {
self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
};
},
lazyAssign: function(id, value) {
var self = this;
return function() {
self.assign(id, value);
};
},
stringEscapeRegex: /[^ a-zA-Z0-9]/g,
stringEscapeFn: function(c) {
return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
},
escape: function(value) {
if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
if (isNumber(value)) return value.toString();
if (value === true) return 'true';
if (value === false) return 'false';
if (value === null) return 'null';
if (typeof value === 'undefined') return 'undefined';
throw $parseMinErr('esc', 'IMPOSSIBLE');
},
nextId: function(skip, init) {
var id = 'v' + (this.state.nextId++);
if (!skip) {
this.current().vars.push(id + (init ? '=' + init : ''));
}
return id;
},
current: function() {
return this.state[this.state.computing];
}
};
function ASTInterpreter(astBuilder, $filter) {
this.astBuilder = astBuilder;
this.$filter = $filter;
}
ASTInterpreter.prototype = {
compile: function(expression, expensiveChecks) {
var self = this;
var ast = this.astBuilder.ast(expression);
this.expression = expression;
this.expensiveChecks = expensiveChecks;
findConstantAndWatchExpressions(ast, self.$filter);
var assignable;
var assign;
if ((assignable = assignableAST(ast))) {
assign = this.recurse(assignable);
}
var toWatch = getInputs(ast.body);
var inputs;
if (toWatch) {
inputs = [];
forEach(toWatch, function(watch, key) {
var input = self.recurse(watch);
watch.input = input;
inputs.push(input);
watch.watchId = key;
});
}
var expressions = [];
forEach(ast.body, function(expression) {
expressions.push(self.recurse(expression.expression));
});
var fn = ast.body.length === 0 ? function() {} :
ast.body.length === 1 ? expressions[0] :
function(scope, locals) {
var lastValue;
forEach(expressions, function(exp) {
lastValue = exp(scope, locals);
});
return lastValue;
};
if (assign) {
fn.assign = function(scope, value, locals) {
return assign(scope, locals, value);
};
}
if (inputs) {
fn.inputs = inputs;
}
fn.literal = isLiteral(ast);
fn.constant = isConstant(ast);
return fn;
},
recurse: function(ast, context, create) {
var left, right, self = this, args, expression;
if (ast.input) {
return this.inputs(ast.input, ast.watchId);
}
switch (ast.type) {
case AST.Literal:
return this.value(ast.value, context);
case AST.UnaryExpression:
right = this.recurse(ast.argument);
return this['unary' + ast.operator](right, context);
case AST.BinaryExpression:
left = this.recurse(ast.left);
right = this.recurse(ast.right);
return this['binary' + ast.operator](left, right, context);
case AST.LogicalExpression:
left = this.recurse(ast.left);
right = this.recurse(ast.right);
return this['binary' + ast.operator](left, right, context);
case AST.ConditionalExpression:
return this['ternary?:'](
this.recurse(ast.test),
this.recurse(ast.alternate),
this.recurse(ast.consequent),
context
);
case AST.Identifier:
ensureSafeMemberName(ast.name, self.expression);
return self.identifier(ast.name,
self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
context, create, self.expression);
case AST.MemberExpression:
left = this.recurse(ast.object, false, !!create);
if (!ast.computed) {
ensureSafeMemberName(ast.property.name, self.expression);
right = ast.property.name;
}
if (ast.computed) right = this.recurse(ast.property);
return ast.computed ?
this.computedMember(left, right, context, create, self.expression) :
this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
case AST.CallExpression:
args = [];
forEach(ast.arguments, function(expr) {
args.push(self.recurse(expr));
});
if (ast.filter) right = this.$filter(ast.callee.name);
if (!ast.filter) right = this.recurse(ast.callee, true);
return ast.filter ?
function(scope, locals, assign, inputs) {
var values = [];
for (var i = 0; i < args.length; ++i) {
values.push(args[i](scope, locals, assign, inputs));
}
var value = right.apply(undefined, values, inputs);
return context ? {context: undefined, name: undefined, value: value} : value;
} :
function(scope, locals, assign, inputs) {
var rhs = right(scope, locals, assign, inputs);
var value;
if (rhs.value != null) {
ensureSafeObject(rhs.context, self.expression);
ensureSafeFunction(rhs.value, self.expression);
var values = [];
for (var i = 0; i < args.length; ++i) {
values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
}
value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
}
return context ? {value: value} : value;
};
case AST.AssignmentExpression:
left = this.recurse(ast.left, true, 1);
right = this.recurse(ast.right);
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
ensureSafeObject(lhs.value, self.expression);
ensureSafeAssignContext(lhs.context);
lhs.context[lhs.name] = rhs;
return context ? {value: rhs} : rhs;
};
case AST.ArrayExpression:
args = [];
forEach(ast.elements, function(expr) {
args.push(self.recurse(expr));
});
return function(scope, locals, assign, inputs) {
var value = [];
for (var i = 0; i < args.length; ++i) {
value.push(args[i](scope, locals, assign, inputs));
}
return context ? {value: value} : value;
};
case AST.ObjectExpression:
args = [];
forEach(ast.properties, function(property) {
args.push({key: property.key.type === AST.Identifier ?
property.key.name :
('' + property.key.value),
value: self.recurse(property.value)
});
});
return function(scope, locals, assign, inputs) {
var value = {};
for (var i = 0; i < args.length; ++i) {
value[args[i].key] = args[i].value(scope, locals, assign, inputs);
}
return context ? {value: value} : value;
};
case AST.ThisExpression:
return function(scope) {
return context ? {value: scope} : scope;
};
case AST.LocalsExpression:
return function(scope, locals) {
return context ? {value: locals} : locals;
};
case AST.NGValueParameter:
return function(scope, locals, assign, inputs) {
return context ? {value: assign} : assign;
};
}
},
'unary+': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = argument(scope, locals, assign, inputs);
if (isDefined(arg)) {
arg = +arg;
} else {
arg = 0;
}
return context ? {value: arg} : arg;
};
},
'unary-': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = argument(scope, locals, assign, inputs);
if (isDefined(arg)) {
arg = -arg;
} else {
arg = 0;
}
return context ? {value: arg} : arg;
};
},
'unary!': function(argument, context) {
return function(scope, locals, assign, inputs) {
var arg = !argument(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary+': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
var arg = plusFn(lhs, rhs);
return context ? {value: arg} : arg;
};
},
'binary-': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs = right(scope, locals, assign, inputs);
var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
return context ? {value: arg} : arg;
};
},
'binary*': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary/': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary%': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary===': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary!==': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary==': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary!=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary<': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary>': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary<=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary>=': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary&&': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'binary||': function(left, right, context) {
return function(scope, locals, assign, inputs) {
var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
'ternary?:': function(test, alternate, consequent, context) {
return function(scope, locals, assign, inputs) {
var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
return context ? {value: arg} : arg;
};
},
value: function(value, context) {
return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
},
identifier: function(name, expensiveChecks, context, create, expression) {
return function(scope, locals, assign, inputs) {
var base = locals && (name in locals) ? locals : scope;
if (create && create !== 1 && base && !(base[name])) {
base[name] = {};
}
var value = base ? base[name] : undefined;
if (expensiveChecks) {
ensureSafeObject(value, expression);
}
if (context) {
return {context: base, name: name, value: value};
} else {
return value;
}
};
},
computedMember: function(left, right, context, create, expression) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
var rhs;
var value;
if (lhs != null) {
rhs = right(scope, locals, assign, inputs);
rhs = getStringValue(rhs);
ensureSafeMemberName(rhs, expression);
if (create && create !== 1) {
ensureSafeAssignContext(lhs);
if (lhs && !(lhs[rhs])) {
lhs[rhs] = {};
}
}
value = lhs[rhs];
ensureSafeObject(value, expression);
}
if (context) {
return {context: lhs, name: rhs, value: value};
} else {
return value;
}
};
},
nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
return function(scope, locals, assign, inputs) {
var lhs = left(scope, locals, assign, inputs);
if (create && create !== 1) {
ensureSafeAssignContext(lhs);
if (lhs && !(lhs[right])) {
lhs[right] = {};
}
}
var value = lhs != null ? lhs[right] : undefined;
if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
ensureSafeObject(value, expression);
}
if (context) {
return {context: lhs, name: right, value: value};
} else {
return value;
}
};
},
inputs: function(input, watchId) {
return function(scope, value, locals, inputs) {
if (inputs) return inputs[watchId];
return input(scope, value, locals);
};
}
};
/**
* @constructor
*/
var Parser = function(lexer, $filter, options) {
this.lexer = lexer;
this.$filter = $filter;
this.options = options;
this.ast = new AST(this.lexer);
this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
new ASTCompiler(this.ast, $filter);
};
Parser.prototype = {
constructor: Parser,
parse: function(text) {
return this.astCompiler.compile(text, this.options.expensiveChecks);
}
};
function isPossiblyDangerousMemberName(name) {
return name == 'constructor';
}
var objectValueOf = Object.prototype.valueOf;
function getValueOf(value) {
return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
}
///////////////////////////////////
/**
* @ngdoc service
* @name $parse
* @kind function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* ```js
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* ```
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The returned function also has the following properties:
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
* literal.
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
* constant literals.
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
* set to a function to change its value on the given context.
*
*/
/**
* @ngdoc provider
* @name $parseProvider
*
* @description
* `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
* service.
*/
function $ParseProvider() {
var cacheDefault = createMap();
var cacheExpensive = createMap();
this.$get = ['$filter', function($filter) {
var noUnsafeEval = csp().noUnsafeEval;
var $parseOptions = {
csp: noUnsafeEval,
expensiveChecks: false
},
$parseOptionsExpensive = {
csp: noUnsafeEval,
expensiveChecks: true
};
return function $parse(exp, interceptorFn, expensiveChecks) {
var parsedExpression, oneTime, cacheKey;
switch (typeof exp) {
case 'string':
exp = exp.trim();
cacheKey = exp;
var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
parsedExpression = cache[cacheKey];
if (!parsedExpression) {
if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
oneTime = true;
exp = exp.substring(2);
}
var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
var lexer = new Lexer(parseOptions);
var parser = new Parser(lexer, $filter, parseOptions);
parsedExpression = parser.parse(exp);
if (parsedExpression.constant) {
parsedExpression.$$watchDelegate = constantWatchDelegate;
} else if (oneTime) {
parsedExpression.$$watchDelegate = parsedExpression.literal ?
oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
} else if (parsedExpression.inputs) {
parsedExpression.$$watchDelegate = inputsWatchDelegate;
}
cache[cacheKey] = parsedExpression;
}
return addInterceptor(parsedExpression, interceptorFn);
case 'function':
return addInterceptor(exp, interceptorFn);
default:
return addInterceptor(noop, interceptorFn);
}
};
function expressionInputDirtyCheck(newValue, oldValueOfValue) {
if (newValue == null || oldValueOfValue == null) { // null/undefined
return newValue === oldValueOfValue;
}
if (typeof newValue === 'object') {
// attempt to convert the value to a primitive type
// TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
// be cheaply dirty-checked
newValue = getValueOf(newValue);
if (typeof newValue === 'object') {
// objects/arrays are not supported - deep-watching them would be too expensive
return false;
}
// fall-through to the primitive equality check
}
//Primitive or NaN
return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
}
function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
var inputExpressions = parsedExpression.inputs;
var lastResult;
if (inputExpressions.length === 1) {
var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
inputExpressions = inputExpressions[0];
return scope.$watch(function expressionInputWatch(scope) {
var newInputValue = inputExpressions(scope);
if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
oldInputValueOf = newInputValue && getValueOf(newInputValue);
}
return lastResult;
}, listener, objectEquality, prettyPrintExpression);
}
var oldInputValueOfValues = [];
var oldInputValues = [];
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
oldInputValues[i] = null;
}
return scope.$watch(function expressionInputsWatch(scope) {
var changed = false;
for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
var newInputValue = inputExpressions[i](scope);
if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
oldInputValues[i] = newInputValue;
oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
}
}
if (changed) {
lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
}
return lastResult;
}, listener, objectEquality, prettyPrintExpression);
}
function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener.apply(this, arguments);
}
if (isDefined(value)) {
scope.$$postDigest(function() {
if (isDefined(lastValue)) {
unwatch();
}
});
}
}, objectEquality);
}
function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch, lastValue;
return unwatch = scope.$watch(function oneTimeWatch(scope) {
return parsedExpression(scope);
}, function oneTimeListener(value, old, scope) {
lastValue = value;
if (isFunction(listener)) {
listener.call(this, value, old, scope);
}
if (isAllDefined(value)) {
scope.$$postDigest(function() {
if (isAllDefined(lastValue)) unwatch();
});
}
}, objectEquality);
function isAllDefined(value) {
var allDefined = true;
forEach(value, function(val) {
if (!isDefined(val)) allDefined = false;
});
return allDefined;
}
}
function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
var unwatch;
return unwatch = scope.$watch(function constantWatch(scope) {
unwatch();
return parsedExpression(scope);
}, listener, objectEquality);
}
function addInterceptor(parsedExpression, interceptorFn) {
if (!interceptorFn) return parsedExpression;
var watchDelegate = parsedExpression.$$watchDelegate;
var useInputs = false;
var regularWatch =
watchDelegate !== oneTimeLiteralWatchDelegate &&
watchDelegate !== oneTimeWatchDelegate;
var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
return interceptorFn(value, scope, locals);
} : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
var value = parsedExpression(scope, locals, assign, inputs);
var result = interceptorFn(value, scope, locals);
// we only return the interceptor's result if the
// initial value is defined (for bind-once)
return isDefined(value) ? result : value;
};
// Propagate $$watchDelegates other then inputsWatchDelegate
if (parsedExpression.$$watchDelegate &&
parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
fn.$$watchDelegate = parsedExpression.$$watchDelegate;
} else if (!interceptorFn.$stateful) {
// If there is an interceptor, but no watchDelegate then treat the interceptor like
// we treat filters - it is assumed to be a pure function unless flagged with $stateful
fn.$$watchDelegate = inputsWatchDelegate;
useInputs = !parsedExpression.inputs;
fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
}
return fn;
}
}];
}
| {'content_hash': 'af451d8e68e31edea0823f78b72a21f4', 'timestamp': '', 'source': 'github', 'line_count': 1956, 'max_line_length': 154, 'avg_line_length': 33.08742331288344, 'alnum_prop': 0.5909238399851666, 'repo_name': 'riczat/anglar', 'id': 'cddde467bc59720bdcc1e2bebc46edbb46be79da', 'size': '64739', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'angularjs/src/ng/parse.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '519'}, {'name': 'CSS', 'bytes': '72'}, {'name': 'HTML', 'bytes': '78285'}, {'name': 'JavaScript', 'bytes': '9471626'}, {'name': 'PHP', 'bytes': '218982'}, {'name': 'PostScript', 'bytes': '19551'}, {'name': 'Shell', 'bytes': '20442'}, {'name': 'TypeScript', 'bytes': '2057'}]} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.raiz.rest;
import com.raiz.entidades.Empleado;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Usuario
*/
public class MantenimientoRestTest {
public MantenimientoRestTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
//@Test
public void testInsertEmpleado() {
System.out.println("insertEmpleado");
Empleado empleado = null;
MantenimientoRest instance = new MantenimientoRest();
String expResult = "";
Integer result = instance.insertEmpleado(empleado);
assertEquals(expResult, result);
}
@Test
public void testGetEmpleados() {
System.out.println("getEmpleados");
MantenimientoRest instance = new MantenimientoRest();
List<Empleado> expResult = null;
List<Empleado> result = instance.getEmpleados();
//assertEquals(expResult, result);
}
//@Test
public void testFindEmpleado() {
System.out.println("findEmpleado");
Integer id = null;
MantenimientoRest instance = new MantenimientoRest();
Empleado expResult = null;
Empleado result = instance.findEmpleado(id);
assertEquals(expResult, result);
}
//@Test
public void testEditEmpleado() {
System.out.println("editEmpleado");
Integer id = null;
Empleado empleado = null;
MantenimientoRest instance = new MantenimientoRest();
String expResult = "";
String result = instance.editEmpleado(id, empleado);
assertEquals(expResult, result);
}
//@Test
public void testDeleteEmpleado() {
System.out.println("deleteEmpleado");
Integer id = null;
MantenimientoRest instance = new MantenimientoRest();
String expResult = "";
String result = instance.deleteEmpleado(id);
assertEquals(expResult, result);
}
}
| {'content_hash': 'a951d7caecdc9e3a434c5c6ad64a9606', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 79, 'avg_line_length': 27.25, 'alnum_prop': 0.6182688472277623, 'repo_name': 'Cajami/DSD_ProyectoFinal_RaizCTS', 'id': '3211c334c4a87510f05ce1c646788d396c5296a6', 'size': '2507', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/com/raiz/rest/MantenimientoRestTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '192690'}, {'name': 'HTML', 'bytes': '81152'}, {'name': 'Java', 'bytes': '145894'}, {'name': 'JavaScript', 'bytes': '792296'}]} |
ALTER TABLE page_lang ADD `online` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '1';
ALTER TABLE page ADD `group_FK` SMALLINT( 4 ) UNSIGNED NOT NULL;
ALTER TABLE article ADD `id_type` INT( 11 ) UNSIGNED NULL ;
CREATE TABLE IF NOT EXISTS article_type (
id_type int(11) unsigned NOT NULL auto_increment,
type varchar(50) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (id_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS extend_field (
id_extend_field INT(11) UNSIGNED NOT NULL auto_increment,
name varchar(255) NOT NULL,
label varchar(255) NOT NULL,
type varchar(1) NOT NULL,
description varchar(2000) DEFAULT '',
parent varchar(50) NOT NULL,
ordering int(11) default 0,
translated char(1) default '0',
PRIMARY KEY (id_extend_field),
KEY i_extend_field_parent (parent)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS extend_fields (
id_extend_fields INT(11) UNSIGNED NOT NULL auto_increment,
id_extend_field INT(11) UNSIGNED NOT NULL,
id_parent int(11) UNSIGNED NOT NULL,
lang char(3) NOT NULL default '',
content text,
PRIMARY KEY (id_extend_fields),
KEY i_extend_fields_lang (lang)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;
| {'content_hash': '0bc9c7486a0e49385d34df9aa06b4ec0', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 79, 'avg_line_length': 37.48571428571429, 'alnum_prop': 0.7461890243902439, 'repo_name': 'smirfolio/rebal', 'id': 'a4d697421b3c04bfbcd793df75b2b9fc162b4021', 'size': '1385', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'install545d4d4d/database/migration_0.90_0.92.sql', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1760275'}, {'name': 'PHP', 'bytes': '4716634'}]} |
export { default } from './Stepper';
export { default as stepperClasses } from './stepperClasses';
export * from './stepperClasses';
export { default as StepperContext } from './StepperContext';
export * from './StepperContext';
| {'content_hash': 'cf1c44b33249dfd1bdc63a767d3f36f0', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 61, 'avg_line_length': 33.0, 'alnum_prop': 0.7186147186147186, 'repo_name': 'mui-org/material-ui', 'id': '550f0b648ad7e081066cb7605553d14500730d80', 'size': '231', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'packages/mui-material/src/Stepper/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2126'}, {'name': 'JavaScript', 'bytes': '4120512'}, {'name': 'TypeScript', 'bytes': '3263233'}]} |
/**
* @author Anas Nashif
*/
#ifdef HAVE_CONFIG_H
#include "wsman_config.h"
#endif
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include "ctype.h"
#include "u/libu.h"
#include "wsman-xml-api.h"
#include "wsman-soap.h"
#include "wsman-xml-serializer.h"
#include "wsman-dispatcher.h"
#include "identify.h"
wsmid_identify g_wsmid_identify = { XML_NS_WS_MAN, "Openwsman Project" , PACKAGE_VERSION };
wsmid_identify* wsmid_identify_Identify_EP(WsContextH cntx)
{
wsmid_identify *buf = u_malloc(sizeof(wsmid_identify));
memcpy(buf, &g_wsmid_identify, sizeof(wsmid_identify));
return buf;
}
| {'content_hash': '9fde1fca0385f3b1584fd3e9a046bf16', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 92, 'avg_line_length': 17.685714285714287, 'alnum_prop': 0.7011308562197092, 'repo_name': 'vcrhonek/openwsman', 'id': '435ed69780fd8c5e8035e4b27a6b8c5103f1e518', 'size': '2318', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/plugins/identify/identify_stubs.c', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '1533878'}, {'name': 'C++', 'bytes': '48257'}, {'name': 'CMake', 'bytes': '93106'}, {'name': 'Java', 'bytes': '14182'}, {'name': 'M4', 'bytes': '28034'}, {'name': 'Makefile', 'bytes': '17976'}, {'name': 'Perl', 'bytes': '22452'}, {'name': 'Python', 'bytes': '14690'}, {'name': 'Ruby', 'bytes': '142704'}, {'name': 'SWIG', 'bytes': '116571'}, {'name': 'Shell', 'bytes': '9814'}]} |
package org.apache.archiva.rest.services;
import org.apache.archiva.admin.model.RepositoryAdminException;
import org.apache.archiva.admin.model.admin.ArchivaAdministration;
import org.apache.archiva.checksum.ChecksumAlgorithm;
import org.apache.archiva.checksum.ChecksummedFile;
import org.apache.archiva.common.utils.VersionComparator;
import org.apache.archiva.common.utils.VersionUtil;
import org.apache.archiva.components.cache.Cache;
import org.apache.archiva.components.taskqueue.TaskQueueException;
import org.apache.archiva.maven.model.Artifact;
import org.apache.archiva.metadata.audit.RepositoryListener;
import org.apache.archiva.maven.metadata.model.MavenArtifactFacet;
import org.apache.archiva.metadata.model.ArtifactMetadata;
import org.apache.archiva.metadata.model.facets.AuditEvent;
import org.apache.archiva.metadata.repository.MetadataRepository;
import org.apache.archiva.metadata.repository.MetadataRepositoryException;
import org.apache.archiva.metadata.repository.MetadataResolutionException;
import org.apache.archiva.metadata.repository.MetadataSessionException;
import org.apache.archiva.metadata.repository.RepositorySession;
import org.apache.archiva.metadata.repository.RepositorySessionFactory;
import org.apache.archiva.model.ArchivaRepositoryMetadata;
import org.apache.archiva.redback.authentication.AuthenticationResult;
import org.apache.archiva.redback.authorization.AuthorizationException;
import org.apache.archiva.redback.system.DefaultSecuritySession;
import org.apache.archiva.redback.system.SecuritySession;
import org.apache.archiva.redback.system.SecuritySystem;
import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManagerException;
import org.apache.archiva.redback.users.UserNotFoundException;
import org.apache.archiva.repository.base.group.RepositoryGroupHandler;
import org.apache.archiva.repository.content.BaseRepositoryContentLayout;
import org.apache.archiva.repository.content.ContentNotFoundException;
import org.apache.archiva.repository.content.LayoutException;
import org.apache.archiva.repository.ManagedRepository;
import org.apache.archiva.repository.ManagedRepositoryContent;
import org.apache.archiva.repository.RepositoryException;
import org.apache.archiva.repository.RepositoryNotFoundException;
import org.apache.archiva.repository.RepositoryRegistry;
import org.apache.archiva.repository.RepositoryType;
import org.apache.archiva.repository.content.ContentItem;
import org.apache.archiva.repository.content.ItemNotFoundException;
import org.apache.archiva.repository.content.ItemSelector;
import org.apache.archiva.repository.content.Version;
import org.apache.archiva.repository.content.base.ArchivaItemSelector;
import org.apache.archiva.repository.metadata.RepositoryMetadataException;
import org.apache.archiva.repository.metadata.base.MetadataTools;
import org.apache.archiva.repository.metadata.base.RepositoryMetadataWriter;
import org.apache.archiva.repository.scanner.RepositoryScanStatistics;
import org.apache.archiva.repository.scanner.RepositoryScanner;
import org.apache.archiva.repository.scanner.RepositoryScannerException;
import org.apache.archiva.repository.scanner.RepositoryScannerInstance;
import org.apache.archiva.repository.storage.RepositoryStorage;
import org.apache.archiva.repository.storage.StorageAsset;
import org.apache.archiva.repository.storage.fs.FsStorageUtil;
import org.apache.archiva.rest.api.model.ActionStatus;
import org.apache.archiva.rest.api.model.ArtifactTransferRequest;
import org.apache.archiva.rest.api.model.PermissionStatus;
import org.apache.archiva.rest.api.model.ScanStatus;
import org.apache.archiva.rest.api.model.StringList;
import org.apache.archiva.rest.api.services.ArchivaRestServiceException;
import org.apache.archiva.rest.api.services.RepositoriesService;
import org.apache.archiva.scheduler.ArchivaTaskScheduler;
import org.apache.archiva.scheduler.indexing.ArtifactIndexingTask;
import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexException;
import org.apache.archiva.scheduler.indexing.DownloadRemoteIndexScheduler;
import org.apache.archiva.maven.scheduler.indexing.ArchivaIndexingTaskExecutor;
import org.apache.archiva.scheduler.repository.model.RepositoryTask;
import org.apache.archiva.security.ArchivaSecurityException;
import org.apache.archiva.security.common.ArchivaRoleConstants;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Path;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
/**
* @author Olivier Lamy
* @since 1.4-M1
*/
@Service("repositoriesService#rest")
public class DefaultRepositoriesService
extends AbstractRestService
implements RepositoriesService
{
private Logger log = LoggerFactory.getLogger( getClass() );
@Inject
@Named(value = "taskExecutor#indexing")
private ArchivaIndexingTaskExecutor archivaIndexingTaskExecutor;
@Inject
private RepositoryRegistry repositoryRegistry;
@SuppressWarnings( "unused" )
@Inject
private RepositoryGroupHandler repositoryGroupHandler;
@Inject
private SecuritySystem securitySystem;
@Inject
@Named(value = "archivaTaskScheduler#repository")
private ArchivaTaskScheduler<RepositoryTask> scheduler;
@Inject
private DownloadRemoteIndexScheduler downloadRemoteIndexScheduler;
@Inject
@Named(value = "repositorySessionFactory")
protected RepositorySessionFactory repositorySessionFactory;
@Inject
@Autowired(required = false)
protected List<RepositoryListener> listeners = new ArrayList<RepositoryListener>();
@Inject
private RepositoryScanner repoScanner;
/**
* Cache used for namespaces
*/
@Inject
@Named(value = "cache#namespaces")
private Cache<String, List<String>> namespacesCache;
private List<ChecksumAlgorithm> algorithms = Arrays.asList(ChecksumAlgorithm.SHA256, ChecksumAlgorithm.SHA1, ChecksumAlgorithm.MD5 );
@Override
public ActionStatus scanRepository( String repositoryId, boolean fullScan )
{
return new ActionStatus( doScanRepository( repositoryId, fullScan ) );
}
@Override
public ScanStatus getScanStatus( String repositoryId )
{
// check queue first to make sure it doesn't get dequeued between calls
if ( repositoryTaskScheduler.isProcessingRepositoryTask( repositoryId ) )
{
return new ScanStatus( true );
}
for ( RepositoryScannerInstance scan : repoScanner.getInProgressScans() )
{
if ( scan.getRepository().getId().equals( repositoryId ) )
{
return new ScanStatus( true );
}
}
return new ScanStatus( false );
}
@Override
public ActionStatus removeScanningTaskFromQueue( String repositoryId )
{
RepositoryTask task = new RepositoryTask();
task.setRepositoryId( repositoryId );
try
{
return new ActionStatus( repositoryTaskScheduler.unQueueTask( task ) );
}
catch ( TaskQueueException e )
{
log.error( "failed to unschedule scanning of repo with id {}", repositoryId, e );
return ActionStatus.FAIL;
}
}
private ManagedRepositoryContent getManagedRepositoryContent( String id) throws RepositoryException
{
org.apache.archiva.repository.ManagedRepository repo = repositoryRegistry.getManagedRepository( id );
if (repo==null) {
throw new RepositoryException( "Repository not found "+id );
}
return repo.getContent();
}
@Override
public ActionStatus scanRepositoryNow( String repositoryId, boolean fullScan )
throws ArchivaRestServiceException
{
try
{
org.apache.archiva.repository.ManagedRepository repository = repositoryRegistry.getManagedRepository( repositoryId );
ArtifactIndexingTask task =
new ArtifactIndexingTask( repository, null, ArtifactIndexingTask.Action.FINISH, repository.getIndexingContext() );
task.setExecuteOnEntireRepo( true );
task.setOnlyUpdate( !fullScan );
archivaIndexingTaskExecutor.executeTask( task );
scheduler.queueTask( new RepositoryTask( repositoryId, fullScan ) );
return ActionStatus.SUCCESS;
}
catch ( Exception e )
{
log.error( e.getMessage(), e );
throw new ArchivaRestServiceException( e.getMessage(), e );
}
}
@Override
public ActionStatus scheduleDownloadRemoteIndex( String repositoryId, boolean now, boolean fullDownload )
throws ArchivaRestServiceException
{
try
{
downloadRemoteIndexScheduler.scheduleDownloadRemote( repositoryId, now, fullDownload );
}
catch ( DownloadRemoteIndexException e )
{
log.error( e.getMessage(), e );
throw new ArchivaRestServiceException( e.getMessage(), e );
}
return ActionStatus.SUCCESS;
}
@Override
public ActionStatus copyArtifact( ArtifactTransferRequest artifactTransferRequest )
throws ArchivaRestServiceException
{
// check parameters
String userName = getAuditInformation().getUser().getUsername();
if ( StringUtils.isBlank( userName ) )
{
throw new ArchivaRestServiceException( "copyArtifact call: userName not found", null );
}
if ( StringUtils.isBlank( artifactTransferRequest.getRepositoryId() ) )
{
throw new ArchivaRestServiceException( "copyArtifact call: sourceRepositoryId cannot be null", null );
}
if ( StringUtils.isBlank( artifactTransferRequest.getTargetRepositoryId() ) )
{
throw new ArchivaRestServiceException( "copyArtifact call: targetRepositoryId cannot be null", null );
}
ManagedRepository source = null;
source = repositoryRegistry.getManagedRepository( artifactTransferRequest.getRepositoryId() );
if ( source == null )
{
throw new ArchivaRestServiceException(
"cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null );
}
ManagedRepository target = null;
target = repositoryRegistry.getManagedRepository( artifactTransferRequest.getTargetRepositoryId() );
if ( target == null )
{
throw new ArchivaRestServiceException(
"cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null );
}
if ( StringUtils.isBlank( artifactTransferRequest.getGroupId() ) )
{
throw new ArchivaRestServiceException( "groupId is mandatory", null );
}
if ( StringUtils.isBlank( artifactTransferRequest.getArtifactId() ) )
{
throw new ArchivaRestServiceException( "artifactId is mandatory", null );
}
if ( StringUtils.isBlank( artifactTransferRequest.getVersion() ) )
{
throw new ArchivaRestServiceException( "version is mandatory", null );
}
if ( VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
{
throw new ArchivaRestServiceException( "copy of SNAPSHOT not supported", null );
}
// end check parameters
User user = null;
try
{
user = securitySystem.getUserManager().findUser( userName );
}
catch ( UserNotFoundException e )
{
throw new ArchivaRestServiceException( "user " + userName + " not found", e );
}
catch ( UserManagerException e )
{
throw new ArchivaRestServiceException( "ArchivaRestServiceException:" + e.getMessage(), e );
}
// check karma on source : read
AuthenticationResult authn = new AuthenticationResult( true, userName, null );
SecuritySession securitySession = new DefaultSecuritySession( authn, user );
try
{
boolean authz =
securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_READ_REPOSITORY,
artifactTransferRequest.getRepositoryId() );
if ( !authz )
{
throw new ArchivaRestServiceException(
"not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null );
}
}
catch ( AuthorizationException e )
{
log.error( "error reading permission: {}", e.getMessage(), e );
throw new ArchivaRestServiceException( e.getMessage(), e );
}
// check karma on target: write
try
{
boolean authz =
securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_ADD_ARTIFACT,
artifactTransferRequest.getTargetRepositoryId() );
if ( !authz )
{
throw new ArchivaRestServiceException(
"not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null );
}
}
catch ( AuthorizationException e )
{
log.error( "error reading permission: {}", e.getMessage(), e );
throw new ArchivaRestServiceException( e.getMessage(), e );
}
// sounds good we can continue !
String packaging = StringUtils.trim( artifactTransferRequest.getPackaging() );
ItemSelector selector = ArchivaItemSelector.builder( )
.withProjectId( artifactTransferRequest.getArtifactId( ) )
.withArtifactId( artifactTransferRequest.getArtifactId( ) )
.withNamespace( artifactTransferRequest.getGroupId( ) )
.withArtifactVersion( artifactTransferRequest.getVersion( ) )
.withClassifier( artifactTransferRequest.getClassifier( ) )
.withExtension( StringUtils.isEmpty( packaging ) ? "jar" : packaging )
.build( );
try
{
ManagedRepositoryContent sourceRepository =
getManagedRepositoryContent( artifactTransferRequest.getRepositoryId() );
BaseRepositoryContentLayout layout = sourceRepository.getLayout( BaseRepositoryContentLayout.class );
// String artifactSourcePath = sourceRepository.toPath( selector );
org.apache.archiva.repository.content.Artifact sourceArtifact = layout.getArtifact( selector );
if ( !sourceArtifact.exists() )
{
log.error( "cannot find artifact {}", artifactTransferRequest );
throw new ArchivaRestServiceException( "cannot find artifact " + artifactTransferRequest.toString(),
null );
}
StorageAsset artifactFile = sourceArtifact.getAsset( );
ManagedRepositoryContent targetRepository =
getManagedRepositoryContent( artifactTransferRequest.getTargetRepositoryId() );
String artifactPath = artifactFile.getPath( );
int lastIndex = artifactPath.lastIndexOf( '/' );
String path = artifactPath.substring( 0, lastIndex );
StorageAsset targetDir = target.getAsset( path );
Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
int newBuildNumber = 1;
String timestamp = null;
StorageAsset versionMetadataFile = target.getAsset(path + "/" + MetadataTools.MAVEN_METADATA );
/* unused */ getMetadata( targetRepository.getRepository().getType(), versionMetadataFile );
if ( !targetDir.exists() )
{
targetDir = target.addAsset(targetDir.getPath(), true);
targetDir.create();
}
String filename = artifactPath.substring( lastIndex + 1 );
boolean fixChecksums =
!( archivaAdministration.getKnownContentConsumers().contains( "create-missing-checksums" ) );
StorageAsset targetFile = target.getAsset(targetDir.getPath() + "/" + filename );
if ( targetFile.exists() && target.blocksRedeployments())
{
throw new ArchivaRestServiceException(
"artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId()
+ " and redeployment blocked", null
);
}
else
{
copyFile(artifactFile, targetFile, fixChecksums );
queueRepositoryTask( target.getId(), targetFile );
}
// copy source pom to target repo
String pomFilename = filename;
if ( StringUtils.isNotBlank( artifactTransferRequest.getClassifier() ) )
{
pomFilename = StringUtils.remove( pomFilename, "-" + artifactTransferRequest.getClassifier() );
}
pomFilename = FilenameUtils.removeExtension( pomFilename ) + ".pom";
StorageAsset pomFile = source.getAsset(
artifactPath.substring( 0, artifactPath.lastIndexOf( '/' ) )+"/"+ pomFilename );
if ( pomFile != null && pomFile.exists() )
{
StorageAsset targetPomFile = target.getAsset( targetDir.getPath() + "/" + pomFilename );
copyFile(pomFile, targetPomFile, fixChecksums );
queueRepositoryTask( target.getId(), targetPomFile );
}
// explicitly update only if metadata-updater consumer is not enabled!
if ( !archivaAdministration.getKnownContentConsumers().contains( "metadata-updater" ) )
{
updateProjectMetadata( target.getType(), target, targetDir, lastUpdatedTimestamp, timestamp, newBuildNumber,
fixChecksums, artifactTransferRequest );
}
String msg =
"Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId()
+ ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'"
+ artifactTransferRequest.getTargetRepositoryId() + "\'";
log.debug("copyArtifact {}", msg);
}
catch ( RepositoryException | LayoutException e )
{
log.error( "RepositoryException: {}", e.getMessage(), e );
throw new ArchivaRestServiceException( e.getMessage(), e );
}
catch ( RepositoryAdminException e )
{
log.error( "RepositoryAdminException: {}", e.getMessage(), e );
throw new ArchivaRestServiceException( e.getMessage(), e );
}
catch ( IOException e )
{
log.error( "IOException: {}", e.getMessage(), e );
throw new ArchivaRestServiceException( e.getMessage(), e );
}
return ActionStatus.SUCCESS;
}
private void queueRepositoryTask( String repositoryId, StorageAsset localFile )
{
RepositoryTask task = new RepositoryTask();
task.setRepositoryId( repositoryId );
task.setResourceFile( localFile );
task.setUpdateRelatedArtifacts( true );
//task.setScanAll( true );
try
{
scheduler.queueTask( task );
}
catch ( TaskQueueException e )
{
log.error( "Unable to queue repository task to execute consumers on resource file ['{}"
+ "'].", localFile.getName());
}
}
private ArchivaRepositoryMetadata getMetadata( RepositoryType repositoryType, StorageAsset metadataFile )
throws RepositoryMetadataException
{
ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();
if ( metadataFile.exists() )
{
metadata = repositoryRegistry.getMetadataReader( repositoryType ).read( metadataFile );
}
return metadata;
}
private StorageAsset getMetadata( RepositoryStorage storage, String targetPath )
{
return storage.getAsset( targetPath + "/" + MetadataTools.MAVEN_METADATA );
}
/*
* Copies the asset to the new target.
*/
private void copyFile(StorageAsset sourceFile, StorageAsset targetPath, boolean fixChecksums)
throws IOException
{
FsStorageUtil.copyAsset( sourceFile, targetPath, true );
if ( fixChecksums )
{
fixChecksums( targetPath );
}
}
private void fixChecksums( StorageAsset file )
{
Path destinationFile = file.getFilePath();
if (destinationFile!=null)
{
ChecksummedFile checksum = new ChecksummedFile( destinationFile );
checksum.fixChecksums( algorithms );
}
}
private void updateProjectMetadata( RepositoryType repositoryType, RepositoryStorage storage, StorageAsset targetPath, Date lastUpdatedTimestamp, String timestamp, int buildNumber,
boolean fixChecksums, ArtifactTransferRequest artifactTransferRequest )
throws RepositoryMetadataException
{
List<String> availableVersions = new ArrayList<>();
String latestVersion = artifactTransferRequest.getVersion();
StorageAsset projectDir = targetPath.getParent();
StorageAsset projectMetadataFile = storage.getAsset( projectDir.getPath()+"/"+MetadataTools.MAVEN_METADATA );
ArchivaRepositoryMetadata projectMetadata = getMetadata( repositoryType, projectMetadataFile );
if ( projectMetadataFile.exists() )
{
availableVersions = projectMetadata.getAvailableVersions();
Collections.sort( availableVersions, VersionComparator.getInstance() );
if ( !availableVersions.contains( artifactTransferRequest.getVersion() ) )
{
availableVersions.add( artifactTransferRequest.getVersion() );
}
latestVersion = availableVersions.get( availableVersions.size() - 1 );
}
else
{
availableVersions.add( artifactTransferRequest.getVersion() );
projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
}
if ( projectMetadata.getGroupId() == null )
{
projectMetadata.setGroupId( artifactTransferRequest.getGroupId() );
}
if ( projectMetadata.getArtifactId() == null )
{
projectMetadata.setArtifactId( artifactTransferRequest.getArtifactId() );
}
projectMetadata.setLatestVersion( latestVersion );
projectMetadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
projectMetadata.setAvailableVersions( availableVersions );
if ( !VersionUtil.isSnapshot( artifactTransferRequest.getVersion() ) )
{
projectMetadata.setReleasedVersion( latestVersion );
}
try(OutputStreamWriter writer = new OutputStreamWriter(projectMetadataFile.getWriteStream(true))) {
RepositoryMetadataWriter.write(projectMetadata, writer);
} catch (IOException e) {
throw new RepositoryMetadataException(e);
}
if ( fixChecksums )
{
fixChecksums( projectMetadataFile );
}
}
@Override
public ActionStatus removeProjectVersion( String repositoryId, String namespace, String projectId, String version )
throws ArchivaRestServiceException
{
// if not a generic we can use the standard way to delete artifact
if ( !VersionUtil.isGenericSnapshot( version ) )
{
Artifact artifact = new Artifact( namespace, projectId, version );
artifact.setRepositoryId( repositoryId );
artifact.setContext( repositoryId );
return deleteArtifact( artifact );
}
if ( StringUtils.isEmpty( repositoryId ) )
{
throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
}
if ( !getPermissionStatus( repositoryId ).isAuthorizedToDeleteArtifacts() )
{
throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
}
if ( StringUtils.isEmpty( namespace ) )
{
throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
}
if ( StringUtils.isEmpty( projectId ) )
{
throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
}
if ( StringUtils.isEmpty( version ) )
{
throw new ArchivaRestServiceException( "version cannot be null", 400, null );
}
RepositorySession repositorySession = null;
try
{
repositorySession = repositorySessionFactory.createSession();
}
catch ( MetadataRepositoryException e )
{
e.printStackTrace( );
}
try
{
ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
BaseRepositoryContentLayout layout = repository.getLayout( BaseRepositoryContentLayout.class );
ArchivaItemSelector selector = ArchivaItemSelector.builder( )
.withNamespace( namespace )
.withProjectId( projectId )
.withVersion( version )
.build( );
Version versionItem = layout.getVersion( selector );
if (versionItem!=null && versionItem.exists()) {
repository.deleteItem( versionItem );
}
MetadataRepository metadataRepository = repositorySession.getRepository();
Collection<ArtifactMetadata> artifacts =
metadataRepository.getArtifacts(repositorySession , repositoryId, namespace, projectId, version );
for ( ArtifactMetadata artifactMetadata : artifacts )
{
metadataRepository.removeTimestampedArtifact(repositorySession , artifactMetadata, version );
}
metadataRepository.removeProjectVersion(repositorySession , repositoryId, namespace, projectId, version );
}
catch ( MetadataRepositoryException | MetadataResolutionException | RepositoryException | ItemNotFoundException | LayoutException e )
{
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
finally
{
try {
repositorySession.save();
} catch (MetadataSessionException e) {
log.error("Session save failed {}", e.getMessage());
}
repositorySession.close();
}
return ActionStatus.SUCCESS;
}
@Override
public ActionStatus deleteArtifact( Artifact artifact )
throws ArchivaRestServiceException
{
String repositoryId = artifact.getContext();
// some rest call can use context or repositoryId
// so try both!!
if ( StringUtils.isEmpty( repositoryId ) )
{
repositoryId = artifact.getRepositoryId();
}
if ( StringUtils.isEmpty( repositoryId ) )
{
throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
}
if ( !getPermissionStatus( repositoryId ).isAuthorizedToDeleteArtifacts() )
{
throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
}
if ( artifact == null )
{
throw new ArchivaRestServiceException( "artifact cannot be null", 400, null );
}
if ( StringUtils.isEmpty( artifact.getGroupId() ) )
{
throw new ArchivaRestServiceException( "artifact.groupId cannot be null", 400, null );
}
if ( StringUtils.isEmpty( artifact.getArtifactId() ) )
{
throw new ArchivaRestServiceException( "artifact.artifactId cannot be null", 400, null );
}
// TODO more control on artifact fields
boolean snapshotVersion =
VersionUtil.isSnapshot( artifact.getVersion() ) | VersionUtil.isGenericSnapshot( artifact.getVersion() );
String baseVersion = VersionUtil.getBaseVersion( artifact.getVersion( ) );
RepositorySession repositorySession = null;
try
{
repositorySession = repositorySessionFactory.createSession();
}
catch ( MetadataRepositoryException e )
{
e.printStackTrace( );
}
try
{
Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
TimeZone timezone = TimeZone.getTimeZone( "UTC" );
DateFormat fmt = new SimpleDateFormat( "yyyyMMdd.HHmmss" );
fmt.setTimeZone( timezone );
ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId );
ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
BaseRepositoryContentLayout layout = repository.getLayout( BaseRepositoryContentLayout.class );
ArchivaItemSelector versionSelector = ArchivaItemSelector.builder( ).withNamespace( artifact.getGroupId( ) )
.withProjectId( artifact.getArtifactId( ) )
.withVersion( baseVersion ).build( );
Version version1 = layout.getVersion( versionSelector );
String path = repository.toPath( version1 );
ArchivaItemSelector selector = ArchivaItemSelector.builder( )
.withNamespace( artifact.getGroupId( ) )
.withProjectId( artifact.getArtifactId( ) )
.withVersion( baseVersion )
.withClassifier( artifact.getClassifier( ) )
.withArtifactId( artifact.getArtifactId( ) )
.withType( artifact.getType( ) )
.includeRelatedArtifacts()
.build( );
MetadataRepository metadataRepository = repositorySession.getRepository();
if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
{
if ( StringUtils.isBlank( artifact.getPackaging() ) )
{
throw new ArchivaRestServiceException( "You must configure a type/packaging when using classifier",
400, null );
}
List<? extends org.apache.archiva.repository.content.Artifact> artifactItems = layout.getArtifacts( selector );
for ( org.apache.archiva.repository.content.Artifact aRef : artifactItems ) {
try
{
repository.deleteItem( aRef );
}
catch ( ItemNotFoundException e )
{
log.error( "Could not delete item, seems to be deleted by other thread. {}, {} ", aRef, e.getMessage( ) );
}
}
}
else
{
int index = path.lastIndexOf( '/' );
path = path.substring( 0, index );
StorageAsset targetPath = repo.getAsset( path );
if ( !targetPath.exists() )
{
//throw new ContentNotFoundException(
// artifact.getNamespace() + ":" + artifact.getArtifactId() + ":" + artifact.getVersion() );
log.warn( "targetPath {} not found skip file deletion", targetPath );
return ActionStatus.FAIL;
}
// TODO: this should be in the storage mechanism so that it is all tied together
// delete from file system
if ( !snapshotVersion && version1.exists() )
{
try
{
repository.deleteItem( version1 );
}
catch ( ItemNotFoundException e )
{
log.error( "Could not delete version item {}", e.getMessage( ) );
}
}
else
{
// We are deleting all version related artifacts for a snapshot version
for ( org.apache.archiva.repository.content.Artifact delArtifact : layout.getArtifacts( selector )) {
try
{
repository.deleteItem( delArtifact );
}
catch ( ItemNotFoundException e )
{
log.warn( "Artifact that should be deleted, was not found: {}", delArtifact );
}
}
StorageAsset metadataFile = getMetadata( repo, targetPath.getPath() );
ArchivaRepositoryMetadata metadata = getMetadata( repository.getRepository().getType(), metadataFile );
updateMetadata( metadata, metadataFile, lastUpdatedTimestamp, artifact );
}
}
Collection<ArtifactMetadata> artifacts = Collections.emptyList();
if ( snapshotVersion )
{
artifacts =
metadataRepository.getArtifacts(repositorySession , repositoryId, artifact.getGroupId(),
artifact.getArtifactId(), baseVersion );
}
else
{
artifacts =
metadataRepository.getArtifacts(repositorySession , repositoryId, artifact.getGroupId(),
artifact.getArtifactId(), artifact.getVersion() );
}
log.debug( "artifacts: {}", artifacts );
if ( artifacts.isEmpty() )
{
if ( !snapshotVersion )
{
// verify metata repository doesn't contains anymore the version
Collection<String> projectVersions =
metadataRepository.getProjectVersions(repositorySession , repositoryId,
artifact.getGroupId(), artifact.getArtifactId() );
if ( projectVersions.contains( artifact.getVersion() ) )
{
log.warn( "artifact not found when deleted but version still here ! so force cleanup" );
metadataRepository.removeProjectVersion(repositorySession , repositoryId,
artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion() );
}
}
}
for ( ArtifactMetadata artifactMetadata : artifacts )
{
// TODO: mismatch between artifact (snapshot) version and project (base) version here
if ( artifactMetadata.getVersion().equals( artifact.getVersion() ) )
{
if ( StringUtils.isNotBlank( artifact.getClassifier() ) )
{
if ( StringUtils.isBlank( artifact.getPackaging() ) )
{
throw new ArchivaRestServiceException(
"You must configure a type/packaging when using classifier", 400, null );
}
// cleanup facet which contains classifier information
MavenArtifactFacet mavenArtifactFacet =
(MavenArtifactFacet) artifactMetadata.getFacet( MavenArtifactFacet.FACET_ID );
if ( StringUtils.equals( artifact.getClassifier(), mavenArtifactFacet.getClassifier() ) )
{
artifactMetadata.removeFacet( MavenArtifactFacet.FACET_ID );
String groupId = artifact.getGroupId(), artifactId = artifact.getArtifactId(), version =
artifact.getVersion();
MavenArtifactFacet mavenArtifactFacetToCompare = new MavenArtifactFacet();
mavenArtifactFacetToCompare.setClassifier( artifact.getClassifier() );
metadataRepository.removeFacetFromArtifact(repositorySession , repositoryId, groupId, artifactId,
version, mavenArtifactFacetToCompare );
repositorySession.save();
}
}
else
{
if ( snapshotVersion )
{
metadataRepository.removeTimestampedArtifact(repositorySession ,
artifactMetadata, VersionUtil.getBaseVersion( artifact.getVersion() ) );
}
else
{
metadataRepository.removeArtifact(repositorySession ,
artifactMetadata.getRepositoryId(),
artifactMetadata.getNamespace(), artifactMetadata.getProject(),
artifact.getVersion(), artifactMetadata.getId() );
}
}
// TODO: move into the metadata repository proper - need to differentiate attachment of
// repository metadata to an artifact
for ( RepositoryListener listener : listeners )
{
listener.deleteArtifact( metadataRepository, repository.getId(),
artifactMetadata.getNamespace(), artifactMetadata.getProject(),
artifactMetadata.getVersion(), artifactMetadata.getId() );
}
triggerAuditEvent( repositoryId, path, AuditEvent.REMOVE_FILE );
}
}
}
catch ( ContentNotFoundException e )
{
throw new ArchivaRestServiceException( "Artifact does not exist: " + e.getMessage(), 400, e );
}
catch ( RepositoryNotFoundException e )
{
throw new ArchivaRestServiceException( "Target repository cannot be found: " + e.getMessage(), 400, e );
}
catch ( RepositoryException e )
{
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
catch (MetadataResolutionException | MetadataSessionException | MetadataRepositoryException | LayoutException e )
{
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
finally
{
try {
repositorySession.save();
} catch (MetadataSessionException e) {
log.error("Could not save sesion {}", e.getMessage());
}
repositorySession.close();
}
return ActionStatus.SUCCESS;
}
@Override
public ActionStatus deleteGroupId( String groupId, String repositoryId )
throws ArchivaRestServiceException
{
if ( StringUtils.isEmpty( repositoryId ) )
{
throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
}
if ( !getPermissionStatus( repositoryId ).isAuthorizedToDeleteArtifacts() )
{
throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
}
if ( StringUtils.isEmpty( groupId ) )
{
throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
}
RepositorySession repositorySession = null;
try
{
repositorySession = repositorySessionFactory.createSession();
}
catch ( MetadataRepositoryException e )
{
e.printStackTrace( );
}
try
{
ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
ArchivaItemSelector itemselector = ArchivaItemSelector.builder( ).withNamespace( groupId ).build();
ContentItem item = repository.getItem( itemselector );
repository.deleteItem( item );
MetadataRepository metadataRepository = repositorySession.getRepository();
metadataRepository.removeNamespace(repositorySession , repositoryId, groupId );
// just invalidate cache entry
String cacheKey = repositoryId + "-" + groupId;
namespacesCache.remove( cacheKey );
namespacesCache.remove( repositoryId );
repositorySession.save();
}
catch (MetadataRepositoryException | MetadataSessionException e )
{
log.error( e.getMessage(), e );
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
catch ( RepositoryException e )
{
log.error( e.getMessage(), e );
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
catch ( ItemNotFoundException e )
{
log.error( "Item not found {}", e.getMessage(), e );
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
finally
{
repositorySession.close();
}
return ActionStatus.SUCCESS;
}
@Override
public ActionStatus deleteProject( String groupId, String projectId, String repositoryId )
throws ArchivaRestServiceException
{
if ( StringUtils.isEmpty( repositoryId ) )
{
throw new ArchivaRestServiceException( "repositoryId cannot be null", 400, null );
}
if ( !getPermissionStatus( repositoryId ).isAuthorizedToDeleteArtifacts() )
{
throw new ArchivaRestServiceException( "not authorized to delete artifacts", 403, null );
}
if ( StringUtils.isEmpty( groupId ) )
{
throw new ArchivaRestServiceException( "groupId cannot be null", 400, null );
}
if ( StringUtils.isEmpty( projectId ) )
{
throw new ArchivaRestServiceException( "artifactId cannot be null", 400, null );
}
RepositorySession repositorySession = null;
try
{
repositorySession = repositorySessionFactory.createSession();
}
catch ( MetadataRepositoryException e )
{
e.printStackTrace( );
}
try
{
ManagedRepositoryContent repository = getManagedRepositoryContent( repositoryId );
ArchivaItemSelector itemSelector = ArchivaItemSelector.builder( ).withNamespace( groupId )
.withProjectId( projectId ).build( );
ContentItem item = repository.getItem( itemSelector );
repository.deleteItem( item );
}
catch ( ContentNotFoundException e )
{
log.warn( "skip ContentNotFoundException: {}", e.getMessage() );
}
catch ( RepositoryException e )
{
log.error( e.getMessage(), e );
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
catch ( ItemNotFoundException e )
{
log.error( "Item not found {}", e.getMessage(), e );
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
try
{
MetadataRepository metadataRepository = repositorySession.getRepository();
metadataRepository.removeProject(repositorySession , repositoryId, groupId, projectId );
repositorySession.save();
}
catch (MetadataRepositoryException | MetadataSessionException e )
{
log.error( e.getMessage(), e );
throw new ArchivaRestServiceException( "Repository exception: " + e.getMessage(), 500, e );
}
finally
{
repositorySession.close();
}
return ActionStatus.SUCCESS;
}
@Override
public PermissionStatus getPermissionStatus( String repoId )
throws ArchivaRestServiceException
{
String userName =
getAuditInformation().getUser() == null ? "guest" : getAuditInformation().getUser().getUsername();
try
{
return new PermissionStatus( userRepositories.isAuthorizedToDeleteArtifacts( userName, repoId ) );
}
catch ( ArchivaSecurityException e )
{
throw new ArchivaRestServiceException( e.getMessage(),
Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e );
}
}
@Override
public RepositoryScanStatistics scanRepositoryDirectoriesNow( String repositoryId )
throws ArchivaRestServiceException
{
long sinceWhen = RepositoryScanner.FRESH_SCAN;
try
{
return repoScanner.scan( repositoryRegistry.getManagedRepository( repositoryId ), sinceWhen );
}
catch ( RepositoryScannerException e )
{
log.error( e.getMessage(), e );
throw new ArchivaRestServiceException( "RepositoryScannerException exception: " + e.getMessage(), 500, e );
}
}
/**
* Update artifact level metadata. Creates one if metadata does not exist after artifact deletion.
*
* @param metadata
*/
private void updateMetadata( ArchivaRepositoryMetadata metadata, StorageAsset metadataFile, Date lastUpdatedTimestamp,
Artifact artifact )
throws RepositoryMetadataException
{
List<String> availableVersions = new ArrayList<>();
String latestVersion = "";
if ( metadataFile.exists() )
{
if ( metadata.getAvailableVersions() != null )
{
availableVersions = metadata.getAvailableVersions();
if ( availableVersions.size() > 0 )
{
Collections.sort( availableVersions, VersionComparator.getInstance() );
if ( availableVersions.contains( artifact.getVersion() ) )
{
availableVersions.remove( availableVersions.indexOf( artifact.getVersion() ) );
}
if ( availableVersions.size() > 0 )
{
latestVersion = availableVersions.get( availableVersions.size() - 1 );
}
}
}
}
if ( metadata.getGroupId() == null )
{
metadata.setGroupId( artifact.getGroupId() );
}
if ( metadata.getArtifactId() == null )
{
metadata.setArtifactId( artifact.getArtifactId() );
}
if ( !VersionUtil.isSnapshot( artifact.getVersion() ) )
{
if ( metadata.getReleasedVersion() != null && metadata.getReleasedVersion().equals(
artifact.getVersion() ) )
{
metadata.setReleasedVersion( latestVersion );
}
}
metadata.setLatestVersion( latestVersion );
metadata.setLastUpdatedTimestamp( lastUpdatedTimestamp );
metadata.setAvailableVersions( availableVersions );
try (OutputStreamWriter writer = new OutputStreamWriter(metadataFile.getWriteStream(true))) {
RepositoryMetadataWriter.write(metadata, writer);
} catch (IOException e) {
throw new RepositoryMetadataException(e);
}
ChecksummedFile checksum = new ChecksummedFile( metadataFile.getFilePath() );
checksum.fixChecksums( algorithms );
}
@Override
public StringList getRunningRemoteDownloadIds()
{
return new StringList( downloadRemoteIndexScheduler.getRunningRemoteDownloadIds() );
}
public RepositorySessionFactory getRepositorySessionFactory()
{
return repositorySessionFactory;
}
public void setRepositorySessionFactory( RepositorySessionFactory repositorySessionFactory )
{
this.repositorySessionFactory = repositorySessionFactory;
}
public List<RepositoryListener> getListeners()
{
return listeners;
}
public void setListeners( List<RepositoryListener> listeners )
{
this.listeners = listeners;
}
public ArchivaAdministration getArchivaAdministration()
{
return archivaAdministration;
}
public void setArchivaAdministration( ArchivaAdministration archivaAdministration )
{
this.archivaAdministration = archivaAdministration;
}
}
| {'content_hash': '646288fc36fe2a56a5f1600a7348dd5a', 'timestamp': '', 'source': 'github', 'line_count': 1265, 'max_line_length': 184, 'avg_line_length': 39.500395256916995, 'alnum_prop': 0.6190361831572206, 'repo_name': 'sadlil/archiva', 'id': 'f7871e75a64357822a7c06f9d13b6bb07e1ea276', 'size': '50775', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'archiva-modules/archiva-web/archiva-rest/archiva-rest-services/src/main/java/org/apache/archiva/rest/services/DefaultRepositoriesService.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AGS Script', 'bytes': '27'}, {'name': 'Batchfile', 'bytes': '948'}, {'name': 'CSS', 'bytes': '193266'}, {'name': 'Dockerfile', 'bytes': '3302'}, {'name': 'Groovy', 'bytes': '8937'}, {'name': 'HTML', 'bytes': '315360'}, {'name': 'Java', 'bytes': '7001198'}, {'name': 'JavaScript', 'bytes': '830548'}, {'name': 'Mustache', 'bytes': '12049'}, {'name': 'PowerShell', 'bytes': '7011'}, {'name': 'SCSS', 'bytes': '26549'}, {'name': 'Shell', 'bytes': '31357'}, {'name': 'TypeScript', 'bytes': '334037'}]} |
"use strict";
var events = require ("events");
var util = require ("util");
var SAMPLES = 4;
var TIMEOUT = 1000;
//setImmediate executes in the next loop (empties the call stack), so the
//max stack limit is never reached and nextTick can be run indefinitely
//https://github.com/isaacs/node-bench/blob/master/lib/bench.js
var async = (function (){
var i = 0;
return function (fn){
if (i++ < 100){
process.nextTick (fn);
}else{
setImmediate (fn);
i = 0;
}
}
})();
var run = function (fn, timeout, ignore, cb){
var calls = 0;
var startTime = Date.now ();
var stopTime = startTime + (ignore ? timeout : 10);
var hr = process.hrtime ();
if (fn.length){
(function cycle (){
fn (function (){
calls++;
var now = Date.now ();
if (now > stopTime){
var diff = process.hrtime (hr);
return cb (calls/(diff[0] + diff[1]/1e9));
}
async (cycle);
});
})();
}else{
(function cycle (){
for (var i=0; i<100; i++){
fn ();
}
calls++;
var now = Date.now ();
if (now > stopTime){
var diff = process.hrtime (hr);
return cb ((calls*100)/(diff[0] + diff[1]/1e9));
}
async (cycle);
})();
}
};
var Runner = module.exports = function (tests){
events.EventEmitter.call (this);
var me = this;
if (typeof tests === "function"){
this._anonymous = true;
tests = [{ fn: tests }];
}
this._tests = tests;
this._samples = SAMPLES;
this._timeout = TIMEOUT;
this._totalProgress = null;
this._currentProgress = 0;
if (this._anonymous){
this._results = [];
}else{
var me = this;
this._results = {};
this._tests.forEach (function (test){
me._results[test.name] = [];
});
}
var me = this;
process.nextTick (function (){
me._totalProgress = me._tests.length*(me._samples - 1);
me._prepare ();
});
};
util.inherits (Runner, events.EventEmitter);
Runner.prototype._progress = function (){
return ++this._currentProgress/this._totalProgress;
};
Runner.prototype._end = function (){
var data = [];
if (this._anonymous){
data[0] = {
raw: this._results
};
}else{
for (var name in this._results){
data.push ({
name: name,
raw: this._results[name]
});
}
}
this.emit ("end", data);
};
Runner.prototype._prepare = function (){
//Runs all the benchmarks to warm-up the virtual machine
var len = this._tests.length;
var me = this;
(function benchmark (i){
if (i === len){
return me._execute ();
}
run (me._tests[i].fn, null, null, function (n){
benchmark (i + 1);
});
})(0);
};
Runner.prototype._execute = function (){
var me = this;
var testsLength = me._tests.length;
(function benchmark (i){
if (i === testsLength){
return me._end ();
}
(function sample (s){
if (s === me._samples){
var o = {};
var test = me._tests[i];
if (me._anonymous){
o.raw = me._results;
}else{
o.name = test.name;
o.raw = me._results[test.name];
}
me.emit ("test", o);
return benchmark (i + 1);
}
var test = me._tests[i];
run (test.fn, me._timeout, s, function (n){
//The first run is ignored because produces inconsistent values
//Virtual machine warm-up stuff
if (s){
me.emit ("progress", me._progress ());
if (me._anonymous){
me._results.push (n);
}else{
me._results[test.name].push (n);
}
}
sample (s + 1);
});
})(0);
})(0);
};
Runner.prototype.samples = function (n){
if (n === undefined) return this._samples - 1;
this._samples = n + 1;
};
Runner.prototype.timeout = function (n){
if (n === undefined) return this._timeout;
this._timeout = n;
}; | {'content_hash': '252f67efd43838c3e15dfe25b378376a', 'timestamp': '', 'source': 'github', 'line_count': 185, 'max_line_length': 73, 'avg_line_length': 21.63783783783784, 'alnum_prop': 0.5253559830127404, 'repo_name': 'gagle/node-speedy', 'id': '0601ee0eb588b80939c4ca2376e8d1565cab1cff', 'size': '4003', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/runner.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '28965'}]} |
package org.apache.nifi.stateless.config;
public class StatelessConfigurationException extends Exception {
public StatelessConfigurationException(final String message) {
super(message);
}
public StatelessConfigurationException(final String message, final Throwable cause) {
super(message, cause);
}
public StatelessConfigurationException(final Throwable cause) {
super(cause);
}
}
| {'content_hash': '9ee8eb2e1a4d209770669ae6fec77bf0', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 89, 'avg_line_length': 25.529411764705884, 'alnum_prop': 0.7304147465437788, 'repo_name': 'pvillard31/nifi', 'id': 'be7fc1d043f29478fba83ed5be8a26ef463feb86', 'size': '1235', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'nifi-stateless/nifi-stateless-api/src/main/java/org/apache/nifi/stateless/config/StatelessConfigurationException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '48535'}, {'name': 'C++', 'bytes': '652'}, {'name': 'CSS', 'bytes': '297537'}, {'name': 'Clojure', 'bytes': '3993'}, {'name': 'Dockerfile', 'bytes': '24868'}, {'name': 'GAP', 'bytes': '31198'}, {'name': 'Groovy', 'bytes': '1948079'}, {'name': 'HTML', 'bytes': '1212191'}, {'name': 'Handlebars', 'bytes': '39081'}, {'name': 'Java', 'bytes': '57094735'}, {'name': 'JavaScript', 'bytes': '4277719'}, {'name': 'Lua', 'bytes': '983'}, {'name': 'Mustache', 'bytes': '2438'}, {'name': 'Python', 'bytes': '27513'}, {'name': 'Ruby', 'bytes': '23018'}, {'name': 'SCSS', 'bytes': '22032'}, {'name': 'Shell', 'bytes': '164326'}, {'name': 'TypeScript', 'bytes': '1337'}, {'name': 'XSLT', 'bytes': '7835'}]} |
InDesign Barcode maker
======================
Easily make simple ISBN-based book barcodes in InDesign. Just enter the ISBN
and the fonts to be used.
Use [`id_barcode.jsx`](https://github.com/skilldrick/id_barcode/raw/master/id_barcode.jsx) if you just want to use the plugin.
| {'content_hash': 'b30a82c1bc8aea1978e665e372d1cc01', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 126, 'avg_line_length': 39.714285714285715, 'alnum_prop': 0.7122302158273381, 'repo_name': 'skilldrick/id_barcode', 'id': '482d5395d2a609b3e809591384cd37cb1b8440bf', 'size': '278', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.markdown', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '33377'}, {'name': 'Shell', 'bytes': '152'}]} |
<!DOCTYPE html>
<html>
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# githubog: http://ogp.me/ns/fb/githubog#">
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Improved regex in strip_tags · d7504a3 · django/django</title>
<link rel="search" type="application/opensearchdescription+xml" href="/opensearch.xml" title="GitHub" />
<link rel="fluid-icon" href="https://github.com/fluidicon.png" title="GitHub" />
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-114.png" />
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114.png" />
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-144.png" />
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144.png" />
<link rel="logo" type="image/svg" href="http://github-media-downloads.s3.amazonaws.com/github-logo.svg" />
<meta name="msapplication-TileImage" content="/windows-tile.png">
<meta name="msapplication-TileColor" content="#ffffff">
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<meta content="authenticity_token" name="csrf-param" />
<meta content="Vbmuc30dLLFdm7POIe3xfTa4nODYc/la/wLrI1OLEOI=" name="csrf-token" />
<link href="https://a248.e.akamai.net/assets.github.com/assets/github-f70e4783e00fd4884a9e5e651a43933c9881caa8.css" media="all" rel="stylesheet" type="text/css" />
<link href="https://a248.e.akamai.net/assets.github.com/assets/github2-0d31290d073dea4d8671e2b8c747629aeb074034.css" media="all" rel="stylesheet" type="text/css" />
<script src="https://a248.e.akamai.net/assets.github.com/assets/frameworks-d76b58e749b52bc47a4c46620bf2c320fabe5248.js" type="text/javascript"></script>
<script src="https://a248.e.akamai.net/assets.github.com/assets/github-67b55380cff8d6766b298e6935a3c1db7d5c6d5d.js" type="text/javascript"></script>
<meta http-equiv="x-pjax-version" content="1212ad79754350a805cefbcd08a3dadf">
<link data-pjax-transient rel='alternate' type='text/plain+diff' href="/django/django/commit/d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e.diff">
<link data-pjax-transient rel='alternate' type='text/plain+patch' href="/django/django/commit/d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e.patch">
<link data-pjax-transient rel='permalink' type='text/html' href="/django/django/commit/d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e">
<meta property="og:title" content="django"/>
<meta property="og:type" content="githubog:gitrepository"/>
<meta property="og:url" content="https://github.com/django/django"/>
<meta property="og:image" content="https://secure.gravatar.com/avatar/fd542381031aa84dca86628ece84fc07?s=420&d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png"/>
<meta property="og:site_name" content="GitHub"/>
<meta property="og:description" content="django - The Web framework for perfectionists with deadlines."/>
<meta property="twitter:card" content="summary"/>
<meta property="twitter:site" content="@GitHub">
<meta property="twitter:title" content="django/django"/>
<meta name="description" content="django - The Web framework for perfectionists with deadlines." />
<link href="https://github.com/django/django/commits/d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e.atom" rel="alternate" title="Recent Commits to django:d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e" type="application/atom+xml" />
</head>
<body class="logged_in linux vis-public env-production ">
<div id="wrapper">
<div class="header header-logged-in true">
<div class="container clearfix">
<a class="header-logo-blacktocat" href="https://github.com/">
<span class="mega-icon mega-icon-blacktocat"></span>
</a>
<div class="divider-vertical"></div>
<a href="/django/django/notifications" class="notification-indicator tooltipped downwards contextually-unread" title="You have unread notifications in this repository">
<span class="mail-status unread"></span>
</a>
<div class="divider-vertical"></div>
<div class="command-bar js-command-bar ">
<form accept-charset="UTF-8" action="/search" class="command-bar-form" id="top_search_form" method="get">
<a href="/search/advanced" class="advanced-search-icon tooltipped downwards command-bar-search" id="advanced_search" title="Advanced search"><span class="mini-icon mini-icon-advanced-search "></span></a>
<input type="text" name="q" id="js-command-bar-field" placeholder="Search or type a command" tabindex="1" data-username="claudep" autocapitalize="off">
<span class="mini-icon help tooltipped downwards" title="Show command bar help">
<span class="mini-icon mini-icon-help"></span>
</span>
<input type="hidden" name="ref" value="commandbar">
<div class="divider-vertical"></div>
</form>
<ul class="top-nav">
<li class="explore"><a href="https://github.com/explore">Explore</a></li>
<li><a href="https://gist.github.com">Gist</a></li>
<li><a href="/blog">Blog</a></li>
<li><a href="http://help.github.com">Help</a></li>
</ul>
</div>
<ul id="user-links">
<li>
<a href="https://github.com/claudep" class="name">
<img height="20" src="https://secure.gravatar.com/avatar/cf4198670f0073174b475634964b576b?s=140&d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="20" /> claudep
</a>
</li>
<li>
<a href="/new" id="new_repo" class="tooltipped downwards" title="Create a new repo">
<span class="mini-icon mini-icon-create"></span>
</a>
</li>
<li>
<a href="/settings/profile" id="account_settings"
class="tooltipped downwards"
title="Account settings ">
<span class="mini-icon mini-icon-account-settings"></span>
</a>
</li>
<li>
<a href="/logout" data-method="post" id="logout" class="tooltipped downwards" title="Sign out">
<span class="mini-icon mini-icon-logout"></span>
</a>
</li>
</ul>
</div>
</div>
<div class="site hfeed" itemscope itemtype="http://schema.org/WebPage">
<div class="hentry">
<div class="pagehead repohead instapaper_ignore readability-menu ">
<div class="container">
<div class="title-actions-bar">
<ul class="pagehead-actions">
<li class="nspr">
<a href="/django/django/pull/new/d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e" class="button minibutton btn-pull-request" icon_class="mini-icon-pull-request"><span class="mini-icon mini-icon-pull-request"></span>Pull Request</a>
</li>
<li class="subscription">
<form accept-charset="UTF-8" action="/notifications/subscribe" data-autosubmit="true" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="Vbmuc30dLLFdm7POIe3xfTa4nODYc/la/wLrI1OLEOI=" /></div> <input id="repository_id" name="repository_id" type="hidden" value="4164482" />
<div class="select-menu js-menu-container js-select-menu">
<span class="minibutton select-menu-button js-menu-target">
<span class="js-select-button">
<span class="mini-icon mini-icon-watching"></span>
Watch
</span>
</span>
<div class="select-menu-modal-holder js-menu-content">
<div class="select-menu-modal">
<div class="select-menu-header">
<span class="select-menu-title">Notification status</span>
<span class="mini-icon mini-icon-remove-close js-menu-close"></span>
</div> <!-- /.select-menu-header -->
<div class="select-menu-list js-navigation-container">
<div class="select-menu-item js-navigation-item js-navigation-target selected">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<div class="select-menu-item-text">
<input checked="checked" id="do_included" name="do" type="radio" value="included" />
<h4>Not watching</h4>
<span class="description">You only receive notifications for discussions in which you participate or are @mentioned.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="mini-icon mini-icon-watching"></span>
Watch
</span>
</div>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<div class="select-menu-item-text">
<input id="do_subscribed" name="do" type="radio" value="subscribed" />
<h4>Watching</h4>
<span class="description">You receive notifications for all discussions in this repository.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="mini-icon mini-icon-unwatch"></span>
Unwatch
</span>
</div>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<div class="select-menu-item-text">
<input id="do_ignore" name="do" type="radio" value="ignore" />
<h4>Ignoring</h4>
<span class="description">You do not receive any notifications for discussions in this repository.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="mini-icon mini-icon-mute"></span>
Stop ignoring
</span>
</div>
</div> <!-- /.select-menu-item -->
</div> <!-- /.select-menu-list -->
</div> <!-- /.select-menu-modal -->
</div> <!-- /.select-menu-modal-holder -->
</div> <!-- /.select-menu -->
</form>
</li>
<li class="js-toggler-container js-social-container starring-container on">
<a href="/django/django/unstar" class="minibutton js-toggler-target star-button starred upwards" title="Unstar this repo" data-remote="true" data-method="post" rel="nofollow">
<span class="mini-icon mini-icon-remove-star"></span>
<span class="text">Unstar</span>
</a>
<a href="/django/django/star" class="minibutton js-toggler-target star-button unstarred upwards" title="Star this repo" data-remote="true" data-method="post" rel="nofollow">
<span class="mini-icon mini-icon-star"></span>
<span class="text">Star</span>
</a>
<a class="social-count js-social-count" href="/django/django/stargazers">5,939</a>
</li>
<li>
<a href="/django/django/fork_select" class="minibutton js-toggler-target fork-button lighter upwards" title="Fork this repo" rel="facebox nofollow">
<span class="mini-icon mini-icon-branch-create"></span>
<span class="text">Fork</span>
</a>
<a href="/django/django/network" class="social-count">1,909</a>
</li>
</ul>
<h1 itemscope itemtype="http://data-vocabulary.org/Breadcrumb" class="entry-title public">
<span class="repo-label"><span>public</span></span>
<span class="mega-icon mega-icon-public-repo"></span>
<span class="author vcard">
<a href="/django" class="url fn" itemprop="url" rel="author">
<span itemprop="title">django</span>
</a></span> /
<strong><a href="/django/django" class="js-current-repository">django</a></strong>
</h1>
</div>
<ul class="tabs">
<li><a href="/django/django" class="selected" highlight="repo_source repo_downloads repo_commits repo_tags repo_branches">Code</a></li>
<li><a href="/django/django/network" highlight="repo_network">Network</a></li>
<li><a href="/django/django/pulls" highlight="repo_pulls">Pull Requests <span class='counter'>177</span></a></li>
<li><a href="/django/django/graphs" highlight="repo_graphs repo_contributors">Graphs</a></li>
<li>
<a href="/django/django/settings">Settings</a>
</li>
</ul>
<div class="tabnav">
<span class="tabnav-right">
<ul class="tabnav-tabs">
<li><a href="/django/django/tags" class="tabnav-tab" highlight="repo_tags">Tags <span class="counter ">39</span></a></li>
</ul>
</span>
<div class="tabnav-widget scope">
<div class="select-menu js-menu-container js-select-menu js-branch-menu">
<a class="minibutton select-menu-button js-menu-target" data-hotkey="w" data-ref="">
<span class="mini-icon mini-icon-tree"></span>
<i>tree:</i>
<span class="js-select-button">d7504a3d7b</span>
</a>
<div class="select-menu-modal-holder js-menu-content js-navigation-container">
<div class="select-menu-modal">
<div class="select-menu-header">
<span class="select-menu-title">Switch branches/tags</span>
<span class="mini-icon mini-icon-remove-close js-menu-close"></span>
</div> <!-- /.select-menu-header -->
<div class="select-menu-filters">
<div class="select-menu-text-filter">
<input type="text" id="commitish-filter-field" class="js-filterable-field js-navigation-enable" placeholder="Find or create a branch…">
</div>
<div class="select-menu-tabs">
<ul>
<li class="select-menu-tab">
<a href="#" data-tab-filter="branches" class="js-select-menu-tab">Branches</a>
</li>
<li class="select-menu-tab">
<a href="#" data-tab-filter="tags" class="js-select-menu-tab">Tags</a>
</li>
</ul>
</div><!-- /.select-menu-tabs -->
</div><!-- /.select-menu-filters -->
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket css-truncate" data-tab-filter="branches">
<div data-filterable-for="commitish-filter-field" data-filterable-type="substring">
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/boulder-oracle-sprint" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/boulder-oracle-sprint" rel="nofollow" title="attic/boulder-oracle-sprint">attic/boulder-oracle-sprint</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/full-history" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/full-history" rel="nofollow" title="attic/full-history">attic/full-history</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/generic-auth" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/generic-auth" rel="nofollow" title="attic/generic-auth">attic/generic-auth</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/gis" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/gis" rel="nofollow" title="attic/gis">attic/gis</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/i18n" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/i18n" rel="nofollow" title="attic/i18n">attic/i18n</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/magic-removal" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/magic-removal" rel="nofollow" title="attic/magic-removal">attic/magic-removal</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/multi-auth" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/multi-auth" rel="nofollow" title="attic/multi-auth">attic/multi-auth</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/multiple-db-support" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/multiple-db-support" rel="nofollow" title="attic/multiple-db-support">attic/multiple-db-support</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/new-admin" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/new-admin" rel="nofollow" title="attic/new-admin">attic/new-admin</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/newforms-admin" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/newforms-admin" rel="nofollow" title="attic/newforms-admin">attic/newforms-admin</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/per-object-permissions" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/per-object-permissions" rel="nofollow" title="attic/per-object-permissions">attic/per-object-permissions</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/queryset-refactor" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/queryset-refactor" rel="nofollow" title="attic/queryset-refactor">attic/queryset-refactor</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/schema-evolution" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/schema-evolution" rel="nofollow" title="attic/schema-evolution">attic/schema-evolution</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/schema-evolution-ng" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/schema-evolution-ng" rel="nofollow" title="attic/schema-evolution-ng">attic/schema-evolution-ng</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/search-api" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/search-api" rel="nofollow" title="attic/search-api">attic/search-api</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/sqlalchemy" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/sqlalchemy" rel="nofollow" title="attic/sqlalchemy">attic/sqlalchemy</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/attic/unicode" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="attic/unicode" rel="nofollow" title="attic/unicode">attic/unicode</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/master" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="master" rel="nofollow" title="master">master</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2009/admin-ui" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2009/admin-ui" rel="nofollow" title="soc2009/admin-ui">soc2009/admin-ui</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2009/http-wsgi-improvements" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2009/http-wsgi-improvements" rel="nofollow" title="soc2009/http-wsgi-improvements">soc2009/http-wsgi-improvements</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2009/i18n-improvements" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2009/i18n-improvements" rel="nofollow" title="soc2009/i18n-improvements">soc2009/i18n-improvements</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2009/model-validation" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2009/model-validation" rel="nofollow" title="soc2009/model-validation">soc2009/model-validation</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2009/multidb" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2009/multidb" rel="nofollow" title="soc2009/multidb">soc2009/multidb</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2009/test-improvements" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2009/test-improvements" rel="nofollow" title="soc2009/test-improvements">soc2009/test-improvements</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2010/app-loading" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2010/app-loading" rel="nofollow" title="soc2010/app-loading">soc2010/app-loading</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2010/query-refactor" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2010/query-refactor" rel="nofollow" title="soc2010/query-refactor">soc2010/query-refactor</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/soc2010/test-refactor" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="soc2010/test-refactor" rel="nofollow" title="soc2010/test-refactor">soc2010/test-refactor</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/0.90.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/0.90.x" rel="nofollow" title="stable/0.90.x">stable/0.90.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/0.91.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/0.91.x" rel="nofollow" title="stable/0.91.x">stable/0.91.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/0.95.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/0.95.x" rel="nofollow" title="stable/0.95.x">stable/0.95.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/0.96.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/0.96.x" rel="nofollow" title="stable/0.96.x">stable/0.96.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/1.0.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/1.0.x" rel="nofollow" title="stable/1.0.x">stable/1.0.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/1.1.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/1.1.x" rel="nofollow" title="stable/1.1.x">stable/1.1.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/1.2.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/1.2.x" rel="nofollow" title="stable/1.2.x">stable/1.2.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/1.3.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/1.3.x" rel="nofollow" title="stable/1.3.x">stable/1.3.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/1.4.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/1.4.x" rel="nofollow" title="stable/1.4.x">stable/1.4.x</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/stable/1.5.x" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="stable/1.5.x" rel="nofollow" title="stable/1.5.x">stable/1.5.x</a>
</div> <!-- /.select-menu-item -->
</div>
<form accept-charset="UTF-8" action="/django/django/branches" class="js-create-branch select-menu-item select-menu-new-item-form js-navigation-item js-navigation-target js-new-item-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="Vbmuc30dLLFdm7POIe3xfTa4nODYc/la/wLrI1OLEOI=" /></div>
<span class="mini-icon mini-icon-branch-create select-menu-item-icon"></span>
<div class="select-menu-item-text">
<h4>Create branch: <span class="js-new-item-name"></span></h4>
<span class="description">from ‘d7504a3’</span>
</div>
<input type="hidden" name="name" id="name" class="js-new-item-submit" />
<input type="hidden" name="branch" id="branch" value="d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e" />
<input type="hidden" name="path" id="branch" value="" />
</form> <!-- /.select-menu-item -->
</div> <!-- /.select-menu-list -->
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket css-truncate" data-tab-filter="tags">
<div data-filterable-for="commitish-filter-field" data-filterable-type="substring">
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.5c2" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.5c2" rel="nofollow" title="1.5c2">1.5c2</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.5c1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.5c1" rel="nofollow" title="1.5c1">1.5c1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.5b2" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.5b2" rel="nofollow" title="1.5b2">1.5b2</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.5b1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.5b1" rel="nofollow" title="1.5b1">1.5b1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.5a1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.5a1" rel="nofollow" title="1.5a1">1.5a1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.5.1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.5.1" rel="nofollow" title="1.5.1">1.5.1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.5" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.5" rel="nofollow" title="1.5">1.5</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.4.5" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.4.5" rel="nofollow" title="1.4.5">1.4.5</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.4.4" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.4.4" rel="nofollow" title="1.4.4">1.4.4</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.4.3" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.4.3" rel="nofollow" title="1.4.3">1.4.3</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.4.2" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.4.2" rel="nofollow" title="1.4.2">1.4.2</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.4.1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.4.1" rel="nofollow" title="1.4.1">1.4.1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.4" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.4" rel="nofollow" title="1.4">1.4</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.3.7" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.3.7" rel="nofollow" title="1.3.7">1.3.7</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.3.6" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.3.6" rel="nofollow" title="1.3.6">1.3.6</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.3.5" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.3.5" rel="nofollow" title="1.3.5">1.3.5</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.3.4" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.3.4" rel="nofollow" title="1.3.4">1.3.4</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.3.3" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.3.3" rel="nofollow" title="1.3.3">1.3.3</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.3.2" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.3.2" rel="nofollow" title="1.3.2">1.3.2</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.3.1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.3.1" rel="nofollow" title="1.3.1">1.3.1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.3" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.3" rel="nofollow" title="1.3">1.3</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.2.7" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.2.7" rel="nofollow" title="1.2.7">1.2.7</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.2.6" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.2.6" rel="nofollow" title="1.2.6">1.2.6</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.2.5" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.2.5" rel="nofollow" title="1.2.5">1.2.5</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.2.4" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.2.4" rel="nofollow" title="1.2.4">1.2.4</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.2.3" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.2.3" rel="nofollow" title="1.2.3">1.2.3</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.2.2" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.2.2" rel="nofollow" title="1.2.2">1.2.2</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.2.1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.2.1" rel="nofollow" title="1.2.1">1.2.1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.2" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.2" rel="nofollow" title="1.2">1.2</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.1.4" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.1.4" rel="nofollow" title="1.1.4">1.1.4</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.1.3" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.1.3" rel="nofollow" title="1.1.3">1.1.3</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.1.2" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.1.2" rel="nofollow" title="1.1.2">1.1.2</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.1.1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.1.1" rel="nofollow" title="1.1.1">1.1.1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.1" rel="nofollow" title="1.1">1.1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.0.4" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.0.4" rel="nofollow" title="1.0.4">1.0.4</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.0.3" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.0.3" rel="nofollow" title="1.0.3">1.0.3</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.0.2" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.0.2" rel="nofollow" title="1.0.2">1.0.2</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.0.1" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.0.1" rel="nofollow" title="1.0.1">1.0.1</a>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<a href="/django/django/commit/1.0" class="js-navigation-open select-menu-item-text js-select-button-text css-truncate-target" data-name="1.0" rel="nofollow" title="1.0">1.0</a>
</div> <!-- /.select-menu-item -->
</div>
<div class="select-menu-no-results">Nothing to show</div>
</div> <!-- /.select-menu-list -->
</div> <!-- /.select-menu-modal -->
</div> <!-- /.select-menu-modal-holder -->
</div> <!-- /.select-menu -->
</div> <!-- /.scope -->
<ul class="tabnav-tabs">
<li><a href="/django/django" class="tabnav-tab" highlight="repo_source">Files</a></li>
<li><a href="/django/django/commits/" class="selected tabnav-tab" highlight="repo_commits">Commits</a></li>
<li><a href="/django/django/branches" class="tabnav-tab" highlight="repo_branches" rel="nofollow">Branches <span class="counter ">37</span></a></li>
</ul>
</div>
</div>
</div><!-- /.repohead -->
<div id="js-repo-pjax-container" class="container context-loader-container" data-pjax-container>
<div class="commit full-commit ">
<a href="/django/django/tree/d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e" class="browse-button" title="Browse the code at this point in the history" rel="nofollow">Browse code</a>
<p class="commit-title">
Improved regex in strip_tags
</p>
<div class="commit-desc"><pre>Thanks Pablo Recio for the report. Refs #19237.</pre></div>
<div class="commit-meta clearfix">
<span class="sha-block">commit <span class="sha js-selectable-text">d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e</span></span>
<span class="sha-block" data-pjax>
1 parent
<a href="/django/django/commit/afa3e1633431137f4e76c7efc359b579f4d9c08e" class="sha" data-hotkey="p">afa3e16</a>
</span>
<div class="authorship">
<img class="gravatar" height="24" src="https://secure.gravatar.com/avatar/cf4198670f0073174b475634964b576b?s=140&d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="24" />
<span class="author-name"><a href="/claudep" rel="author">claudep</a></span>
authored <time class="js-relative-date" datetime="2013-02-06T12:20:43-08:00" title="2013-02-06 12:20:43">February 06, 2013</time>
</div>
</div>
</div>
<a name="diff-stat"></a>
<div id='toc' class="details-collapse js-details-container ">
<p class="explain">
<span class="mini-icon mini-icon-diff"></span>Showing <strong>2 changed files</strong>
with <strong>2 additions</strong>
and <strong>1 deletion</strong>.
<a href="#" class="minibutton show-diff-stats js-details-target">Show Diff Stats</a>
<a href="#" class="minibutton hide-diff-stats js-details-target">Hide Diff Stats</a></p>
<ol class="content collapse js-transitionable">
<li>
<span class="diffstat">
<a href="#diff-0" class="tooltipped leftwards" title="1 addition & 1 deletion">
2
<span class="diffstat-bar"> <i class='plus'></i><i class='minus'></i> </span>
</a>
</span>
<span class='mini-icon mini-icon-modified' title='modified'></span> <a href="#diff-0">django/utils/html.py</a>
</li>
<li>
<span class="diffstat">
<a href="#diff-1" class="tooltipped leftwards" title="1 addition & 0 deletions">
1
<span class="diffstat-bar"> <i class='plus'></i> </span>
</a>
</span>
<span class='mini-icon mini-icon-modified' title='modified'></span> <a href="#diff-1">tests/regressiontests/utils/html.py</a>
</li>
</ol>
</div>
<div id="files" class="diff-view commentable">
<div id="diff-0" class="file js-details-container">
<div class="meta" data-path="django/utils/html.py">
<div class="info">
<span class="diffstat tooltipped rightwards" title="1 addition & 1 deletion">2 <span class="diffstat-bar"><i class='plus'></i><i class='minus'></i></span></span>
<span class="js-selectable-text css-truncate css-truncate-target" title="django/utils/html.py">
django/utils/html.py
</span>
</div>
<div class="actions">
<span class="show-inline-notes">
<label>
<input type="checkbox" checked="checked" class="js-show-inline-comments-toggle">
show inline notes
</label>
</span>
<div class="button-group">
<a href="/django/django/blob/d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e/django/utils/html.py" class="minibutton" rel="nofollow">View file @ <code>d7504a3</code></a>
</div>
</div>
</div>
<div class="data highlight ">
<table class="diff-table">
<tr id="django-utils-html-py-P0" data-position='0'>
<td id="L0L32" class="line_numbers linkable-line-number">
<span class="line-number-content">...</span>
</td>
<td id="L0R32" class="line_numbers linkable-line-number">
<span class="line-number-content">...</span>
</td>
<td class="gc diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=0&line=32"></b>
@@ -33,7 +33,7 @@
</td>
</tr>
<tr id="django-utils-html-py-P1" data-position='1'>
<td id="L0L33" class="line_numbers linkable-line-number">
<span class="line-number-content">33</span>
</td>
<td id="L0R33" class="line_numbers linkable-line-number">
<span class="line-number-content">33</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=1&line=33"></b>
html_gunk_re = re.compile(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
</td>
</tr>
<tr id="django-utils-html-py-P2" data-position='2'>
<td id="L0L34" class="line_numbers linkable-line-number">
<span class="line-number-content">34</span>
</td>
<td id="L0R34" class="line_numbers linkable-line-number">
<span class="line-number-content">34</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=2&line=34"></b>
hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join([re.escape(x) for x in DOTS]), re.DOTALL)
</td>
</tr>
<tr id="django-utils-html-py-P3" data-position='3'>
<td id="L0L35" class="line_numbers linkable-line-number">
<span class="line-number-content">35</span>
</td>
<td id="L0R35" class="line_numbers linkable-line-number">
<span class="line-number-content">35</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=3&line=35"></b>
trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z')
</td>
</tr>
<tr id="django-utils-html-py-P4" data-position='4'>
<td id="L0L36" class="line_numbers linkable-line-number">
<span class="line-number-content">36</span>
</td>
<td id="L0R35" class="line_numbers linkable-line-number empty-cell">
<span class="line-number-content"> </span>
</td>
<td class="gd diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=4&line=36"></b>
-strip_tags_re = re.compile(r'</?\S([^=<span class="x"></span>]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE)
</td>
</tr>
<tr id="django-utils-html-py-P5" data-position='5'>
<td id="L0L36" class="line_numbers linkable-line-number empty-cell">
<span class="line-number-content"> </span>
</td>
<td id="L0R36" class="line_numbers linkable-line-number">
<span class="line-number-content">36</span>
</td>
<td class="gi diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=5&line=36"></b>
+strip_tags_re = re.compile(r'</?\S([^=<span class="x">></span>]*=(\s*"[^"]*"|\s*\'[^\']*\'|\S*)|[^>])*?>', re.IGNORECASE)
</td>
</tr>
<tr id="django-utils-html-py-P6" data-position='6'>
<td id="L0L37" class="line_numbers linkable-line-number">
<span class="line-number-content">37</span>
</td>
<td id="L0R37" class="line_numbers linkable-line-number">
<span class="line-number-content">37</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=6&line=37"></b>
</td>
</tr>
<tr id="django-utils-html-py-P7" data-position='7'>
<td id="L0L38" class="line_numbers linkable-line-number">
<span class="line-number-content">38</span>
</td>
<td id="L0R38" class="line_numbers linkable-line-number">
<span class="line-number-content">38</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=7&line=38"></b>
</td>
</tr>
<tr id="django-utils-html-py-P8" data-position='8'>
<td id="L0L39" class="line_numbers linkable-line-number">
<span class="line-number-content">39</span>
</td>
<td id="L0R39" class="line_numbers linkable-line-number">
<span class="line-number-content">39</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=django/utils/html.py&position=8&line=39"></b>
def escape(text):
</td>
</tr>
</table>
</div>
<div class="file-comments-place-holder" data-path="django/utils/html.py"></div>
</div>
<div id="diff-1" class="file js-details-container">
<div class="meta" data-path="tests/regressiontests/utils/html.py">
<div class="info">
<span class="diffstat tooltipped rightwards" title="1 addition & 0 deletions">1 <span class="diffstat-bar"><i class='plus'></i></span></span>
<span class="js-selectable-text css-truncate css-truncate-target" title="tests/regressiontests/utils/html.py">
tests/regressiontests/utils/html.py
</span>
</div>
<div class="actions">
<span class="show-inline-notes">
<label>
<input type="checkbox" checked="checked" class="js-show-inline-comments-toggle">
show inline notes
</label>
</span>
<div class="button-group">
<a href="/django/django/blob/d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e/tests/regressiontests/utils/html.py" class="minibutton" rel="nofollow">View file @ <code>d7504a3</code></a>
</div>
</div>
</div>
<div class="data highlight ">
<table class="diff-table">
<tr id="tests-regressiontests-utils-html-py-P0" data-position='0'>
<td id="L1L67" class="line_numbers linkable-line-number">
<span class="line-number-content">...</span>
</td>
<td id="L1R67" class="line_numbers linkable-line-number">
<span class="line-number-content">...</span>
</td>
<td class="gc diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=tests/regressiontests/utils/html.py&position=0&line=67"></b>
@@ -68,6 +68,7 @@ def test_strip_tags(self):
</td>
</tr>
<tr id="tests-regressiontests-utils-html-py-P1" data-position='1'>
<td id="L1L68" class="line_numbers linkable-line-number">
<span class="line-number-content">68</span>
</td>
<td id="L1R68" class="line_numbers linkable-line-number">
<span class="line-number-content">68</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=tests/regressiontests/utils/html.py&position=1&line=68"></b>
('a<p onclick="alert(\'<test>\')">b</p>c', 'abc'),
</td>
</tr>
<tr id="tests-regressiontests-utils-html-py-P2" data-position='2'>
<td id="L1L69" class="line_numbers linkable-line-number">
<span class="line-number-content">69</span>
</td>
<td id="L1R69" class="line_numbers linkable-line-number">
<span class="line-number-content">69</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=tests/regressiontests/utils/html.py&position=2&line=69"></b>
('a<p a >b</p>c', 'abc'),
</td>
</tr>
<tr id="tests-regressiontests-utils-html-py-P3" data-position='3'>
<td id="L1L70" class="line_numbers linkable-line-number">
<span class="line-number-content">70</span>
</td>
<td id="L1R70" class="line_numbers linkable-line-number">
<span class="line-number-content">70</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=tests/regressiontests/utils/html.py&position=3&line=70"></b>
('d<a:b c:d>e</p>f', 'def'),
</td>
</tr>
<tr id="tests-regressiontests-utils-html-py-P4" data-position='4'>
<td id="L1L70" class="line_numbers linkable-line-number empty-cell">
<span class="line-number-content"> </span>
</td>
<td id="L1R71" class="line_numbers linkable-line-number">
<span class="line-number-content">71</span>
</td>
<td class="gi diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=tests/regressiontests/utils/html.py&position=4&line=71"></b>
+ ('<strong>foo</strong><a href="http://example.com">bar</a>', 'foobar'),
</td>
</tr>
<tr id="tests-regressiontests-utils-html-py-P5" data-position='5'>
<td id="L1L71" class="line_numbers linkable-line-number">
<span class="line-number-content">71</span>
</td>
<td id="L1R72" class="line_numbers linkable-line-number">
<span class="line-number-content">72</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=tests/regressiontests/utils/html.py&position=5&line=72"></b>
)
</td>
</tr>
<tr id="tests-regressiontests-utils-html-py-P6" data-position='6'>
<td id="L1L72" class="line_numbers linkable-line-number">
<span class="line-number-content">72</span>
</td>
<td id="L1R73" class="line_numbers linkable-line-number">
<span class="line-number-content">73</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=tests/regressiontests/utils/html.py&position=6&line=73"></b>
for value, output in items:
</td>
</tr>
<tr id="tests-regressiontests-utils-html-py-P7" data-position='7'>
<td id="L1L73" class="line_numbers linkable-line-number">
<span class="line-number-content">73</span>
</td>
<td id="L1R74" class="line_numbers linkable-line-number">
<span class="line-number-content">74</span>
</td>
<td class=" diff-line line">
<b class="add-bubble mini-icon mini-icon-add-comment" data-remote="/django/django/commit_comment/form?commit_id=d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e&path=tests/regressiontests/utils/html.py&position=7&line=74"></b>
self.check_output(f, value, output)
</td>
</tr>
</table>
</div>
<div class="file-comments-place-holder" data-path="tests/regressiontests/utils/html.py"></div>
</div>
</div>
<div id="all_commit_comments">
<h2 class="commit-comments-header">
0 notes
on commit <code class="commit-comments-header-sha">d7504a3</code>
<span class="commit-comments-toggle-line-notes-wrapper"><label><input id="js-inline-comments-toggle" class="commit-comments-toggle-line-notes" type="checkbox">Show line notes below</label></span>
</h2>
<div id="comments" class="only-commit-comments comment-holder commit-comments">
</div>
<div class="discussion-bubble js-comment-container">
<img class="discussion-bubble-avatar" height="48" src="https://secure.gravatar.com/avatar/cf4198670f0073174b475634964b576b?s=140&d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="48" />
<form accept-charset="UTF-8" action="/django/django/commit_comment/create" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="Vbmuc30dLLFdm7POIe3xfTa4nODYc/la/wLrI1OLEOI=" /></div>
<div class="discussion-bubble-content bubble">
<div class="discussion-bubble-inner">
<input type='hidden' name='commit_id' value='d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e'>
<div class="js-previewable-comment-form previewable-comment-form write-selected" data-preview-url="/preview?repository=4164482">
<div class="comment-form-head tabnav">
<ul class="tabnav-tabs">
<li><a href="#write_bucket_525" class="tabnav-tab write-tab js-write-tab selected">Write</a></li>
<li><a href="#preview_bucket_525" class="tabnav-tab preview-tab js-preview-tab">Preview</a></li>
</ul>
<span class="tabnav-right">
<span class="tabnav-widget text">Comments are parsed with <a href="http://github.github.com/github-flavored-markdown/" class="gfm-help" target="_blank">GitHub Flavored Markdown</a></span>
</span>
</div>
<div class="comment-form-error js-comment-form-error" style="display:none;"></div>
<div id="write_bucket_525" class="write-content js-write-bucket js-uploadable-container upload-enabled is-default" data-model="asset">
<a href="#fullscreen_comment_body_525" class="enable-fullscreen js-enable-fullscreen tooltipped
leftwards " title="Zen Mode">
<span class="mini-icon mini-icon-fullscreen"></span>
</a>
<textarea name="comment[body]"
tabindex="2"
id="comment_body_525"
placeholder="Leave a comment"
class="js-comment-field js-size-to-fit input-with-fullscreen-icon"
data-suggester="525_new_preview_suggester"
required></textarea>
<p class="drag-and-drop">
<span class="default">
Attach images by dragging & dropping them or
<input type="file" multiple="multiple" class="manual-file-chooser js-manual-file-chooser">
<a class="manual-file-chooser-text" href="#">choose an image</a>
</span>
<span class="loading">
<img alt="Octocat-spinner-32" height="16" src="https://a248.e.akamai.net/assets.github.com/images/spinners/octocat-spinner-32.gif?1338945075" width="16" /> Uploading your images now…
</span>
<span class="error bad-file">
Unfortunately we don't support that file type yet. Try image files less than 5MB.
</span>
<span class="error bad-browser">
This browser doesn't support image attachments.
</span>
<span class="error failed-request">
Something went really wrong and we can't process that image.
</span>
</p>
</div>
<div id="preview_bucket_525" class="preview-content js-preview-bucket">
<div id="openstruct-163168300" class="js-comment comment">
<div class="comment-header normal-comment-header">
<img class="comment-header-gravatar" height="22" src="https://secure.gravatar.com/avatar/cf4198670f0073174b475634964b576b?s=140&d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png" width="22" />
<a href="/claudep" class="comment-header-author">claudep</a>
<span class='comment-header-action-text'>
<a href="#openstruct-163168300">
commented
</a>
</span>
<span class="comment-header-right">
<a href="#openstruct-163168300" class="comment-header-date"><time class="js-relative-date" datetime="2013-04-01T06:45:26-07:00" title="2013-04-01 06:45:26">April 01, 2013</time></a>
</span>
</div> <!-- /.comment-header -->
<div class="comment-content">
<div class="edit-comment-hide">
<div class="js-comment-body comment-body markdown-body " data-body-version="">
<p>Nothing to preview</p>
</div>
</div>
</div> <!-- /.comment-content -->
</div> <!-- /.comment -->
</div>
<div class="suggester-container">
<div class="suggester js-navigation-container" id="525_new_preview_suggester"
data-url="/django/django/suggestions/commit">
</div>
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="tip">
<img alt="Commit_comment_tip" height="35" src="https://a248.e.akamai.net/assets.github.com/images/modules/commit/commit_comment_tip.gif?1347524281" width="95" />
<p><strong>Tip:</strong> You can also add notes to lines in a file. Hover to the left of a line to make a note</p>
</div>
<button type="submit" class="button primary" tabindex="2" data-disable-invalid data-disable-with>Comment on this commit</button>
</div>
</form> </div><!-- /.discussion-bubble -->
</div>
<div class="thread-subscription-status clearfix">
<span class="mega-icon mega-icon-notifications"></span>
<div class="select-menu js-menu-container js-select-menu">
<form accept-charset="UTF-8" action="/notifications/thread" data-autosubmit="true" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="authenticity_token" type="hidden" value="Vbmuc30dLLFdm7POIe3xfTa4nODYc/la/wLrI1OLEOI=" /></div> <input id="repository_id" name="repository_id" type="hidden" value="4164482" />
<input id="thread_id" name="thread_id" type="hidden" value="d7504a3d7b8645bdb979bab7ded0e9a9b6dccd0e" />
<input id="thread_class" name="thread_class" type="hidden" value="c" />
<span class="minibutton select-menu-button js-menu-target">
<span class="js-select-button">
<span class="mini-icon mini-icon-watching"></span>
Watch thread
</span>
</span>
<div class="select-menu-modal-holder js-menu-content js-navigation-container">
<div class="select-menu-modal">
<div class="select-menu-header">
<span class="select-menu-title">Thread notifications</span>
<span class="mini-icon mini-icon-remove-close js-menu-close"></span>
</div> <!-- /.select-menu-header -->
<div class="select-menu-list">
<div class="select-menu-item js-navigation-item js-navigation-target selected">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<div class="select-menu-item-text">
<input checked="checked" id="id_unsubscribe" name="id" type="radio" value="unsubscribe" />
<h4>Not watching</h4>
<span class="description">You only receive notifications for this thread if you participate or are @mentioned.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="mini-icon mini-icon-watching"></span>
Watch thread
</span>
</div>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<div class="select-menu-item-text">
<input checked="checked" id="id_subscribe" name="id" type="radio" value="subscribe" />
<h4>Watching</h4>
<span class="description">Receive all notifications for this thread.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="mini-icon mini-icon-unwatch"></span>
Unwatch thread
</span>
</div>
</div> <!-- /.select-menu-item -->
<div class="select-menu-item js-navigation-item js-navigation-target ">
<span class="select-menu-item-icon mini-icon mini-icon-confirm"></span>
<div class="select-menu-item-text">
<input checked="checked" id="id_mute" name="id" type="radio" value="mute" />
<h4>Ignoring</h4>
<span class="description">You do not receive notifications for this thread.</span>
<span class="js-select-button-text hidden-select-button-text">
<span class="mini-icon mini-icon-mute ignored"></span>
Stop ignoring thread
</span>
</div>
</div> <!-- /.select-menu-item -->
</div> <!-- /.select-menu-list -->
</div> <!-- /.select-menu-modal -->
</div> <!-- /.select-menu-modal-holder -->
</form> </div> <!-- /.select-menu -->
<p class="reason">You only receive notifications for this thread when you participate or are @mentioned.</p>
</div>
<!-- COMMENTS -->
<div id='diff-comment-data' style='display:none'>
</div>
</div>
</div>
<div class="context-overlay"></div>
</div>
<div id="footer-push"></div><!-- hack for sticky footer -->
</div><!-- end of wrapper - hack for sticky footer -->
<!-- footer -->
<div id="footer">
<div class="container clearfix">
<dl class="footer_nav">
<dt>GitHub</dt>
<dd><a href="https://github.com/about">About us</a></dd>
<dd><a href="https://github.com/blog">Blog</a></dd>
<dd><a href="https://github.com/contact">Contact & support</a></dd>
<dd><a href="http://enterprise.github.com/">GitHub Enterprise</a></dd>
<dd><a href="http://status.github.com/">Site status</a></dd>
</dl>
<dl class="footer_nav">
<dt>Applications</dt>
<dd><a href="http://mac.github.com/">GitHub for Mac</a></dd>
<dd><a href="http://windows.github.com/">GitHub for Windows</a></dd>
<dd><a href="http://eclipse.github.com/">GitHub for Eclipse</a></dd>
<dd><a href="http://mobile.github.com/">GitHub mobile apps</a></dd>
</dl>
<dl class="footer_nav">
<dt>Services</dt>
<dd><a href="http://get.gaug.es/">Gauges: Web analytics</a></dd>
<dd><a href="http://speakerdeck.com">Speaker Deck: Presentations</a></dd>
<dd><a href="https://gist.github.com">Gist: Code snippets</a></dd>
<dd><a href="http://jobs.github.com/">Job board</a></dd>
</dl>
<dl class="footer_nav">
<dt>Documentation</dt>
<dd><a href="http://help.github.com/">GitHub Help</a></dd>
<dd><a href="http://developer.github.com/">Developer API</a></dd>
<dd><a href="http://github.github.com/github-flavored-markdown/">GitHub Flavored Markdown</a></dd>
<dd><a href="http://pages.github.com/">GitHub Pages</a></dd>
</dl>
<dl class="footer_nav">
<dt>More</dt>
<dd><a href="http://training.github.com/">Training</a></dd>
<dd><a href="https://github.com/edu">Students & teachers</a></dd>
<dd><a href="http://shop.github.com">The Shop</a></dd>
<dd><a href="/plans">Plans & pricing</a></dd>
<dd><a href="http://octodex.github.com/">The Octodex</a></dd>
</dl>
<hr class="footer-divider">
<p class="right">© 2013 <span title="0.09734s from fe2.rs.github.com">GitHub</span>, Inc. All rights reserved.</p>
<a class="left" href="https://github.com/">
<span class="mega-icon mega-icon-invertocat"></span>
</a>
<ul id="legal">
<li><a href="https://github.com/site/terms">Terms of Service</a></li>
<li><a href="https://github.com/site/privacy">Privacy</a></li>
<li><a href="https://github.com/security">Security</a></li>
</ul>
</div><!-- /.container -->
</div><!-- /.#footer -->
<div class="fullscreen-overlay js-fullscreen-overlay" id="fullscreen_overlay">
<div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
<textarea name="fullscreen-contents" id="fullscreen-contents" class="js-fullscreen-contents" placeholder="" data-suggester="fullscreen_suggester"></textarea>
<div class="suggester-container">
<div class="suggester fullscreen-suggester js-navigation-container" id="fullscreen_suggester"
data-url="/django/django/suggestions/commit">
</div>
</div>
</div>
</div>
<div class="fullscreen-sidebar">
<a href="#" class="exit-fullscreen js-exit-fullscreen tooltipped leftwards" title="Exit Zen Mode">
<span class="mega-icon mega-icon-normalscreen"></span>
</a>
<a href="#" class="theme-switcher js-theme-switcher tooltipped leftwards"
title="Switch themes">
<span class="mini-icon mini-icon-brightness"></span>
</a>
</div>
</div>
<div id="ajax-error-message" class="flash flash-error">
<span class="mini-icon mini-icon-exclamation"></span>
Something went wrong with that request. Please try again.
<a href="#" class="mini-icon mini-icon-remove-close ajax-error-dismiss"></a>
</div>
<span id='server_response_time' data-time='0.09780' data-host='fe2'></span>
</body>
</html>
| {'content_hash': '037f02f153d7a3d0f0b887b64f7268f7', 'timestamp': '', 'source': 'github', 'line_count': 1302, 'max_line_length': 370, 'avg_line_length': 65.81720430107526, 'alnum_prop': 0.6064251872943264, 'repo_name': 'atruberg/django-custom', 'id': '8e9ee1d8fddc4edbdd5933ffb2f9ce28be43dc15', 'size': '85704', 'binary': False, 'copies': '61', 'ref': 'refs/heads/master', 'path': 'tests/utils_tests/files/strip_tags1.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '51013'}, {'name': 'JavaScript', 'bytes': '98272'}, {'name': 'Python', 'bytes': '8636914'}, {'name': 'Shell', 'bytes': '12135'}]} |
<?php
namespace Gregwar\Tex2pngBundle\Services;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Tex2png service
*
* @author Gregwar <[email protected]>
*/
class Tex2pngService
{
protected $cache_dir;
protected $handler_class;
protected $container;
public function __construct($cache_dir, $handler_class, ContainerInterface $container)
{
$this->cache_dir = $cache_dir;
$this->handler_class = $handler_class;
$this->container = $container;
}
/**
* Create a PNG image from a LaTeX formula
*
* @param $tex the LaTeX formula
* @param $density the density (resolution)
*
* @return object a tex2png object
*/
public function create($tex, $density = 155)
{
$asset = $this->container->get('templating.helper.assets');
$handler_class = $this->handler_class;
$tex2png = new $handler_class($tex, $density);
$tex2png->setCacheDirectory($this->cache_dir);
$tex2png->setFileCallback(function($file) use ($asset) {
return $asset->getUrl($file);
});
return $tex2png;
}
}
| {'content_hash': 'e07d48b114487906d0a6326ff7583a43', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 90, 'avg_line_length': 24.104166666666668, 'alnum_prop': 0.6188418323249784, 'repo_name': 'Gregwar/Tex2pngBundle', 'id': '90002ac6d08e237018ff2f1b18925764f5aa527b', 'size': '1157', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Services/Tex2pngService.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '10187'}]} |
package com.michaelfotiadis.validator.annotated.validators.text;
import java.util.regex.Pattern;
/**
*
*/
public final class TextNumericValidatorHelper {
private static final String EXPRESSION = "-?\\d+([.]\\d+)?";
private static final Pattern PATTERN = Pattern.compile(EXPRESSION);
private TextNumericValidatorHelper() {
// do not instantiate
}
public static boolean isNumeric(final String input) {
if (input == null) {
return false;
} else {
return PATTERN.matcher(input).matches();
}
}
}
| {'content_hash': 'bbda9fbf194022a45657ce91e38e124e', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 71, 'avg_line_length': 22.307692307692307, 'alnum_prop': 0.6344827586206897, 'repo_name': 'MikeFot/java-lib-annotated-validator', 'id': 'bab1c95a5a4f336f612b1477e1dd35854c88278d', 'size': '580', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/michaelfotiadis/validator/annotated/validators/text/TextNumericValidatorHelper.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '198527'}]} |
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<!--[if lt IE 9]>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<![endif]-->
<script src="../bower_components/angular/angular.js"></script>
<script src="../dist/ng-table.js"></script>
<link rel="stylesheet" href="../dist/ng-table.css">
</head>
<body ng-app="main">
<h1>Multiple tables per page</h1>
<div ng-controller="DemoCtrl">
<div class="row">
<div class="col col-sm-6">
<h2>Table #1</h2>
<p><strong>Filter:</strong> {{tableParams.filter()|json}}
<table ng-table="tableParams" show-filter="true" class="table">
<tr ng-repeat="user in $data">
<td data-title="'Name'" filter="{ 'name': 'text' }">
{{user.name}}
</td>
<td data-title="'Age'">
{{user.age}}
</td>
</tr>
</table>
</div>
<div class="col col-sm-6">
<h2>Table #2</h2>
<p><strong>Filter:</strong> {{tableParams2.filter()|json}}
<table ng-table="tableParams2" show-filter="true" class="table">
<tr ng-repeat="user in $data">
<td data-title="'Name'" filter="{ 'name': 'text' }">
{{user.name}}
</td>
<td data-title="'Age'">
{{user.age}}
</td>
</tr>
</table>
</div>
</div>
<script>
var app = angular.module('main', ['ngTable'])
.controller('DemoCtrl', function($scope, NgTableParams, $filter) {
var data = [{name: "Moroni", age: 50},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34},
{name: "Tiancum", age: 43},
{name: "Jacob", age: 27},
{name: "Nephi", age: 29},
{name: "Enos", age: 34}];
// params for table #1
$scope.tableParams = new NgTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: data.length, // length of data
getData: function($defer, params) {
// use built-in angular filter
var orderedData = params.sorting() ?
$filter('orderBy')(data, params.orderBy()) :
data;
orderedData = params.filter() ?
$filter('filter')(orderedData, params.filter()) :
orderedData;
params.total(orderedData.length);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
// params for table #2
$scope.tableParams2 = new NgTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: data.length, // length of data
getData: function($defer, params) {
// use built-in angular filter
var orderedData = params.sorting() ?
$filter('orderBy')(data, params.orderBy()) :
data;
orderedData = params.filter() ?
$filter('filter')(orderedData, params.filter()) :
orderedData;
params.total(orderedData.length);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
});
</script>
</div>
</body>
</html>
| {'content_hash': '072fd0eeba95278c0ed538bd83c6efb8', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 132, 'avg_line_length': 42.304, 'alnum_prop': 0.4003403933434191, 'repo_name': 'enkodellc/ng-table', 'id': 'bb524122d7bba3e411c68de936416ed4c97a709f', 'size': '5288', 'binary': False, 'copies': '22', 'ref': 'refs/heads/master', 'path': 'examples/demo19.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '12090'}, {'name': 'HTML', 'bytes': '179519'}, {'name': 'JavaScript', 'bytes': '335229'}]} |
/* Engine.js
* This file provides the game loop functionality (update entities and render),
* draws the initial game board on the screen, and then calls the update and
* render methods on your player and enemy objects (defined in your app.js).
*
* A game engine works by drawing the entire game screen over and over, kind of
* like a flipbook you may have created as a kid. When your player moves across
* the screen, it may look like just that image/character is moving or being
* drawn but that is not the case. What's really happening is the entire "scene"
* is being drawn over and over, presenting the illusion of animation.
*
* This engine is available globally via the Engine variable and it also makes
* the canvas' context (ctx) object globally available to make writing app.js
* a little simpler to work with.
*/
function difficulty(skill){
// numOfEnemies establishes the approx number of enemies that are on the screen at one time.
// This should be set by selecting a difficulty on a modal window that pops up when the
// game is launched.
console.log("The current value of skill is: "+skill);
if (skill === "easy") {
numOfEnemies = 3;
}
if (skill === "medium") {
numOfEnemies = 5;
}
if (skill === "hard") {
numOfEnemies = 7;
}
//console.log("The current value of numOfEnemies is: "+numOfEnemies);
var generatedEnemies = (numOfEnemies*2);
for (var i = 0; i < generatedEnemies; i++) {
allEnemies.push(new Enemy());
}
launch();
}
// Wrapped Engine in a function named launch so that I can delay the Engine function call until the player selects a difficulty
function launch() {
var Engine = (function(global) {
/* Predefine the variables we'll be using within this scope,
* create the canvas element, grab the 2D context for that canvas
* set the canvas elements height/width and add it to the DOM.
*/
var doc = global.document,
win = global.window,
canvas = doc.createElement('canvas'),
ctx = canvas.getContext('2d'),
lastTime;
canvas.width = 505;
canvas.height = 606;
doc.body.appendChild(canvas);
/* This function serves as the kickoff point for the game loop itself
* and handles properly calling the update and render methods.
*/
function main() {
/* Get our time delta information which is required if your game
* requires smooth animation. Because everyone's computer processes
* instructions at different speeds we need a constant value that
* would be the same for everyone (regardless of how fast their
* computer is) - hurray time!
*/
var now = Date.now(),
dt = (now - lastTime) / 1000.0;//dt = (now - lastTime) / 1000.0;
/* Call our update/render functions, pass along the time delta to
* our update function since it may be used for smooth animation.
*/
update(dt);
render();
/* Set our lastTime variable which is used to determine the time delta
* for the next time this function is called.
*/
lastTime = now;
/* Use the browser's requestAnimationFrame function to call this
* function again as soon as the browser is able to draw another frame.
*/
win.requestAnimationFrame(main);
}
/* This function does some initial setup that should only occur once,
* particularly setting the lastTime variable that is required for the
* game loop.
*/
function init() {
reset();
lastTime = Date.now();
main();
}
/* This function is called by main (our game loop) and itself calls all
* of the functions which may need to update entity's data. Based on how
* you implement your collision detection (when two entities occupy the
* same space, for instance when your character should die), you may find
* the need to add an additional function call here. For now, we've left
* it commented out - you may or may not want to implement this
* functionality this way (you could just implement collision detection
* on the entities themselves within your app.js file).
*/
function update(dt) {
ctx.font = "24px Arial";
ctx.fillStyle = "#65c84e";
ctx.fillText("Score: "+score, 10, 40);
ctx.fillText("Lives: "+lives, 415, 40);
function pauseMessage() {
ctx.font = "18px Arial";
ctx.fillStyle = "#d24a1d";
ctx.fillText("Press 'P' to pause", 180, 40);
ctx.font = "24px Arial";
ctx.fillStyle = "#65c84e";
}
pauseMessage();
if (gamePaused === false) {
updateEntities(dt);
checkCollisions();
}
// Thank you to the udacity forums for giving me an idea on how to pause my game as needed:
// https://discussions.udacity.com/t/how-to-pause-the-game/190398
}
/* This is called by the update function and loops through all of the
* objects within your allEnemies array as defined in app.js and calls
* their update() methods. It will then call the update function for your
* player object. These update methods should focus purely on updating
* the data/properties related to the object. Do your drawing in your
* render methods.
*/
function updateEntities(dt) {
allEnemies.forEach(function(enemy) {
enemy.update(dt);
});
player.update();
}
/* This function initially draws the "game level", it will then call
* the renderEntities function. Remember, this function is called every
* game tick (or loop of the game engine) because that's how games work -
* they are flipbooks creating the illusion of animation but in reality
* they are just drawing the entire screen over and over.
*/
function render() {
/* This array holds the relative URL to the image used
* for that particular row of the game level.
*/
var rowImages = [
'images/water-block.png', // Top row is water
'images/stone-block.png', // Row 1 of 3 of stone
'images/stone-block.png', // Row 2 of 3 of stone
'images/stone-block.png', // Row 3 of 3 of stone
'images/grass-block.png', // Row 1 of 2 of grass
'images/grass-block.png' // Row 2 of 2 of grass
],
numRows = 6,
numCols = 5,
row, col;
/* Loop through the number of rows and columns we've defined above
* and, using the rowImages array, draw the correct image for that
* portion of the "grid"
*/
for (row = 0; row < numRows; row++) {
for (col = 0; col < numCols; col++) {
/* The drawImage function of the canvas' context element
* requires 3 parameters: the image to draw, the x coordinate
* to start drawing and the y coordinate to start drawing.
* We're using our Resources helpers to refer to our images
* so that we get the benefits of caching these images, since
* we're using them over and over.
*/
ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 83);
}
}
renderEntities();
}
/* This function is called by the render function and is called on each game
* tick. Its purpose is to then call the render functions you have defined
* on your enemy and player entities within app.js
*/
function renderEntities() {
/* Loop through all of the objects within the allEnemies array and call
* the render function you have defined.
*/
allEnemies.forEach(function(enemy) {
enemy.render();
});
player.render();
}
/* This function does nothing but it could have been a good place to
* handle game reset states - maybe a new game menu or a game over screen
* those sorts of things. It's only called once by the init() method.
*/
function reset() {
// noop
}
/* Go ahead and load all of the images we know we're going to need to
* draw our game level. Then set init as the callback method, so that when
* all of these images are properly loaded our game will start.
*/
Resources.load([
'images/stone-block.png',
'images/water-block.png',
'images/grass-block.png',
'images/enemy-bug.png',
'images/char-boy.png',
'images/char-boy-dead.png'
]);
Resources.onReady(init);
/* Assign the canvas' context object to the global variable (the window
* object when run in a browser) so that developers can use it more easily
* from within their app.js files.
*/
global.ctx = ctx;
})(this);//});//
};
| {'content_hash': '63260ca32951b876ad673487bff40784', 'timestamp': '', 'source': 'github', 'line_count': 235, 'max_line_length': 128, 'avg_line_length': 41.297872340425535, 'alnum_prop': 0.5766099948480164, 'repo_name': 'GBClemson/Udacity-FEND-Classic-Game', 'id': 'dea86384d3f7dc26fbd4422effee0feeb6a5099d', 'size': '9705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/engine.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1592'}, {'name': 'HTML', 'bytes': '5514'}, {'name': 'JavaScript', 'bytes': '27819'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<!--© The Office of the High Commisioner for Human Rights-->
<udhr iso639-3='bre' xml:lang='br' key='bre' n='Breton' xmlns="http://www.unhchr.ch/udhr">
<title>DISKLERIADUR HOLLVEDEL GWIRIOU MAB-DEN</title>
<note>
<para>Embannet gant ar Broadou-Unanet d’an 10 a viz Kerzu 1948</para>
</note>
<preamble>
<title>Rakger</title>
<para>–O vezañ ma’z eo war anaout an dellezegezh enstag ouzh holl izili an denelezh hag o gwirioù par ha diwerzhus eo diazezet ar frankiz, ar reizhded hag ar peoc’h,</para>
<para>–o vezañ ma’z eo war dizanaout ha dismegañsiñ gwirioù mab-den eo bet ganet an aktoù a varbariezh a sav koustiañs mab-den en o enep, ha ma’z eo bet embannet eo donedigezh ur bed a vo ennañ gant an dud frankiz da gomz ha da grediñ, dieubet ma vint diouzh ar spont hag an dienez, a zo mennad uhelañ mab-den,</para>
<para>–o vezañ ma’z eo ret-holl diwall gwirioù mabden gant reolenn al lezenn evit na vefe ket rediet an dud d’en em sevel ouzh an tirantegezh hag ar gwaskerezh da rekour diwezhañ,</para>
<para>–o vezañ ma’z eo ret-holl kas war-raok an darempredoù a vignoniezh etre ar broadoù,</para>
<para>–o vezañ ma’z eo bet embannet adarre er Garta gant pobloù ar Broadoù-Unanet o feiz e gwirioù diazez mab-den, e dellezegezh ha talvoudegezh mab-den, e parded ar baotred hag ar merc’hed en o gwirioù, ha ma’z eo bet disklêriet ganto e oant mennet da gas war-raok an diorroadur kevredigezhel ha da wellaat an aozioù-buhez en ur frankiz vrasoc’h,</para>
<para>-o vezañ ma’z eo bet gouestlet gant ar Stadoù-Ezel diogeliñ, gant kenlabour Aozadur ar Broadoù-Unanet, an doujañs hollvedel ha gwirion ouzh gwirioù mab-den hag ar frankizioù pennan,</para>
<para>–hago vezañ ma’z eo a bouez bras kengompren ar gwirioù hag ar frankizioù-mañ a-benn seveniñ ar gouestl,</para>
<para>EZ EMBANN</para>
<para>AR VODADEG-VEUR</para>
<para>DISKLERIADUR HOLLVEDEL GWIRIOÙ MABDEN</para>
<para>evel uhelvennad boutin da vezañ diraezet gant an holl bobloù hag an holl vroadoù, d’an holl dud hag ensavadurioù, gant an Disklêriadur-mañ atav en o freder, da lakaat kreskiñ dre ar c’helenn hag an deskadurezh, an doujans ouzh ar gwirioù ha frankizioù-mañ, d’o lakaat da vezañ anavezet ha sevenet tamm-ha-tamm da vat hag e pep lec’h, dre ziarbennoù broadel hag etrevroadel, koulz e-touez pobloù ar Stadoù-Ezel hag e-touez ar re zo war zouaroù dindan o lezennoù.</para>
</preamble>
<article number="1">
<title>Mellad unan (1)</title>
<para>Dieub ha par en o dellezegezh hag o gwirioù eo ganet an holl dud. Poell ha skiant zo dezho ha dleout a reont bevañ an eil gant egile en ur spered a genvreudeuriezh.</para>
</article>
<article number="2">
<title>Mellad daou (2)</title>
<para>Da bep hini eo an holl wirioù ha frankizioù embannet en disklêriadur-mañ, hep ket a ziforc’h, a ouenn, a liv, a reizh, a yezh, a veno politikel pe a veno all, a orin broadel pe gevredigezhel, a leve, a c’hanedigezh pe a natur all.</para>
<para>Ouzhpenn-se ne vo graet diforc’h ebet hervez statud politikel, lezennel pe etrevroadel, arvro pe an dachenn-vro emañ an den dindan he lezenn, pe dizalc’h pe dindan verezeh e ve, diemren pe bevennet hec’h aotrouniezh en ur stumm bennak.</para>
</article>
<article number="3">
<title>Mellad tri (3)</title>
<para>Gwir a zo gant pep hini d’ar vuhez, d’ar frankiz, ha d’an diogelroez evitañ.</para>
</article>
<article number="4">
<title>Mellad peuar (4)</title>
<para>Ne vo dalc’het den er sklaverezh nag er sujidigezh; berzet e vo kement stumm a sklaverezh hag a werzhañ-sklaved.</para>
</article>
<article number="5">
<title>Mellad pemp (5)</title>
<para>Ne vo lakaet den da c’houzañv ar jahinerezh, na doareoù pe kastizoù kriz ha didruez.</para>
</article>
<article number="6">
<title>Mellad c’hwec’h (6)</title>
<para>Gwir pep hini eo e vefe anavezet e bersonelezh lezennel e pep lec’h.</para>
</article>
<article number="7">
<title>Mellad seizh (7)</title>
<para>Par eo an holl dirak al lezenn ha gwir o deus da vezañ diwallet ganti. Holl o deus gwir da vezañ diwallet heñvel diouzh kement gwallziforc’h a dorrfe an Disklêriadur-mañ ha diouzh kement tra a zegasfe seurt diforc’hioù.</para>
</article>
<article number="8">
<title>Mellad eizh (8)</title>
<para>Pep hini en deus gwir da gaout digoll gwirion dirak lezioù-barn broadel kenveliek evit oberoù o dije torret ar gwirioù diazez anavezet dezhañ gant ar Vonreizh pa al lezenn.</para>
</article>
<article number="9">
<title>Mellad nav (9)</title>
<para>Den ebet ne vo harzet, bac’het pe harluet diouzh c’hoant.</para>
</article>
<article number="10">
<title>Mellad dek (10)</title>
<para>Ur gwir par da hini ar re all a zo gant pep hini da vezañ klevet dirak an holl ha gant reizhded gant ul lez-varn dizalc’h ha neptu, dezhi da dermenañ e wirioù ha dleadoù hag an tamalloù graet dezhañ.</para>
</article>
<article number="11">
<title>Mellad unnek (11)</title>
<orderedlist>
<listitem>
<para>Digablus eo kement den a zo tamallet dezhañ ur felladenn ken na vo prouet eo kablus hervez al lezenn en ur prosez digor d’an holl ma vo bet diogelet dezhañ an holl wareziou ret d’en em zifenn.</para>
</listitem>
<listitem>
<para>Ne vo kondaonet den ebet en abeg da oberoù pe da nannoberoù ha ne oant ket felladennoù hervez ar gwir broadel pe etrevroadel d’ar mare ma oant c’hoarvezet. Den kennebeut ne vo barnet d’ur c’hastiz kreñvoc’h eget an hini a oa hervez al lezenn d’ar mare ma oa bet graet ar felladenn.</para>
</listitem>
</orderedlist>
</article>
<article number="12">
<title>Mellad daouzek (12)</title>
<para>Den ebet ne vo emellet diouzh c’hoant en e vuhez prevez, e diegezh, e annez pe e lizhiri, ha ne vo ket stoket ouzh e enor nag ouzh e vrud. Pep hini en deus gwir da gaout gwarez digant al lezenn diouzh emelladennoù ha tagadennoù a seurt-se.</para>
</article>
<article number="13">
<title>Mellad trizek (13)</title>
<orderedlist>
<listitem>
<para>Pep den en deus gwir da vont ha dont en e frankiz ha da zibab e annez e diabarzh ur Stad.</para>
</listitem>
<listitem>
<para>Pep den en deus gwir da guitaat ne vern pe vro, da guitaat e vro-eñ zoken ha da zont en-dro dezhi.</para>
</listitem>
</orderedlist>
</article>
<article number="14">
<title>Mellad pevarzek (14)</title>
<orderedlist>
<listitem>
<para>Pep den en deus gwir da glask repu ha da gavout bod e broioù all pa vez heskinerezh.</para>
</listitem>
<listitem>
<para>Ar gwir-mañ n’haller ket daveiñ dezhañ pa vez klask war un den gant gwir abeg evit torfedoù a genwir pe evit oberoù kontrol da balioù ha pennaennoù ar Broadoù-Unanet.</para>
</listitem>
</orderedlist>
</article>
<article number="15">
<title>Mellad pemzek (15)</title>
<orderedlist>
<listitem>
<para>Pep den en deus gwir da gaout ur vroadelezh.</para>
</listitem>
<listitem>
<para>Den ebet ne vo tennet e vroadelezh digantañ nag ar gwir da gemmañ e vroadelezh diouzh c’hoant.</para>
</listitem>
</orderedlist>
</article>
<article number="16">
<title>Mellad c’hwezek (16)</title>
<orderedlist>
<listitem>
<para>Gwir o deus ar wazed hag ar merc’hed adalek an oad da zimeziñ, ne vern o gouenn, o broadelezh, pe o relijion, da zimeziñ ha da sevel tiegezh. Gwirioù par zo dezho e-keñver an dimeziñ, e-pad ar briedelezh hag e-keñver an dibriediñ.</para>
</listitem>
<listitem>
<para>Ne c’hell bezañ dimeziñ ebet hep asant gwir ha dieub an danvez-priedoù.</para>
</listitem>
<listitem>
<para>An tiegezh eo maen diazez naturel ar gevredigezh, ha gwir en deus da gaout gwarez ar gevredigezh hag ar Stad.</para>
</listitem>
</orderedlist>
</article>
<article number="17">
<title>Mellad seitek (17)</title>
<orderedlist>
<listitem>
<para>Pep den en deus gwir da vezañ perc’henn e-unan pe a-gevret gant tud all.</para>
</listitem>
<listitem>
<para>Den ebet ne vo tennet e berc’hentiezh digantañ diouzh c’hoant.</para>
</listitem>
</orderedlist>
</article>
<article number="18">
<title>Mellad triwec’h (18)</title>
<para>Pep den en deus gwir da gaout frankiz ar soñj, ar goustiañs hag ar relijion; er gwir-mañ emañ ivez ar frankiz da gemmañ e relijion pe e gredenn, hag ivez ar frankiz da ziskuliañ e relijion pe e gredenn, eunan pe a-stroll, dirak an holl pe en-prevez, dre ar c’helenn, an oberoù, an azeulerezh pe al liderezh.</para>
</article>
<article number="19">
<title>Mellad naontek (19)</title>
<para>Pep hini en deus gwir d’ar frankiz d’ober e veno ha d’en disklêriañ, da lavarout eo gwir da chom hep bezañ trubuilhet en abeg d’e vennozhioù, gwir da glask, da resev ha da skignañ keleier ha mennozhioù, dre n’eus forzh pe zoare disklêriañ, hep teurel pled ouzh an harzoù.</para>
</article>
<article number="20">
<title>Mellad ugent (20)</title>
<orderedlist>
<listitem>
<para>Pep den en deus gwir d’ar frankiz d’en em vodañ ha d’en em gevreañ e peoc’h.</para>
</listitem>
<listitem>
<para>Den ne c’hell bezañ rediet da vezañ ezel eus ur gevredigezh.</para>
</listitem>
</orderedlist>
</article>
<article number="21">
<title>Mellad unan warn-ugent (21)</title>
<orderedlist>
<listitem>
<para>Pep hini en deus gwir da gemer perzh e gouarnerezh e vro, war-eeun pe dre hantererezh dileuridi dibabet hep gwaskerezh.</para>
</listitem>
<listitem>
<para>Pep hini, par d’ar re al, en deus gwir da gaout kargoù publik en e vro.</para>
</listitem>
<listitem>
<para>Youl ar bobl eo diazez aotrouniezh ar galloud publik; disklêriet e vo ar youl-se e dilennadegoù onest ha mareadek gant mouezhierezh an holl, dre baperennoù kuzh pe dre zoareoù mouezhiañ kevatal o tiogeliñ frankiz ar vouezhiadeg.</para>
</listitem>
</orderedlist>
</article>
<article number="22">
<title>Mellad daou warn-ugent (22)</title>
<para>Pep den, evel ezel eus ar gevredigezh, en deus gwir d’ar c’hedskor ha da gaout e walc’h eus ar gwirioù armerzhel, kevredigezhel ha sevenadurel en deus ezhomm evit e zellezegezh ha diorroadur dinask e bersonelezh a-drugarez d’ar strivadeg vroadel ha d’ar c’henlabour etrevroadel, en ur zerc’hel kont eus aozadur ha pinvidigezh ar vro.</para>
</article>
<article number="23">
<title>Mellad tri warn-ugent (23)</title>
<orderedlist>
<listitem>
<para>Pep den en deus gwir da labourat, da zibab al labour a gar, da gaout aozioù labour reizh ha dereat, ha da vezañ gwarezet diouzh an dilabour.</para>
</listitem>
<listitem>
<para>Pep den en deus gwir, hep gwallziforc’h ebet, da gaout an hevelep gopr evit an hevelep labour.</para>
</listitem>
<listitem>
<para>An neb a labour en deus gwir da vezañ paeet reizh ha mat evit ma c’hellfe, eñ hag e diegezh, bevañ en un doare a zere ouzh dellezegezh mab-den, ha mar deo ret ouzhpenn, da gaout gwarez kevredigezhel dre hentoù all.</para>
</listitem>
<listitem>
<para>Pep den en deus gwir da sevel sindikadoù pe da emezelañ enno evit difenn e lazioù.</para>
</listitem>
</orderedlist>
</article>
<article number="24">
<title>Mellad pevar warn-ugent (24)</title>
<para>Pep hini en deus gwir da ziskuizhañ ha da gaout lezir, da gaout un amzer-labour bevennet poellek ha vakañsoù mareadek paeet.</para>
</article>
<article number="25">
<title>Mellad pemp warn-ugent (25)</title>
<orderedlist>
<listitem>
<para>Pep den en deus gwir da gaout ul live-bevañ dereat evit e yec’hed, e aezamant ha hini e diegezh da lavarout eo: boued, dilhad, lojeiz, skoazell ar vezegiezh hag ar servijoù kevredigezhel zo ezhomm; gwir en deus ivez d’an diogelroez ma c’hoarvez dezhañ bezañ dilabour, klañv, mac’hagnet, instañvet, kozh, pe koll an tu da gaout peadra da vevañ en desped dezhañ.</para>
</listitem>
<listitem>
<para>Ar mammoù hag ar vugale o deus gwir da gaout harp ha skoazell dreist an holl. An hol vugale, ganet eus tud dimezet pe dizimez, o devo ar emmes gwares kevredigezhel.</para>
</listitem>
</orderedlist>
</article>
<article number="26">
<title>Mellad c’hwec’h warn-ugent (26)</title>
<orderedlist>
<listitem>
<para>Pep den en deus gwir da gaout deskadurezh. Digoust e tle bezañ an deskadurezh, da vihanañ an deskadurezh kentañ ha diazez. Ret ha dleet eo ar gelennadurezh kentañ. D’an holl e tle bezañ kinniget ar gelennadurezh teknikel ha micherel, d’an holl e vo roet tu d’ober studioù uhel hervez o dellid.</para>
</listitem>
<listitem>
<para>Pal an deskadurezh eo diorren personelezh mab-den ha lakaat doujañ muioc’h gwirioù mab-den hag ar frankizioù diazez. Drezi e klaskor kreskiñ ar c’hengompren, an habaskted hag ar vignoniezh etre an holl vroadoù hag an holl strolladoù a ouenn pe a relijion disheñvel, hag ivez kas war-raok obererezh ar Broadoù-Unanet evit derc’hel ar peoc’h.</para>
</listitem>
<listitem>
<para>An tadoù ha mammoù, da gentañ, o deus gwir da zibab an doare deskadurezh a vo roet d’o bugale.</para>
</listitem>
</orderedlist>
</article>
<article number="27">
<title>Mellad seizh warn-ugent (27)</title>
<orderedlist>
<listitem>
<para>Pep hini en deus gwir da gemer perzh evel a gar e buhez sevenadurel ar gumuniezh, da gaout dudi gant an arzoù, da gemer perzh en araokadeg ar skiantoù ha da gaout e lod eus ar madoù degaset ganti.</para>
</listitem>
<listitem>
<para>Pep den en deus gwir da gaout e lazioù speredel ha danvezel deuet diwar an oberennoù skiantel, lennegel pe arzel savet gantañ.</para>
</listitem>
</orderedlist>
</article>
<article number="28">
<title>Mellad eizh warn-ugent (28)</title>
<para>Pep hini en deus gwir e renfe un urzh kevredigezhel hag etrevroadel a c’hellfe bezañ peursevenet enni ar gwirioù ha frankizioù embannet en Disklêriadur-mañ.</para>
</article>
<article number="29">
<title>Mellad nav warn-ugent (29)</title>
<orderedlist>
<listitem>
<para>Pep den en deus dleadoù e-keñver ar gevredigezh, al lec’h nemetañ ma c’hell peurziorren e bersonelezh en he frankiz.</para>
</listitem>
<listitem>
<para>En e wirioù hagen e frankiz ne c’hell pep hini bezañ bevennet nemet gant al lezenn ha nemet evit diogeliñ ma vo anavezet ha doujet gwirioù ha frankizioù ar re all hag evit klotañ gant ezhommoù reizh ar vuhezegezh, an urzh publik, hag aezamant an holl en ur gevredigezh demokratel.</para>
</listitem>
<listitem>
<para>Ar gwirioù ha frankizioù-mañ ne c’hellor, war zigarez ebet, ober ganto a-enep da balioù ha pennaennoù ar Broadoù-Unanet.</para>
</listitem>
</orderedlist>
</article>
<article number="30">
<title>Mellad tregont (30)</title>
<para>Pennad ebet eus an Disklêriadur-mañ ne c’hello bezañ komprenet evel pa rofe gwir d’ur Stad, d’ur strollad pe d’un den, da ober pe klask ober traoù abenn distrujañ ar gwirioù hag ar frankizioù embannet amañ.</para>
</article>
</udhr> | {'content_hash': '97aa4e03bb496c2bc3896dd0a60cfd78', 'timestamp': '', 'source': 'github', 'line_count': 254, 'max_line_length': 480, 'avg_line_length': 62.90551181102362, 'alnum_prop': 0.6768681937664288, 'repo_name': 'pahans/nototools', 'id': '3a39372c0ff654dd92dc0a362f04fb26868af47f', 'size': '16401', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'third_party/udhr/udhr_bre.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '620'}, {'name': 'Makefile', 'bytes': '3424'}, {'name': 'Python', 'bytes': '546238'}, {'name': 'Shell', 'bytes': '3802'}]} |
<?php
/**
* Created by PhpStorm.
* User: zhangjincheng
* Date: 17-2-27
* Time: 上午10:13
*/
namespace Server\Asyn\TcpClient;
use Server\Asyn\AsynPool;
use Server\CoreBase\PortManager;
use Server\CoreBase\SwooleException;
use Server\Memory\Pool;
use Server\Pack\IPack;
/**
* 主要用作SD的RPC,所以加上了rpc_token用于识别,这里并没有用到连接池!!
* 如果和SD通讯推荐使用这个而不是TcpClientPool
* Class TcpClientPool
* @package Server\Asyn\TcpClient
*/
class SdTcpRpcPool extends AsynPool
{
const AsynName = 'tcp_rpc_client';
public $connect;
protected $port;
protected $host;
protected $set;
protected $client;
/**
* 因为这里是流rpc,会一直向服务器发请求,这里需要针对返回结果验证请求是否成功
* @var array
*/
private $command_backup;
/**
* @var IPack
*/
protected $pack;
public function __construct($config, $config_name, $connect)
{
parent::__construct($config);
$this->connect = $connect;
$this->pack = PortManager::createPack($this->config->get("tcpClient.$config_name.pack_tool"));
$this->set = $this->pack->getProbufSet();
list($this->host, $this->port) = explode(':', $connect);
}
/**
* 获取同步
* @throws SwooleException
*/
public function getSync()
{
throw new SwooleException('暂时没有TcpClient的同步方法');
}
/**
* @return string
*/
public function getAsynName()
{
return self::AsynName . ":" . $this->connect;
}
/**
* @param $send
* @param $callback
* @param bool $oneway
* @return int
* @internal param $data
*/
public function send($send, $callback, $oneway = false)
{
$send['token'] = $this->addTokenCallback($callback);
$send['oneway'] = $oneway;
$this->execute($send);
return $send['token'];
}
/**
* @param $data
*/
public function execute($data)
{
if ($this->client == null) {//代表目前没有可用的连接
$this->prepareOne();
$this->commands->push($data);
} else {
if (!$this->client->isConnected()) {
$this->client = null;
$this->prepareOne();
$this->commands->push($data);
return;
}
$this->command_backup[$data['token']] = $data;
$data['rpc_token'] = $data['token'];
$token = $data['token'];
unset($data['token']);
$oneway = $data['oneway'];
unset($data['oneway']);
$data = $this->pack->pack($data);
$this->client->send($data);
if ($oneway) {
$result['token'] = $token;
$result['result'] = null;
unset($this->command_backup[$token]);
$this->distribute($result);
}
}
}
/**
* 准备一个httpClient
*/
public function prepareOne()
{
$client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->set($this->set);
$client->on("connect", function ($cli) {
$this->client = $cli;
if (count($this->commands) > 0) {//有残留的任务
$command = $this->commands->shift();
$this->execute($command);
}
});
$client->on("receive", function ($cli, $recdata) {
try {
$packdata = $this->pack->unPack($recdata);
} catch (\Exception $e) {
return null;
}
if (isset($packdata->rpc_token)) {
$data['token'] = $packdata->rpc_token;
$data['result'] = $packdata->rpc_result;
unset($this->command_backup[$packdata->rpc_token]);
$this->distribute($data);
}
});
$client->on("error", function ($cli) {
if ($cli->isConnected()) {
$cli->close();
} else {
$this->client = null;
}
});
$client->on("close", function ($cli) {
$this->client = null;
});
$client->connect($this->host, $this->port);
}
/**
* 协程的发送
* @param $send
* @param bool $oneway
* @return TcpClientRequestCoroutine
*/
public function coroutineSend($send, $oneway = false)
{
return Pool::getInstance()->get(TcpClientRequestCoroutine::class)->init($this, $send, $oneway);
}
/**
* 帮助去构建一个SD的请求结构体
* @param $context
* @param $controllerName
* @param $method
* @return array
*/
public function helpToBuildSDControllerQuest($context, $controllerName, $method)
{
return ['path' => '/' . $controllerName . '/' . $method, 'controller_name' => $controllerName, 'method_name' => $method, 'rpc_request_id' => $context['request_id']];
}
/**
* 超时时需要处理下
* 销毁垃圾
* @param $token
*/
public function destoryGarbage($token)
{
unset($this->callBacks[$token]);
$this->destoryClient($this->client);
}
/**
* 销毁Client
* @param $client
*/
protected function destoryClient($client)
{
if ($client != null && $this->client->isConnected()) {
$client->close();
}
$this->client = null;
}
public function destroy(&$migrate = [])
{
if ($this->command_backup != null) {
foreach ($this->command_backup as $command) {
$command['callback'] = $this->callBacks[$command['token']];
$migrate[] = $command;
}
}
$migrate = parent::destroy($migrate);
$this->command_backup = null;
$this->destoryClient($this->client);
return $migrate;
}
} | {'content_hash': '2f127f7def33fad76c17ab8da121c209', 'timestamp': '', 'source': 'github', 'line_count': 216, 'max_line_length': 173, 'avg_line_length': 26.50925925925926, 'alnum_prop': 0.5078588892769822, 'repo_name': 'tmtbe/SwooleDistributed', 'id': 'c21f768163943a3a3fb5c19f576624c9d94b0f4d', 'size': '6018', 'binary': False, 'copies': '1', 'ref': 'refs/heads/v2', 'path': 'src/Server/Asyn/TcpClient/SdTcpRpcPool.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '3832'}, {'name': 'HTML', 'bytes': '11136'}, {'name': 'JavaScript', 'bytes': '23410'}, {'name': 'Lua', 'bytes': '96'}, {'name': 'PHP', 'bytes': '657810'}, {'name': 'Shell', 'bytes': '230'}]} |
package gloving
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import java.net.URI
import java.io.{File, PrintWriter}
import scala.collection.mutable.{Map,HashMap}
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD
import org.apache.spark.mllib.clustering.{KMeans, KMeansModel}
import org.apache.spark.mllib.linalg.{Vectors}
import play.api.libs.json._
import play.api.libs.json.Json._
import org.slf4j.LoggerFactory
import com.typesafe.scalalogging.slf4j.Logger
class WordVectorKMeansClusterer(val words: WordVectorRDD) {
@transient lazy val logger = Logger(LoggerFactory.getLogger(getClass.getName))
val nakedVectors = words.map(w => Vectors.dense(w.vector.toArray)).persist().setName(s"${words.name}-nakedVectors")
val count = nakedVectors.count()
def unpersist() { nakedVectors.unpersist() }
def sc = words.context
def train(k: Int, iterations: Int, initialModel: WordVectorKMeansModel): WordVectorKMeansModel = {
train(k, iterations, runs = None, initialModel = Some(initialModel))
}
def train(k: Int, iterations: Int, runs: Int): WordVectorKMeansModel = {
train(k, iterations, runs = Some(runs), initialModel = None)
}
def train(k: Int, iterations: Int, runs: Option[Int], initialModel: Option[WordVectorKMeansModel]): WordVectorKMeansModel = {
//Either the number of runs OR an initial model can be specified, but not both
//The whole purpose of having multiple runs is to run clustering with multiple random initial models to see which one
//performs best, but if there's a user-defined initial model then there's no point in running it multiple times.
assert(runs.isDefined || initialModel.isDefined)
assert(!(runs.isDefined && initialModel.isDefined))
val kmeans = new KMeans()
.setK(k)
.setMaxIterations(iterations)
.setInitializationMode(KMeans.RANDOM)
//If there is a model from the previous iteration, initialize with that
//if there is no model, then perform this first step with the specified number of runs
initialModel.map { m => kmeans.setInitialModel(m) }
runs.map { r => kmeans.setRuns(r) }
logger.info(s"Training model on $count vectors in ${words.name} with k=${k}, iterations=${iterations}, runs=${runs}, initialModel=${initialModel.isDefined}")
new WordVectorKMeansModel(words, kmeans.run(nakedVectors))
}
def trainInSteps[A](k: Int,
totalIterations: Int,
iterationsPerStep: Int,
runs: Int,
initialState: Option[WordVectorKMeansClusterer.TrainingState],
stepFunc: WordVectorKMeansClusterer.TrainingState => A): Seq[A] = {
assert(totalIterations % iterationsPerStep == 0)
var model = initialState.map{s => s.model}
val startingIteration = initialState match {
case Some(s) => s.iteration + iterationsPerStep
case None => iterationsPerStep
}
//Figure out which iteration counts to checkpoint at.
//The last iteration is always a checkpoint.
val steps: List[Int] = (startingIteration to totalIterations by iterationsPerStep).toList
val results = for (iteration <- steps) yield {
logger.info(s"Training model for $iterationsPerStep iterations starting with iteration $iteration")
val nextModel = model match {
case Some(m) => train(k, iterationsPerStep, m)
case None => train(k, iterationsPerStep, runs)
}
model = Some(nextModel)
stepFunc(WordVectorKMeansClusterer.TrainingState(iteration, nextModel))
}
results.toSeq
}
}
object WordVectorKMeansClusterer {
case class TrainingState(iteration: Int, model: WordVectorKMeansModel)
}
| {'content_hash': 'd3f632529d142e0a8694befe57335cf5', 'timestamp': '', 'source': 'github', 'line_count': 101, 'max_line_length': 161, 'avg_line_length': 37.35643564356435, 'alnum_prop': 0.734958918632388, 'repo_name': 'anelson/gloving', 'id': 'd06d0b46261e80e6250a0b15208eecdd20536a68', 'size': '3773', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/scala/WordVectorKMeansClusterer.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '12514'}, {'name': 'CoffeeScript', 'bytes': '13032'}, {'name': 'HTML', 'bytes': '6189'}, {'name': 'Scala', 'bytes': '88480'}, {'name': 'Shell', 'bytes': '16644'}]} |
package com.intellij.find.impl;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.intellij.find.FindBundle;
import com.intellij.find.FindModel;
import com.intellij.find.findInProject.FindInProjectManager;
import com.intellij.find.ngrams.TrigramIndex;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectUtil;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.TrigramBuilder;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileFilter;
import com.intellij.openapi.vfs.VirtualFileVisitor;
import com.intellij.psi.PsiBinaryFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.cache.CacheManager;
import com.intellij.psi.impl.cache.impl.id.IdIndex;
import com.intellij.psi.impl.search.PsiSearchHelperImpl;
import com.intellij.psi.search.*;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.usageView.UsageInfo;
import com.intellij.usages.FindUsagesProcessPresentation;
import com.intellij.usages.UsageLimitUtil;
import com.intellij.usages.impl.UsageViewManagerImpl;
import com.intellij.util.Processor;
import com.intellij.util.Processors;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.FileBasedIndexImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author peter
*/
class FindInProjectTask {
private static final Logger LOG = Logger.getInstance("#com.intellij.find.impl.FindInProjectTask");
private static final int FILES_SIZE_LIMIT = 70 * 1024 * 1024; // megabytes.
private static final int SINGLE_FILE_SIZE_LIMIT = 5 * 1024 * 1024; // megabytes.
private final FindModel myFindModel;
private final Project myProject;
private final PsiManager myPsiManager;
@Nullable private final VirtualFile myDirectory;
private final ProjectFileIndex myProjectFileIndex;
private final FileIndex myFileIndex;
private final Condition<VirtualFile> myFileMask;
private final ProgressIndicator myProgress;
@Nullable private final Module myModule;
private final Set<VirtualFile> myLargeFiles = Collections.synchronizedSet(ContainerUtil.newTroveSet());
private final Set<VirtualFile> myFilesToScanInitially;
private final AtomicBoolean myWarningShown = new AtomicBoolean();
private final AtomicLong myTotalFilesSize = new AtomicLong();
private final String myStringToFindInIndices;
FindInProjectTask(@NotNull final FindModel findModel, @NotNull final Project project, @NotNull Set<VirtualFile> filesToScanInitially) {
myFindModel = findModel;
myProject = project;
myFilesToScanInitially = filesToScanInitially;
myDirectory = FindInProjectUtil.getDirectory(findModel);
myPsiManager = PsiManager.getInstance(project);
final String moduleName = findModel.getModuleName();
myModule = moduleName == null ? null : ApplicationManager.getApplication().runReadAction(
(Computable<Module>)() -> ModuleManager.getInstance(project).findModuleByName(moduleName));
myProjectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
myFileIndex = myModule == null ? myProjectFileIndex : ModuleRootManager.getInstance(myModule).getFileIndex();
Condition<CharSequence> patternCondition = FindInProjectUtil.createFileMaskCondition(findModel.getFileFilter());
myFileMask = file -> file != null && patternCondition.value(file.getNameSequence());
final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
myProgress = progress != null ? progress : new EmptyProgressIndicator();
String stringToFind = myFindModel.getStringToFind();
if (myFindModel.isRegularExpressions()) {
stringToFind = FindInProjectUtil.buildStringToFindForIndicesFromRegExp(stringToFind, myProject);
}
myStringToFindInIndices = stringToFind;
}
public void findUsages(@NotNull Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation) {
try {
myProgress.setIndeterminate(true);
myProgress.setText("Scanning indexed files...");
Set<VirtualFile> filesForFastWordSearch = ApplicationManager.getApplication().runReadAction((Computable<Set<VirtualFile>>)this::getFilesForFastWordSearch);
myProgress.setIndeterminate(false);
if (LOG.isDebugEnabled()) {
LOG.debug("Searching for " + myFindModel.getStringToFind() + " in " + filesForFastWordSearch.size() + " indexed files");
}
searchInFiles(filesForFastWordSearch, processPresentation, consumer);
myProgress.setIndeterminate(true);
myProgress.setText("Scanning non-indexed files...");
boolean canRelyOnIndices = canRelyOnIndices();
final Collection<VirtualFile> otherFiles = collectFilesInScope(filesForFastWordSearch, canRelyOnIndices);
myProgress.setIndeterminate(false);
if (LOG.isDebugEnabled()) {
LOG.debug("Searching for " + myFindModel.getStringToFind() + " in " + otherFiles.size() + " non-indexed files");
}
myProgress.checkCanceled();
long start = System.currentTimeMillis();
searchInFiles(otherFiles, processPresentation, consumer);
if (canRelyOnIndices && otherFiles.size() > 1000) {
long time = System.currentTimeMillis() - start;
logStats(otherFiles, time);
}
}
catch (ProcessCanceledException e) {
processPresentation.setCanceled(true);
if (LOG.isDebugEnabled()) {
LOG.debug("Usage search canceled", e);
}
}
if (!myLargeFiles.isEmpty()) {
processPresentation.setLargeFilesWereNotScanned(myLargeFiles);
}
if (!myProgress.isCanceled()) {
myProgress.setText(FindBundle.message("find.progress.search.completed"));
}
}
private static void logStats(@NotNull Collection<VirtualFile> otherFiles, long time) {
final Multiset<String> stats = HashMultiset.create();
for (VirtualFile file : otherFiles) {
//noinspection StringToUpperCaseOrToLowerCaseWithoutLocale
stats.add(StringUtil.notNullize(file.getExtension()).toLowerCase());
}
List<String> extensions = ContainerUtil.newArrayList(stats.elementSet());
Collections.sort(extensions, (o1, o2) -> stats.count(o2) - stats.count(o1));
String message = "Search in " + otherFiles.size() + " files with unknown types took " + time + "ms.\n" +
"Mapping their extensions to an existing file type (e.g. Plain Text) might speed up the search.\n" +
"Most frequent non-indexed file extensions: ";
for (int i = 0; i < Math.min(10, extensions.size()); i++) {
String extension = extensions.get(i);
message += extension + "(" + stats.count(extension) + ") ";
}
LOG.info(message);
}
private void searchInFiles(@NotNull Collection<VirtualFile> virtualFiles,
@NotNull FindUsagesProcessPresentation processPresentation,
@NotNull final Processor<UsageInfo> consumer) {
AtomicInteger occurrenceCount = new AtomicInteger();
AtomicInteger processedFileCount = new AtomicInteger();
Processor<VirtualFile> processor = virtualFile -> {
if (!virtualFile.isValid()) return true;
long fileLength = UsageViewManagerImpl.getFileLength(virtualFile);
if (fileLength == -1) return true; // Binary or invalid
final boolean skipProjectFile = ProjectUtil.isProjectOrWorkspaceFile(virtualFile) && !myFindModel.isSearchInProjectFiles();
if (skipProjectFile && !Registry.is("find.search.in.project.files")) return true;
if (fileLength > SINGLE_FILE_SIZE_LIMIT) {
myLargeFiles.add(virtualFile);
return true;
}
myProgress.checkCanceled();
if (myProgress.isRunning()) {
double fraction = (double)processedFileCount.incrementAndGet() / virtualFiles.size();
myProgress.setFraction(fraction);
}
String text = FindBundle.message("find.searching.for.string.in.file.progress",
myFindModel.getStringToFind(), virtualFile.getPresentableUrl());
myProgress.setText(text);
myProgress.setText2(FindBundle.message("find.searching.for.string.in.file.occurrences.progress", occurrenceCount));
Pair.NonNull<PsiFile, VirtualFile> pair = ReadAction.compute(() -> findFile(virtualFile));
if (pair == null) return true;
PsiFile psiFile = pair.first;
VirtualFile sourceVirtualFile = pair.second;
int countInFile = FindInProjectUtil.processUsagesInFile(psiFile, sourceVirtualFile, myFindModel, info -> skipProjectFile || consumer.process(info));
if (countInFile > 0 && skipProjectFile) {
processPresentation.projectFileUsagesFound(() -> {
FindModel model = myFindModel.clone();
model.setSearchInProjectFiles(true);
FindInProjectManager.getInstance(myProject).startFindInProject(model);
});
return true;
}
occurrenceCount.addAndGet(countInFile);
if (countInFile > 0) {
if (myTotalFilesSize.addAndGet(fileLength) > FILES_SIZE_LIMIT && myWarningShown.compareAndSet(false, true)) {
String message = FindBundle.message("find.excessive.total.size.prompt",
UsageViewManagerImpl.presentableSize(myTotalFilesSize.longValue()),
ApplicationNamesInfo.getInstance().getProductName());
UsageLimitUtil.showAndCancelIfAborted(myProject, message, processPresentation.getUsageViewPresentation());
}
}
return true;
};
PsiSearchHelperImpl.processFilesConcurrentlyDespiteWriteActions(myProject, new ArrayList<>(virtualFiles), myProgress, processor);
}
// must return non-binary files
@NotNull
private Collection<VirtualFile> collectFilesInScope(@NotNull final Set<VirtualFile> alreadySearched, final boolean skipIndexed) {
SearchScope customScope = myFindModel.isCustomScope() ? myFindModel.getCustomScope() : null;
final GlobalSearchScope globalCustomScope = customScope == null ? null : GlobalSearchScopeUtil.toGlobalSearchScope(customScope, myProject);
final ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(myProject);
final boolean hasTrigrams = hasTrigrams(myStringToFindInIndices);
class EnumContentIterator implements ContentIterator {
private final Set<VirtualFile> myFiles = new LinkedHashSet<>();
@Override
public boolean processFile(@NotNull final VirtualFile virtualFile) {
ApplicationManager.getApplication().runReadAction(new Runnable() {
@Override
public void run() {
ProgressManager.checkCanceled();
if (virtualFile.isDirectory() || !virtualFile.isValid() ||
!myFileMask.value(virtualFile) ||
globalCustomScope != null && !globalCustomScope.contains(virtualFile)) {
return;
}
if (skipIndexed && isCoveredByIndex(virtualFile) &&
(fileIndex.isInContent(virtualFile) || fileIndex.isInLibraryClasses(virtualFile) || fileIndex.isInLibrarySource(virtualFile))) {
return;
}
Pair.NonNull<PsiFile, VirtualFile> pair = findFile(virtualFile);
if (pair == null) return;
VirtualFile sourceVirtualFile = pair.second;
if (sourceVirtualFile != null && !alreadySearched.contains(sourceVirtualFile)) {
myFiles.add(sourceVirtualFile);
}
}
private final FileBasedIndexImpl fileBasedIndex = (FileBasedIndexImpl)FileBasedIndex.getInstance();
private boolean isCoveredByIndex(VirtualFile file) {
FileType fileType = file.getFileType();
if (hasTrigrams) {
return TrigramIndex.isIndexable(fileType) && fileBasedIndex.isIndexingCandidate(file, TrigramIndex.INDEX_ID);
}
return IdIndex.isIndexable(fileType) && fileBasedIndex.isIndexingCandidate(file, IdIndex.NAME);
}
});
return true;
}
@NotNull
private Collection<VirtualFile> getFiles() {
return myFiles;
}
}
final EnumContentIterator iterator = new EnumContentIterator();
if (customScope instanceof LocalSearchScope) {
for (VirtualFile file : GlobalSearchScopeUtil.getLocalScopeFiles((LocalSearchScope)customScope)) {
iterator.processFile(file);
}
}
else if (customScope instanceof Iterable) { // GlobalSearchScope can span files out of project roots e.g. FileScope / FilesScope
//noinspection unchecked
for (VirtualFile file : (Iterable<VirtualFile>)customScope) {
iterator.processFile(file);
}
}
else if (myDirectory != null) {
final boolean checkExcluded = !ProjectFileIndex.SERVICE.getInstance(myProject).isExcluded(myDirectory);
VirtualFileVisitor.Option limit = VirtualFileVisitor.limit(myFindModel.isWithSubdirectories() ? -1 : 1);
VfsUtilCore.visitChildrenRecursively(myDirectory, new VirtualFileVisitor(limit) {
@Override
public boolean visitFile(@NotNull VirtualFile file) {
if (checkExcluded && myProjectFileIndex.isExcluded(file)) return false;
iterator.processFile(file);
return true;
}
});
}
else {
boolean success = myFileIndex.iterateContent(iterator);
if (success && globalCustomScope != null && globalCustomScope.isSearchInLibraries()) {
final VirtualFile[] librarySources = ApplicationManager.getApplication().runReadAction((Computable<VirtualFile[]>)() -> {
OrderEnumerator enumerator = myModule == null ? OrderEnumerator.orderEntries(myProject) : OrderEnumerator.orderEntries(myModule);
return enumerator.withoutModuleSourceEntries().withoutDepModules().getSourceRoots();
});
iterateAll(librarySources, globalCustomScope, iterator);
}
}
return iterator.getFiles();
}
private static boolean iterateAll(@NotNull VirtualFile[] files, @NotNull final GlobalSearchScope searchScope, @NotNull final ContentIterator iterator) {
final FileTypeManager fileTypeManager = FileTypeManager.getInstance();
final VirtualFileFilter contentFilter = file -> file.isDirectory() ||
!fileTypeManager.isFileIgnored(file) && !file.getFileType().isBinary() && searchScope.contains(file);
for (VirtualFile file : files) {
if (!VfsUtilCore.iterateChildrenRecursively(file, contentFilter, iterator)) return false;
}
return true;
}
private boolean canRelyOnIndices() {
if (DumbService.isDumb(myProject)) return false;
// a local scope may be over a non-indexed file
if (myFindModel.getCustomScope() instanceof LocalSearchScope) return false;
String text = myStringToFindInIndices;
if (StringUtil.isEmptyOrSpaces(text)) return false;
if (hasTrigrams(text)) return true;
// $ is used to separate words when indexing plain-text files but not when indexing
// Java identifiers, so we can't consistently break a string containing $ characters into words
return myFindModel.isWholeWordsOnly() && text.indexOf('$') < 0 && !StringUtil.getWordsInStringLongestFirst(text).isEmpty();
}
private static boolean hasTrigrams(@NotNull String text) {
return TrigramIndex.ENABLED &&
!TrigramBuilder.processTrigrams(text, new TrigramBuilder.TrigramProcessor() {
@Override
public boolean execute(int value) {
return false;
}
});
}
@NotNull
private Set<VirtualFile> getFilesForFastWordSearch() {
String stringToFind = myStringToFindInIndices;
if (stringToFind.isEmpty() || DumbService.getInstance(myProject).isDumb()) {
return Collections.emptySet();
}
final Set<VirtualFile> resultFiles = new LinkedHashSet<>();
for(VirtualFile file:myFilesToScanInitially) {
if (myFileMask.value(file)) {
resultFiles.add(file);
}
}
final GlobalSearchScope scope = GlobalSearchScopeUtil.toGlobalSearchScope(FindInProjectUtil.getScopeFromModel(myProject, myFindModel),
myProject);
if (TrigramIndex.ENABLED) {
final Set<Integer> keys = ContainerUtil.newTroveSet();
TrigramBuilder.processTrigrams(stringToFind, new TrigramBuilder.TrigramProcessor() {
@Override
public boolean execute(int value) {
keys.add(value);
return true;
}
});
if (!keys.isEmpty()) {
final List<VirtualFile> hits = new ArrayList<>();
ApplicationManager.getApplication().runReadAction(() -> {
FileBasedIndex.getInstance().getFilesWithKey(TrigramIndex.INDEX_ID, keys, Processors.cancelableCollectProcessor(hits), scope);
});
for (VirtualFile hit : hits) {
if (myFileMask.value(hit)) {
resultFiles.add(hit);
}
}
return resultFiles;
}
}
PsiSearchHelperImpl helper = (PsiSearchHelperImpl)PsiSearchHelper.SERVICE.getInstance(myProject);
helper.processFilesWithText(scope, UsageSearchContext.ANY, myFindModel.isCaseSensitive(), stringToFind, file -> {
if (myFileMask.value(file)) {
ContainerUtil.addIfNotNull(resultFiles, file);
}
return true;
});
// in case our word splitting is incorrect
CacheManager cacheManager = CacheManager.SERVICE.getInstance(myProject);
VirtualFile[] filesWithWord = cacheManager.getVirtualFilesWithWord(stringToFind, UsageSearchContext.ANY, scope,
myFindModel.isCaseSensitive());
for (VirtualFile file : filesWithWord) {
if (myFileMask.value(file)) {
resultFiles.add(file);
}
}
return resultFiles;
}
private Pair.NonNull<PsiFile, VirtualFile> findFile(@NotNull final VirtualFile virtualFile) {
PsiFile psiFile = myPsiManager.findFile(virtualFile);
if (psiFile != null && !(psiFile instanceof PsiBinaryFile)) {
PsiFile sourceFile = (PsiFile)psiFile.getNavigationElement();
if (sourceFile != null) psiFile = sourceFile;
if (psiFile.getFileType().isBinary()) {
psiFile = null;
}
}
VirtualFile sourceVirtualFile = PsiUtilCore.getVirtualFile(psiFile);
if (psiFile == null || psiFile.getFileType().isBinary() || sourceVirtualFile == null) {
return null;
}
return Pair.createNonNull(psiFile, sourceVirtualFile);
}
}
| {'content_hash': 'cfb903b8ade6f7e8367452cb40a3181c', 'timestamp': '', 'source': 'github', 'line_count': 451, 'max_line_length': 161, 'avg_line_length': 44.0509977827051, 'alnum_prop': 0.7107766648210601, 'repo_name': 'youdonghai/intellij-community', 'id': 'b453a5570ed163f08dfb150f9b0449ff9cccb9ba', 'size': '20467', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '60477'}, {'name': 'C', 'bytes': '195270'}, {'name': 'C#', 'bytes': '1264'}, {'name': 'C++', 'bytes': '197804'}, {'name': 'CMake', 'bytes': '1195'}, {'name': 'CSS', 'bytes': '201445'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Cucumber', 'bytes': '14382'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groff', 'bytes': '35232'}, {'name': 'Groovy', 'bytes': '3078038'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1837329'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '160121025'}, {'name': 'JavaScript', 'bytes': '570364'}, {'name': 'Jupyter Notebook', 'bytes': '93222'}, {'name': 'Kotlin', 'bytes': '2803472'}, {'name': 'Lex', 'bytes': '183993'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '49795'}, {'name': 'Objective-C', 'bytes': '28750'}, {'name': 'Perl', 'bytes': '903'}, {'name': 'Perl6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6639'}, {'name': 'Python', 'bytes': '24055272'}, {'name': 'Ruby', 'bytes': '1217'}, {'name': 'Scala', 'bytes': '11698'}, {'name': 'Shell', 'bytes': '63389'}, {'name': 'Smalltalk', 'bytes': '338'}, {'name': 'TeX', 'bytes': '25473'}, {'name': 'Thrift', 'bytes': '1846'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'Visual Basic', 'bytes': '77'}, {'name': 'XSLT', 'bytes': '113040'}]} |
#import "ORKTintedImageView.h"
#import "ORKTintedImageView_Internal.h"
#import "ORKHelpers_Internal.h"
#define ORKTintedImageLog(...)
ORK_INLINE BOOL ORKIsImageAnimated(UIImage *image) {
return image.images.count > 1;
}
UIImage *ORKImageByTintingImage(UIImage *image, UIColor *tintColor, CGFloat scale) {
if (!image || !tintColor || !(scale > 0)) {
return nil;
}
ORKTintedImageLog(@"%@ %@ %f", image, tintColor, scale);
UIGraphicsBeginImageContextWithOptions(image.size, NO, scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextSetAlpha(context, 1);
CGRect r = (CGRect){{0,0},image.size};
CGContextBeginTransparencyLayerWithRect(context, r, NULL);
[tintColor setFill];
[image drawInRect:r];
UIRectFillUsingBlendMode(r, kCGBlendModeSourceIn);
CGContextEndTransparencyLayer(context);
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
@interface ORKTintedImageCacheKey : NSObject
- (instancetype)initWithImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale;
@property (nonatomic, readonly) UIImage *image;
@property (nonatomic, readonly) UIColor *tintColor;
@property (nonatomic, readonly) CGFloat scale;
@end
@implementation ORKTintedImageCacheKey {
UIImage *_image;
UIColor *_tintColor;
CGFloat _scale;
}
- (instancetype)initWithImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale {
self = [super init];
if (self) {
_image = image;
_tintColor = tintColor;
_scale = scale;
}
return self;
}
- (BOOL)isEqual:(id)object {
if ([self class] != [object class]) {
return NO;
}
__typeof(self) castObject = object;
return (ORKEqualObjects(self.image, castObject.image)
&& ORKEqualObjects(self.tintColor, castObject.tintColor)
&& ORKCGFloatNearlyEqualToFloat(self.scale, castObject.scale));
}
@end
@interface ORKTintedImageCache ()
- (UIImage *)tintedImageForImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale;
@end
@implementation ORKTintedImageCache
+ (instancetype)sharedCache
{
static dispatch_once_t onceToken;
static id sharedInstance = nil;
dispatch_once(&onceToken, ^{
sharedInstance = [[[self class] alloc] init];
});
return sharedInstance;
}
- (UIImage *)tintedImageForImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale {
UIImage *tintedImage = nil;
ORKTintedImageCacheKey *key = [[ORKTintedImageCacheKey alloc] initWithImage:image tintColor:tintColor scale:scale];
tintedImage = [self objectForKey:key];
if (!tintedImage) {
tintedImage = ORKImageByTintingImage(image, tintColor, scale);
if (tintedImage) {
[self setObject:tintedImage forKey:key];
}
}
return tintedImage;
}
- (void)cacheImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale {
[[ORKTintedImageCache sharedCache] tintedImageForImage:image tintColor:tintColor scale:scale];
}
@end
@implementation ORKTintedImageView {
UIImage *_originalImage;
UIImage *_tintedImage;
UIColor *_appliedTintColor;
CGFloat _appliedScaleFactor;
}
- (void)setShouldApplyTint:(BOOL)shouldApplyTint {
_shouldApplyTint = shouldApplyTint;
self.image = _originalImage;
}
- (UIImage *)imageByTintingImage:(UIImage *)image {
if (!image || (image.renderingMode == UIImageRenderingModeAlwaysOriginal
|| (image.renderingMode == UIImageRenderingModeAutomatic && !_shouldApplyTint))) {
return image;
}
UIColor *tintColor = self.tintColor;
CGFloat screenScale = self.window.screen.scale; // Use screen.scale; self.contentScaleFactor remains 1.0 until later
if (screenScale > 0 && (![_appliedTintColor isEqual:tintColor] || !ORKCGFloatNearlyEqualToFloat(_appliedScaleFactor, screenScale))) {
_appliedTintColor = tintColor;
_appliedScaleFactor = screenScale;
if (!ORKIsImageAnimated(image)) {
if (_enableTintedImageCaching) {
_tintedImage = [[ORKTintedImageCache sharedCache] tintedImageForImage:image tintColor:tintColor scale:screenScale];
} else {
_tintedImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
}
} else {
NSArray *animationImages = image.images;
NSMutableArray *tintedAnimationImages = [[NSMutableArray alloc] initWithCapacity:animationImages.count];
for (UIImage *animationImage in animationImages) {
UIImage *tintedAnimationImage = nil;
if (_enableTintedImageCaching) {
tintedAnimationImage = [[ORKTintedImageCache sharedCache] tintedImageForImage:animationImage tintColor:tintColor scale:screenScale];
} else {
tintedAnimationImage = ORKImageByTintingImage(animationImage, tintColor, screenScale);
}
if (tintedAnimationImage) {
[tintedAnimationImages addObject:tintedAnimationImage];
}
}
_tintedImage = [UIImage animatedImageWithImages:tintedAnimationImages duration:image.duration];
}
}
return _tintedImage;
}
- (void)setImage:(UIImage *)image {
_originalImage = image;
image = [self imageByTintingImage:image];
[super setImage:image];
}
- (void)tintColorDidChange {
[super tintColorDidChange];
// recompute for new tint color
self.image = _originalImage;
}
- (void)didMoveToWindow {
[super didMoveToWindow];
// recompute for new screen.scale
self.image = _originalImage;
}
@end
| {'content_hash': '82341de7ffa52c84e8d86c4a305d0208', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 152, 'avg_line_length': 30.978947368421053, 'alnum_prop': 0.6805980292218824, 'repo_name': 'jeremiahyan/ResearchKit', 'id': 'ef7e7dcd83bf04125def7f3ecded5ed9209348ef', 'size': '7564', 'binary': False, 'copies': '3', 'ref': 'refs/heads/main', 'path': 'ResearchKit/Common/ORKTintedImageView.m', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Objective-C', 'bytes': '3281362'}, {'name': 'Python', 'bytes': '7008'}, {'name': 'Ruby', 'bytes': '3907'}, {'name': 'Swift', 'bytes': '17493'}]} |
import InternalLink from '../common/InternalLink';
import Page from '../common/Page';
import { loadConfig } from '../config';
import GeneralPageMeta from '../general-page/GeneralPageMeta';
import { routerRedirects } from '../routes';
import { TagGroupData } from './types';
import { Typography } from '@mui/material';
import { Box } from '@mui/system';
import React from 'react';
type TagListPageProps = {
tags: TagGroupData[];
};
const TagListPage: React.FC<TagListPageProps> = ({
tags,
}: TagListPageProps) => {
const config = loadConfig();
return (
<Page narrow>
<GeneralPageMeta
title={`Tags - ${config.title}`}
description={`Tags on ${config.title}.`}
url={`${config.url}${routerRedirects.tags.index}`}
/>
<Typography variant="h1" gutterBottom>
Tags
</Typography>
<Box sx={{ textAlign: 'center' }}>
{tags.map((tag) => (
<InternalLink
sx={{
verticalAlign: 'middle',
display: 'inline-block',
lineHeight: 1,
mx: 1,
my: 2,
}}
key={tag.slug}
href={routerRedirects.tags.tag(tag.slug).index}
style={{
fontSize:
Math.max((tag.articleCount * 15) / tags.length, 1).toString() +
'rem',
}}
>
{tag.title}
</InternalLink>
))}
</Box>
</Page>
);
};
export default TagListPage;
| {'content_hash': '72e866049827c50a507c98b185043914', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 79, 'avg_line_length': 26.821428571428573, 'alnum_prop': 0.5352862849533955, 'repo_name': 'outcrawl/site', 'id': '38dea50d1f4fa751fabfe8c136890ecf8fff53cd', 'size': '1502', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/tag/TagListPage.tsx', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1435'}, {'name': 'TypeScript', 'bytes': '97834'}]} |
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
| {'content_hash': 'ef7fbe385ee820110a4f59154f3b72b8', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 34, 'avg_line_length': 15.666666666666666, 'alnum_prop': 0.723404255319149, 'repo_name': 'sergecodd/FireFox-OS', 'id': '599a7a5fadd323d7b38b806780886309ead01ec9', 'size': '108', 'binary': False, 'copies': '15', 'ref': 'refs/heads/master', 'path': 'B2G/gecko/media/libnestegg/include/nestegg-stdint.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ada', 'bytes': '443'}, {'name': 'ApacheConf', 'bytes': '85'}, {'name': 'Assembly', 'bytes': '5123438'}, {'name': 'Awk', 'bytes': '46481'}, {'name': 'Batchfile', 'bytes': '56250'}, {'name': 'C', 'bytes': '101720951'}, {'name': 'C#', 'bytes': '38531'}, {'name': 'C++', 'bytes': '148896543'}, {'name': 'CMake', 'bytes': '23541'}, {'name': 'CSS', 'bytes': '2758664'}, {'name': 'DIGITAL Command Language', 'bytes': '56757'}, {'name': 'Emacs Lisp', 'bytes': '12694'}, {'name': 'Erlang', 'bytes': '889'}, {'name': 'FLUX', 'bytes': '34449'}, {'name': 'GLSL', 'bytes': '26344'}, {'name': 'Gnuplot', 'bytes': '710'}, {'name': 'Groff', 'bytes': '447012'}, {'name': 'HTML', 'bytes': '43343468'}, {'name': 'IDL', 'bytes': '1455122'}, {'name': 'Java', 'bytes': '43261012'}, {'name': 'JavaScript', 'bytes': '46646658'}, {'name': 'Lex', 'bytes': '38358'}, {'name': 'Logos', 'bytes': '21054'}, {'name': 'Makefile', 'bytes': '2733844'}, {'name': 'Matlab', 'bytes': '67316'}, {'name': 'Max', 'bytes': '3698'}, {'name': 'NSIS', 'bytes': '421625'}, {'name': 'Objective-C', 'bytes': '877657'}, {'name': 'Objective-C++', 'bytes': '737713'}, {'name': 'PHP', 'bytes': '17415'}, {'name': 'Pascal', 'bytes': '6780'}, {'name': 'Perl', 'bytes': '1153180'}, {'name': 'Perl6', 'bytes': '1255'}, {'name': 'PostScript', 'bytes': '1139'}, {'name': 'PowerShell', 'bytes': '8252'}, {'name': 'Protocol Buffer', 'bytes': '26553'}, {'name': 'Python', 'bytes': '8453201'}, {'name': 'Ragel in Ruby Host', 'bytes': '3481'}, {'name': 'Ruby', 'bytes': '5116'}, {'name': 'Scilab', 'bytes': '7'}, {'name': 'Shell', 'bytes': '3383832'}, {'name': 'SourcePawn', 'bytes': '23661'}, {'name': 'TeX', 'bytes': '879606'}, {'name': 'WebIDL', 'bytes': '1902'}, {'name': 'XSLT', 'bytes': '13134'}, {'name': 'Yacc', 'bytes': '112744'}]} |
<?php
namespace PHPExiftool\Driver\Tag\DICOM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;
/**
* @ExclusionPolicy("all")
*/
class RedPaletteColorTableDescriptor extends AbstractTag
{
protected $Id = '0028,1101';
protected $Name = 'RedPaletteColorTableDescriptor';
protected $FullName = 'DICOM::Main';
protected $GroupName = 'DICOM';
protected $g0 = 'DICOM';
protected $g1 = 'DICOM';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Red Palette Color Table Descriptor';
}
| {'content_hash': 'fa7dda0455c52f717d3f25495c508396', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 66, 'avg_line_length': 17.714285714285715, 'alnum_prop': 0.6838709677419355, 'repo_name': 'romainneutron/PHPExiftool', 'id': 'ae0804f7e13c0694d1090450a18aa6716a65d7bf', 'size': '842', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/PHPExiftool/Driver/Tag/DICOM/RedPaletteColorTableDescriptor.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '22042446'}]} |
[](https://circleci.com/gh/docker/libnetwork/tree/master) [](https://coveralls.io/r/docker/libnetwork) [](https://godoc.org/github.com/docker/libnetwork) [](https://goreportcard.com/report/github.com/docker/libnetwork)
Libnetwork provides a native Go implementation for connecting containers
The goal of libnetwork is to deliver a robust Container Network Model that provides a consistent programming interface and the required network abstractions for applications.
#### Design
Please refer to the [design](docs/design.md) for more information.
#### Using libnetwork
There are many networking solutions available to suit a broad range of use-cases. libnetwork uses a driver / plugin model to support all of these solutions while abstracting the complexity of the driver implementations by exposing a simple and consistent Network Model to users.
```go
import (
"fmt"
"log"
"github.com/docker/docker/pkg/reexec"
"github.com/docker/libnetwork"
"github.com/docker/libnetwork/config"
"github.com/docker/libnetwork/netlabel"
"github.com/docker/libnetwork/options"
)
func main() {
if reexec.Init() {
return
}
// Select and configure the network driver
networkType := "bridge"
// Create a new controller instance
driverOptions := options.Generic{}
genericOption := make(map[string]interface{})
genericOption[netlabel.GenericData] = driverOptions
controller, err := libnetwork.New(config.OptionDriverConfig(networkType, genericOption))
if err != nil {
log.Fatalf("libnetwork.New: %s", err)
}
// Create a network for containers to join.
// NewNetwork accepts Variadic optional arguments that libnetwork and Drivers can use.
network, err := controller.NewNetwork(networkType, "network1", "")
if err != nil {
log.Fatalf("controller.NewNetwork: %s", err)
}
// For each new container: allocate IP and interfaces. The returned network
// settings will be used for container infos (inspect and such), as well as
// iptables rules for port publishing. This info is contained or accessible
// from the returned endpoint.
ep, err := network.CreateEndpoint("Endpoint1")
if err != nil {
log.Fatalf("network.CreateEndpoint: %s", err)
}
// Create the sandbox for the container.
// NewSandbox accepts Variadic optional arguments which libnetwork can use.
sbx, err := controller.NewSandbox("container1",
libnetwork.OptionHostname("test"),
libnetwork.OptionDomainname("docker.io"))
if err != nil {
log.Fatalf("controller.NewSandbox: %s", err)
}
// A sandbox can join the endpoint via the join api.
err = ep.Join(sbx)
if err != nil {
log.Fatalf("ep.Join: %s", err)
}
// libnetwork client can check the endpoint's operational data via the Info() API
epInfo, err := ep.DriverInfo()
if err != nil {
log.Fatalf("ep.DriverInfo: %s", err)
}
macAddress, ok := epInfo[netlabel.MacAddress]
if !ok {
log.Fatalf("failed to get mac address from endpoint info")
}
fmt.Printf("Joined endpoint %s (%s) to sandbox %s (%s)\n", ep.Name(), macAddress, sbx.ContainerID(), sbx.Key())
}
```
## Future
Please refer to [roadmap](ROADMAP.md) for more information.
## Contributing
Want to hack on libnetwork? [Docker's contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md) apply.
## Copyright and license
Code and documentation copyright 2015 Docker, inc. Code released under the Apache 2.0 license. Docs released under Creative commons.
| {'content_hash': '1f903ced0ceada27dbbe2b9d965719ff', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 518, 'avg_line_length': 37.857142857142854, 'alnum_prop': 0.7452830188679245, 'repo_name': 'mikebrow/docker', 'id': 'a9020381abe8f66a999462f41b36b7e758d60bca', 'size': '3752', 'binary': False, 'copies': '26', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/docker/libnetwork/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '81'}, {'name': 'C', 'bytes': '4815'}, {'name': 'Dockerfile', 'bytes': '12323'}, {'name': 'Go', 'bytes': '7318440'}, {'name': 'Makefile', 'bytes': '8880'}, {'name': 'PowerShell', 'bytes': '78275'}, {'name': 'Shell', 'bytes': '124859'}, {'name': 'Vim script', 'bytes': '1369'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Allison Kadel - Technical Blog</title>
<!-- Bootstrap Core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Theme CSS -->
<link href="css/clean-blog.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
Menu <i class="fa fa-bars"></i>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li>
<a href="index.html">Home</a>
</li>
<li>
<a href="photography.html">Photography</a>
</li>
<li>
<a href="videography.html">Videography</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Header -->
<!-- Set your background image for this header on the line below. -->
<header class="intro-header" style="background-image: url('img/Bathroom_dark.jpg')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h2>Technical Blog</h2>
<hr class="small">
<span class="subheading"></span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="post-preview">
<a href="posts/basic-ruby-environment.html">
<h2 class="post-title">
A Simple Ruby Environment
</h2>
<h3 class="post-subtitle">
Setting up a console to play with your objects
</h3>
</a>
<p class="post-meta">Posted on January 14, 2019</p>
</div>
<hr>
<div class="post-preview">
<a href="posts/musicality.html">
<h2 class="post-title">
Musicality
</h2>
<h3 class="post-subtitle">
A React-Redux app for composing music
</h3>
</a>
<p class="post-meta">Posted on January 12, 2019</p>
</div>
<hr>
<div class="post-preview">
<a href="posts/javascript-events.html">
<h2 class="post-title">
Events in Javascript
</h2>
<h3 class="post-subtitle">
Handlers, order, and delegation
</h3>
</a>
<p class="post-meta">Posted on November 17, 2018</p>
</div>
<hr>
<div class="post-preview">
<a href="posts/perfectionism.html">
<h2 class="post-title">
The Process of Perfecting
</h2>
<h3 class="post-subtitle">
Bushwhacking through disabling ideals
</h3>
</a>
<p class="post-meta">Posted on August 15, 2018</p>
</div>
<hr>
<div class="post-preview">
<a href="posts/stateless-protocol.html">
<h2 class="post-title">
Stateless Protocol
</h2>
<h3 class="post-subtitle">
A fleeting connection between two friends
</h3>
</a>
<p class="post-meta">Posted on June 5, 2018</p>
</div>
<hr>
<div class="post-preview">
<a href="posts/biorhythms.html">
<h2 class="post-title">
Tracking Biorhythms with Sinatra
</h2>
<h3 class="post-subtitle">
Leave the paint and open the hood
</h3>
</a>
<p class="post-meta">Posted on June 4, 2018</p>
</div>
<hr>
<div class="post-preview">
<a href="posts/rescue-cats-with-code.html">
<h2 class="post-title">
Rescuing Cats with Ruby
</h2>
<h3 class="post-subtitle">
A web scraper CLI app
</h3>
</a>
<p class="post-meta">Posted on May 18, 2018</p>
</div>
<hr>
<div class="post-preview">
<a href="posts/why-software.html">
<h2 class="post-title">
Why Software?
</h2>
<h3 class="post-subtitle">
How coding can assuage existential crisis
</h3>
</a>
<p class="post-meta">Posted on May 18, 2018</p>
</div>
<hr>
<!--<div class="post-preview">
<a href="post.html">
<h2 class="post-title">
I believe every human has a finite number of heartbeats. I don't intend to waste any of mine.
</h2>
</a>
<p class="post-meta">Posted by
<a href="#">Start Bootstrap</a>
on September 18, 2018</p>
</div> -->
<!--
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>Test text for blog!
<p><h5>more test text!</h5></p>
<p><h6>Something technical and exciting.</h6></p>
<p>More cutting edge jargony stuff.</p>
-->
<!-- <p>Want to get in touch with me? Fill out the form below to send me a message and I will try to get back to you within 24 hours!</p>
Contact Form - Enter your email address on line 19 of the mail/contact_me.php file to make this form work. -->
<!-- WARNING: Some web hosts do not allow emails to be sent through forms to common mail hosts like Gmail or Yahoo. It's recommended that you use a private domain email address! -->
<!-- NOTE: To use the contact form, your site must be on a live web host with PHP! The form will not work locally! -->
<!-- <form name="sentMessage" id="contactForm" novalidate>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Phone Number</label>
<input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</form> -->
</div>
</div>
</div>
<hr>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<ul class="list-inline text-center">
<li>
<a href="#">
<span class="fa-stack fa-lg">
<i class="fa fa-circle fa-stack-2x"></i>
<i class="fa fa-instagram fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="copyright text-muted">Copyright © Allison Kadel 2018</p>
</div>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Contact Form JavaScript -->
<script src="js/jqBootstrapValidation.js"></script>
<script src="js/contact_me.js"></script>
<!-- Theme JavaScript -->
<script src="js/clean-blog.min.js"></script>
</body>
</html>
| {'content_hash': 'be42f3e566be5c5088e08e374470047e', 'timestamp': '', 'source': 'github', 'line_count': 298, 'max_line_length': 197, 'avg_line_length': 39.828859060402685, 'alnum_prop': 0.4756929817170781, 'repo_name': 'allisonkadel/allisonkadel.github.io', 'id': '0504200c85c361fc68101452b7b4569da3d9de18', 'size': '11869', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'blog.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9050'}, {'name': 'HTML', 'bytes': '134223'}]} |
typedef struct env_md_ctx_st EVP_MD_CTX;
#elif defined(USE_NSS)
// Forward declaration.
struct SGNContextStr;
#elif defined(OS_MACOSX) && !defined(OS_IOS)
#include <Security/cssm.h>
#endif
#include <vector>
#include "base/basictypes.h"
#include "crypto/crypto_export.h"
#if defined(OS_WIN)
#include "crypto/scoped_capi_types.h"
#endif
namespace crypto {
class RSAPrivateKey;
// Signs data using a bare private key (as opposed to a full certificate).
// Currently can only sign data using SHA-1 with RSA encryption.
class CRYPTO_EXPORT SignatureCreator {
public:
~SignatureCreator();
// Create an instance. The caller must ensure that the provided PrivateKey
// instance outlives the created SignatureCreator.
static SignatureCreator* Create(RSAPrivateKey* key);
// Update the signature with more data.
bool Update(const uint8* data_part, int data_part_len);
// Finalize the signature.
bool Final(std::vector<uint8>* signature);
private:
// Private constructor. Use the Create() method instead.
SignatureCreator();
RSAPrivateKey* key_;
#if defined(USE_OPENSSL)
EVP_MD_CTX* sign_context_;
#elif defined(USE_NSS)
SGNContextStr* sign_context_;
#elif defined(OS_MACOSX) && !defined(OS_IOS)
CSSM_CC_HANDLE sig_handle_;
#elif defined(OS_WIN)
ScopedHCRYPTHASH hash_object_;
#endif
DISALLOW_COPY_AND_ASSIGN(SignatureCreator);
};
} // namespace crypto
#endif // CRYPTO_SIGNATURE_CREATOR_H_
| {'content_hash': 'e6cddf1df0f9d4f2ac218db5e8921d68', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 76, 'avg_line_length': 24.25423728813559, 'alnum_prop': 0.7365478686233403, 'repo_name': 'zcbenz/cefode-chromium', 'id': '301ab19bc1acbead6716be33f8a6d53b15964cc6', 'size': '1771', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'crypto/signature_creator.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '853'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '1174304'}, {'name': 'Awk', 'bytes': '9519'}, {'name': 'C', 'bytes': '76026099'}, {'name': 'C#', 'bytes': '1132'}, {'name': 'C++', 'bytes': '157904700'}, {'name': 'DOT', 'bytes': '1559'}, {'name': 'F#', 'bytes': '381'}, {'name': 'Java', 'bytes': '3225038'}, {'name': 'JavaScript', 'bytes': '18180217'}, {'name': 'Logos', 'bytes': '4517'}, {'name': 'Matlab', 'bytes': '5234'}, {'name': 'Objective-C', 'bytes': '7139426'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '932901'}, {'name': 'Python', 'bytes': '8654916'}, {'name': 'R', 'bytes': '262'}, {'name': 'Ragel in Ruby Host', 'bytes': '3621'}, {'name': 'Shell', 'bytes': '1533012'}, {'name': 'Tcl', 'bytes': '277077'}, {'name': 'XML', 'bytes': '13493'}]} |
using DFlow.Tenants.Core.Model;
using System;
using Domion.Web.ViewModels;
namespace DFlow.WebApp.Features.Tenants
{
public class TenantViewModelMapper : IViewModelMapper<TenantViewModel, Tenant>
{
public Tenant CreateEntity(TenantViewModel vm)
{
var entity = new Tenant();
UpdateEntityData(entity, vm);
return entity;
}
public TenantViewModel CreateViewModel(Tenant entity)
{
var vm = new TenantViewModel
{
Id = entity.Id,
Owner = entity.Owner,
Notes = "Nota simulada en el ViewModel",
RowVersion = entity.RowVersion
};
return vm;
}
public Tenant UpdateEntity(TenantViewModel vm, Tenant entity)
{
if (vm.RowVersion == null || vm.RowVersion.Length == 0)
throw new InvalidOperationException($"{nameof(UpdateEntity)} requires a valid {nameof(vm.RowVersion)}.");
entity.RowVersion = vm.RowVersion;
UpdateEntityData(entity, vm);
return entity;
}
private void UpdateEntityData(Tenant entity, TenantViewModel vm)
{
entity.Owner = vm.Owner;
}
}
}
| {'content_hash': 'a9e5ac8dbf342bea9b3455029bc7e554', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 121, 'avg_line_length': 26.979166666666668, 'alnum_prop': 0.5652509652509653, 'repo_name': 'mvelosop/Domion-X.Net', 'id': '72ba3ba0c5cda60f6ddadae4a80505efea2d5d30', 'size': '1297', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'samples/DFlow.WebApp/Features/Tenants/TenantViewModelMapper.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1687'}, {'name': 'C#', 'bytes': '92215'}]} |
module WebMock::Util
class QueryMapper
class << self
#This class is based on Addressable::URI pre 2.3.0
##
# Converts the query component to a Hash value.
#
# @option [Symbol] notation
# May be one of <code>:flat</code>, <code>:dot</code>, or
# <code>:subscript</code>. The <code>:dot</code> notation is not
# supported for assignment. Default value is <code>:subscript</code>.
#
# @return [Hash, Array] The query string parsed as a Hash or Array object.
#
# @example
# WebMock::Util::QueryMapper.query_to_values("?one=1&two=2&three=3")
# #=> {"one" => "1", "two" => "2", "three" => "3"}
# WebMock::Util::QueryMapper("?one[two][three]=four").query_values
# #=> {"one" => {"two" => {"three" => "four"}}}
# WebMock::Util::QueryMapper.query_to_values("?one.two.three=four",
# :notation => :dot
# )
# #=> {"one" => {"two" => {"three" => "four"}}}
# WebMock::Util::QueryMapper.query_to_values("?one[two][three]=four",
# :notation => :flat
# )
# #=> {"one[two][three]" => "four"}
# WebMock::Util::QueryMapper.query_to_values("?one.two.three=four",
# :notation => :flat
# )
# #=> {"one.two.three" => "four"}
# WebMock::Util::QueryMapper(
# "?one[two][three][]=four&one[two][three][]=five"
# )
# #=> {"one" => {"two" => {"three" => ["four", "five"]}}}
# WebMock::Util::QueryMapper.query_to_values(
# "?one=two&one=three").query_values(:notation => :flat_array)
# #=> [['one', 'two'], ['one', 'three']]
def query_to_values(query, options={})
return nil if query.nil?
query.force_encoding('utf-8') if query.respond_to?(:force_encoding)
options[:notation] ||= :subscript
if ![:flat, :dot, :subscript, :flat_array].include?(options[:notation])
raise ArgumentError,
'Invalid notation. Must be one of: ' +
'[:flat, :dot, :subscript, :flat_array].'
end
empty_accumulator = :flat_array == options[:notation] ? [] : {}
query_array = collect_query_parts(query)
query_hash = collect_query_hash(query_array, empty_accumulator, options)
normalize_query_hash(query_hash, empty_accumulator, options)
end
def normalize_query_hash(query_hash, empty_accumulator, options)
query_hash.inject(empty_accumulator.dup) do |accumulator, (key, value)|
if options[:notation] == :flat_array
accumulator << [key, value]
else
accumulator[key] = value.kind_of?(Hash) ? dehash(value) : value
end
accumulator
end
end
def collect_query_parts(query)
query_parts = query.split('&').map do |pair|
pair.split('=', 2) if pair && !pair.empty?
end
query_parts.compact
end
def collect_query_hash(query_array, empty_accumulator, options)
query_array.compact.inject(empty_accumulator.dup) do |accumulator, (key, value)|
value = if value.nil?
nil
else
::Addressable::URI.unencode_component(value.gsub(/\+/, ' '))
end
key = Addressable::URI.unencode_component(key)
key = key.dup.force_encoding(Encoding::ASCII_8BIT) if key.respond_to?(:force_encoding)
self.__send__("fill_accumulator_for_#{options[:notation]}", accumulator, key, value)
accumulator
end
end
def fill_accumulator_for_flat(accumulator, key, value)
if accumulator[key]
raise ArgumentError, "Key was repeated: #{key.inspect}"
end
accumulator[key] = value
end
def fill_accumulator_for_flat_array(accumulator, key, value)
accumulator << [key, value]
end
def fill_accumulator_for_dot(accumulator, key, value)
array_value = false
subkeys = key.split(".")
current_hash = accumulator
subkeys[0..-2].each do |subkey|
current_hash[subkey] = {} unless current_hash[subkey]
current_hash = current_hash[subkey]
end
if array_value
if current_hash[subkeys.last] && !current_hash[subkeys.last].is_a?(Array)
current_hash[subkeys.last] = [current_hash[subkeys.last]]
end
current_hash[subkeys.last] = [] unless current_hash[subkeys.last]
current_hash[subkeys.last] << value
else
current_hash[subkeys.last] = value
end
end
def fill_accumulator_for_subscript(accumulator, key, value)
current_node = accumulator
subkeys = key.split(/(?=\[\w)/)
subkeys[0..-2].each do |subkey|
node = subkey =~ /\[\]\z/ ? [] : {}
subkey = subkey.gsub(/[\[\]]/, '')
if current_node.is_a? Array
container = current_node.find { |n| n.is_a?(Hash) && n.has_key?(subkey) }
if container
current_node = container[subkey]
else
current_node << {subkey => node}
current_node = node
end
else
current_node[subkey] = node unless current_node[subkey]
current_node = current_node[subkey]
end
end
last_key = subkeys.last
array_value = !!(last_key =~ /\[\]$/)
last_key = last_key.gsub(/[\[\]]/, '')
if current_node.is_a? Array
last_container = current_node.select { |n| n.is_a?(Hash) }.last
if last_container && !last_container.has_key?(last_key)
if array_value
last_container[last_key] << value
else
last_container[last_key] = value
end
else
if array_value
current_node << {last_key => [value]}
else
current_node << {last_key => value}
end
end
else
if array_value
current_node[last_key] = [] unless current_node[last_key]
current_node[last_key] << value
else
current_node[last_key] = value
end
end
end
##
# Sets the query component for this URI from a Hash object.
# This method produces a query string using the :subscript notation.
# An empty Hash will result in a nil query.
#
# @param [Hash, #to_hash, Array] new_query_values The new query values.
def values_to_query(new_query_values, options = {})
options[:notation] ||= :subscript
return if new_query_values.nil?
unless new_query_values.is_a?(Array)
unless new_query_values.respond_to?(:to_hash)
raise TypeError,
"Can't convert #{new_query_values.class} into Hash."
end
new_query_values = new_query_values.to_hash
new_query_values = new_query_values.inject([]) do |object, (key, value)|
key = key.to_s if key.is_a?(::Symbol) || key.nil?
if value.is_a?(Array)
value.each { |v| object << [key.to_s + '[]', v] }
elsif value.is_a?(Hash)
value.each { |k, v| object << ["#{key.to_s}[#{k}]", v]}
else
object << [key.to_s, value]
end
object
end
# Useful default for OAuth and caching.
# Only to be used for non-Array inputs. Arrays should preserve order.
begin
new_query_values.sort! # may raise for non-comparable values
rescue NoMethodError, ArgumentError
# ignore
end
end
buffer = ''
new_query_values.each do |parent, value|
encoded_parent = ::Addressable::URI.encode_component(
parent.dup, ::Addressable::URI::CharacterClasses::UNRESERVED
)
buffer << "#{to_query(encoded_parent, value, options)}&"
end
buffer.chop
end
def dehash(hash)
hash.each do |(key, value)|
if value.is_a?(::Hash)
hash[key] = self.dehash(value)
end
end
if hash != {} && hash.keys.all? { |key| key =~ /^\d+$/ }
hash.sort.inject([]) do |accu, (_, value)|
accu << value; accu
end
else
hash
end
end
##
# Joins and converts parent and value into a properly encoded and
# ordered URL query.
#
# @private
# @param [String] parent an URI encoded component.
# @param [Array, Hash, Symbol, #to_str] value
#
# @return [String] a properly escaped and ordered URL query.
# new_query_values have form [['key1', 'value1'], ['key2', 'value2']]
def to_query(parent, value, options = {})
options[:notation] ||= :subscript
case value
when ::Hash
value = value.map do |key, val|
[
::Addressable::URI.encode_component(key.to_s.dup, ::Addressable::URI::CharacterClasses::UNRESERVED),
val
]
end
value.sort!
buffer = ''
value.each do |key, val|
new_parent = options[:notation] != :flat_array ? "#{parent}[#{key}]" : parent
buffer << "#{to_query(new_parent, val, options)}&"
end
buffer.chop
when ::Array
buffer = ''
value.each_with_index do |val, i|
new_parent = options[:notation] != :flat_array ? "#{parent}[#{i}]" : parent
buffer << "#{to_query(new_parent, val, options)}&"
end
buffer.chop
when NilClass
parent
else
encoded_value = Addressable::URI.encode_component(
value.to_s.dup, Addressable::URI::CharacterClasses::UNRESERVED
)
"#{parent}=#{encoded_value}"
end
end
end
end
end
| {'content_hash': '89b0a432ee78cc1a93b3093097715aef', 'timestamp': '', 'source': 'github', 'line_count': 278, 'max_line_length': 114, 'avg_line_length': 36.02158273381295, 'alnum_prop': 0.5280607149990014, 'repo_name': 'fughz/fx_info_reader', 'id': '0c5919f0091d10b178ff0713fb1938f29a1a0aed', 'size': '10014', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/bundle/ruby/2.2.0/gems/webmock-1.24.2/lib/webmock/util/query_mapper.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '19263'}, {'name': 'Ruby', 'bytes': '21611'}, {'name': 'Shell', 'bytes': '131'}]} |
import unittest
from tests.test_base import *
from rfho.models import *
class TestModelVectorization(unittest.TestCase):
def test_augmented_gradient(self):
iris, x, y, model, w, model_y, error, accuracy = iris_logistic_regression(2)
d = int(w.tensor.get_shape()[0].value/3)
self.assertEqual(d, 4*3 + 3)
gt = tf.gradients(error, w.tensor)
print('gradients w.r.t. augmented state', gt, sep='\n')
self.assertFalse(any([g is None for g in gt])) # all gradients are defined (all(gt) rises a tf error
grads_intermediate = tf.gradients(error, w._var_list_as_tensors())
print('gradients w.r.t. w, m, p', grads_intermediate, sep='\n')
self.assertFalse(any([g is None for g in grads_intermediate]))
grads_wrt_single_variables = tf.gradients(error, w._get_base_variable_list())
print('gradients w.r.t. w, m, p', grads_wrt_single_variables, sep='\n')
self.assertFalse(any([g is None for g in grads_wrt_single_variables]))
fd = {x: iris.train.data, y: iris.train.target}
with tf.Session().as_default() as ss:
tf.global_variables_initializer().run()
print('gradients w.r.t. augmented state', ss.run(gt, feed_dict=fd), sep='\n')
print('gradients w.r.t. w, m, p', ss.run(grads_intermediate, feed_dict=fd), sep='\n')
print('gradients w.r.t. w, m, p', ss.run(grads_wrt_single_variables, feed_dict=fd), sep='\n')
class TestModels(unittest.TestCase):
# FIXME (last time error:tensorflow.python.framework.errors_impl.InternalError: Dst tensor is not initialized.
# def test_sparse_input_models(self):
# import rfho.datasets as ddt
#
# real_sim = ddt.load_20newsgroup_vectorized(partitions_proportions=[.5, .3])
#
# model_train = LinearModel(real_sim.train.data, real_sim.train.dim_data, real_sim.train.dim_target,
# init_w=tf.random_normal, init_b=tf.random_normal, benchmark=False)
#
# model_train2 = model_train.for_input(real_sim.train.data)
#
# model_valid = model_train.for_input(real_sim.validation.data)
#
# with tf.Session().as_default():
# tf.global_variables_initializer().run()
# self.assertEqual(np.sum(model_train.Ws[0].eval()), np.sum(model_valid.Ws[0].eval()))
# self.assertEqual(np.sum(model_train.bs[0].eval()), np.sum(model_valid.bs[0].eval()))
#
# print(np.sum(model_train.inp[-1].eval() - model_train2.inp[-1].eval()))
# print(np.sum(model_train.inp[-1].eval() - model_train2.inp[-1].eval()))
# print(np.sum(model_train.inp[-1].eval() - model_train2.inp[-1].eval()))
#
# print(np.sum(model_train.inp[-1].eval() - model_train.inp[-1].eval()))
# print(np.sum(model_train.inp[-1].eval() - model_train.inp[-1].eval()))
# # if sparse matmul is used then on gpu these last values are not 0!
def test_ffnn(self):
x, y = tf.placeholder(tf.float32), tf.placeholder(tf.float32)
model = FFNN(x, dims=[10, 123, 89, 47], active_gen_kwargs=(
{'activ': mixed_activation(tf.identity, tf.nn.sigmoid)},
{}
))
mod_y = model.for_input(y)
self.assertEqual(model.var_list, mod_y.var_list) # share variables
self.assertNotEqual(model.inp[1:], mod_y.inp[1:]) # various activations are different nodes!
def test_simpleCNN(self):
x, y = tf.placeholder(tf.float32), tf.placeholder(tf.float32)
model = SimpleCNN(tf.reshape(x, [-1, 15, 15, 1]),
conv_dims=[
[5, 5, 1, 4],
[5, 5, 4, 8],
], ffnn_dims=[20, 10],
active_gen_kwargs=(
{'activ': mixed_activation(tf.identity, tf.nn.sigmoid)},
{}
))
mod_y = model.for_input(tf.reshape(y, [-1, 15, 15, 1]))
self.assertEqual(model.ffnn_part.var_list, mod_y.ffnn_part.var_list)
self.assertEqual(model.var_list, mod_y.var_list) # share variables
self.assertNotEqual(model.inp[1:], mod_y.inp[1:]) # various activations are different nodes!
w, out, out_y = vectorize_model(model.var_list, model.inp[-1], mod_y.inp[-1])
self.assertIsNotNone(out)
def test_determinitstic_initialization(self):
x = tf.constant([[1., 2.]])
mod = FFNN(x, [2, 2, 1], deterministic_initialization=True)
with tf.Session().as_default() as ss:
mod.initialize()
vals = ss.run(mod.Ws)
mod.initialize()
assert_array_lists_same(ss.run(mod.Ws), vals, test_case=self)
print()
with tf.Session().as_default() as ss:
mod.initialize()
assert_array_lists_same(ss.run(mod.Ws), vals, test_case=self)
if __name__ == '__main__':
unittest.main()
| {'content_hash': 'a2a16a180473ded39b196411f1cdb65c', 'timestamp': '', 'source': 'github', 'line_count': 119, 'max_line_length': 114, 'avg_line_length': 42.04201680672269, 'alnum_prop': 0.5774535278832701, 'repo_name': 'lucfra/RFHO', 'id': '04e1a1e8948ee3045c9a940827f2bd39253b49fb', 'size': '5003', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/test_models.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Jupyter Notebook', 'bytes': '34704'}, {'name': 'Python', 'bytes': '308433'}, {'name': 'Shell', 'bytes': '87'}]} |
package org.elasticsearch.search.aggregations.bucket.terms;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregator.BucketCountThresholds;
import org.elasticsearch.search.aggregations.bucket.terms.support.IncludeExclude;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValueType;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorBuilder;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
/**
*
*/
/**
*
*/
public class TermsAggregatorBuilder extends ValuesSourceAggregatorBuilder<ValuesSource, TermsAggregatorBuilder> {
public static final ParseField EXECUTION_HINT_FIELD_NAME = new ParseField("execution_hint");
public static final ParseField SHARD_SIZE_FIELD_NAME = new ParseField("shard_size");
public static final ParseField MIN_DOC_COUNT_FIELD_NAME = new ParseField("min_doc_count");
public static final ParseField SHARD_MIN_DOC_COUNT_FIELD_NAME = new ParseField("shard_min_doc_count");
public static final ParseField REQUIRED_SIZE_FIELD_NAME = new ParseField("size");
static final TermsAggregator.BucketCountThresholds DEFAULT_BUCKET_COUNT_THRESHOLDS = new TermsAggregator.BucketCountThresholds(1, 0, 10,
-1);
public static final ParseField SHOW_TERM_DOC_COUNT_ERROR = new ParseField("show_term_doc_count_error");
public static final ParseField ORDER_FIELD = new ParseField("order");
static final TermsAggregatorBuilder PROTOTYPE = new TermsAggregatorBuilder("", null);
private Terms.Order order = Terms.Order.compound(Terms.Order.count(false), Terms.Order.term(true));
private IncludeExclude includeExclude = null;
private String executionHint = null;
private SubAggCollectionMode collectMode = SubAggCollectionMode.DEPTH_FIRST;
private TermsAggregator.BucketCountThresholds bucketCountThresholds = new TermsAggregator.BucketCountThresholds(
DEFAULT_BUCKET_COUNT_THRESHOLDS);
private boolean showTermDocCountError = false;
public TermsAggregatorBuilder(String name, ValueType valueType) {
super(name, StringTerms.TYPE, ValuesSourceType.ANY, valueType);
}
public TermsAggregator.BucketCountThresholds bucketCountThresholds() {
return bucketCountThresholds;
}
public TermsAggregatorBuilder bucketCountThresholds(TermsAggregator.BucketCountThresholds bucketCountThresholds) {
if (bucketCountThresholds == null) {
throw new IllegalArgumentException("[bucketCountThresholds] must not be null: [" + name + "]");
}
this.bucketCountThresholds = bucketCountThresholds;
return this;
}
/**
* Sets the size - indicating how many term buckets should be returned
* (defaults to 10)
*/
public TermsAggregatorBuilder size(int size) {
if (size < 0) {
throw new IllegalArgumentException("[size] must be greater than or equal to 0. Found [" + size + "] in [" + name + "]");
}
bucketCountThresholds.setRequiredSize(size);
return this;
}
/**
* Sets the shard_size - indicating the number of term buckets each shard
* will return to the coordinating node (the node that coordinates the
* search execution). The higher the shard size is, the more accurate the
* results are.
*/
public TermsAggregatorBuilder shardSize(int shardSize) {
if (shardSize < 0) {
throw new IllegalArgumentException(
"[shardSize] must be greater than or equal to 0. Found [" + shardSize + "] in [" + name + "]");
}
bucketCountThresholds.setShardSize(shardSize);
return this;
}
/**
* Set the minimum document count terms should have in order to appear in
* the response.
*/
public TermsAggregatorBuilder minDocCount(long minDocCount) {
if (minDocCount < 0) {
throw new IllegalArgumentException(
"[minDocCount] must be greater than or equal to 0. Found [" + minDocCount + "] in [" + name + "]");
}
bucketCountThresholds.setMinDocCount(minDocCount);
return this;
}
/**
* Set the minimum document count terms should have on the shard in order to
* appear in the response.
*/
public TermsAggregatorBuilder shardMinDocCount(long shardMinDocCount) {
if (shardMinDocCount < 0) {
throw new IllegalArgumentException(
"[shardMinDocCount] must be greater than or equal to 0. Found [" + shardMinDocCount + "] in [" + name + "]");
}
bucketCountThresholds.setShardMinDocCount(shardMinDocCount);
return this;
}
/**
* Sets the order in which the buckets will be returned.
*/
public TermsAggregatorBuilder order(Terms.Order order) {
if (order == null) {
throw new IllegalArgumentException("[order] must not be null: [" + name + "]");
}
this.order = order;
return this;
}
/**
* Sets the order in which the buckets will be returned.
*/
public TermsAggregatorBuilder order(List<Terms.Order> orders) {
if (orders == null) {
throw new IllegalArgumentException("[orders] must not be null: [" + name + "]");
}
order(Terms.Order.compound(orders));
return this;
}
/**
* Gets the order in which the buckets will be returned.
*/
public Terms.Order order() {
return order;
}
/**
* Expert: sets an execution hint to the aggregation.
*/
public TermsAggregatorBuilder executionHint(String executionHint) {
this.executionHint = executionHint;
return this;
}
/**
* Expert: gets an execution hint to the aggregation.
*/
public String executionHint() {
return executionHint;
}
/**
* Expert: set the collection mode.
*/
public TermsAggregatorBuilder collectMode(SubAggCollectionMode collectMode) {
if (collectMode == null) {
throw new IllegalArgumentException("[collectMode] must not be null: [" + name + "]");
}
this.collectMode = collectMode;
return this;
}
/**
* Expert: get the collection mode.
*/
public SubAggCollectionMode collectMode() {
return collectMode;
}
/**
* Set terms to include and exclude from the aggregation results
*/
public TermsAggregatorBuilder includeExclude(IncludeExclude includeExclude) {
this.includeExclude = includeExclude;
return this;
}
/**
* Get terms to include and exclude from the aggregation results
*/
public IncludeExclude includeExclude() {
return includeExclude;
}
/**
* Get whether doc count error will be return for individual terms
*/
public boolean showTermDocCountError() {
return showTermDocCountError;
}
/**
* Set whether doc count error will be return for individual terms
*/
public TermsAggregatorBuilder showTermDocCountError(boolean showTermDocCountError) {
this.showTermDocCountError = showTermDocCountError;
return this;
}
@Override
protected ValuesSourceAggregatorFactory<ValuesSource, ?> innerBuild(AggregationContext context, ValuesSourceConfig<ValuesSource> config,
AggregatorFactory<?> parent, Builder subFactoriesBuilder) throws IOException {
return new TermsAggregatorFactory(name, type, config, order, includeExclude, executionHint, collectMode,
bucketCountThresholds,
showTermDocCountError, context, parent, subFactoriesBuilder, metaData);
}
@Override
protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
bucketCountThresholds.toXContent(builder, params);
builder.field(SHOW_TERM_DOC_COUNT_ERROR.getPreferredName(), showTermDocCountError);
if (executionHint != null) {
builder.field(TermsAggregatorBuilder.EXECUTION_HINT_FIELD_NAME.getPreferredName(), executionHint);
}
builder.field(ORDER_FIELD.getPreferredName());
order.toXContent(builder, params);
builder.field(SubAggCollectionMode.KEY.getPreferredName(), collectMode.parseField().getPreferredName());
if (includeExclude != null) {
includeExclude.toXContent(builder, params);
}
return builder;
}
@Override
protected TermsAggregatorBuilder innerReadFrom(String name, ValuesSourceType valuesSourceType,
ValueType targetValueType, StreamInput in) throws IOException {
TermsAggregatorBuilder factory = new TermsAggregatorBuilder(name, targetValueType);
factory.bucketCountThresholds = BucketCountThresholds.readFromStream(in);
factory.collectMode = SubAggCollectionMode.BREADTH_FIRST.readFrom(in);
factory.executionHint = in.readOptionalString();
if (in.readBoolean()) {
factory.includeExclude = IncludeExclude.readFromStream(in);
}
factory.order = InternalOrder.Streams.readOrder(in);
factory.showTermDocCountError = in.readBoolean();
return factory;
}
@Override
protected void innerWriteTo(StreamOutput out) throws IOException {
bucketCountThresholds.writeTo(out);
collectMode.writeTo(out);
out.writeOptionalString(executionHint);
boolean hasIncExc = includeExclude != null;
out.writeBoolean(hasIncExc);
if (hasIncExc) {
includeExclude.writeTo(out);
}
InternalOrder.Streams.writeOrder(order, out);
out.writeBoolean(showTermDocCountError);
}
@Override
protected int innerHashCode() {
return Objects.hash(bucketCountThresholds, collectMode, executionHint, includeExclude, order, showTermDocCountError);
}
@Override
protected boolean innerEquals(Object obj) {
TermsAggregatorBuilder other = (TermsAggregatorBuilder) obj;
return Objects.equals(bucketCountThresholds, other.bucketCountThresholds)
&& Objects.equals(collectMode, other.collectMode)
&& Objects.equals(executionHint, other.executionHint)
&& Objects.equals(includeExclude, other.includeExclude)
&& Objects.equals(order, other.order)
&& Objects.equals(showTermDocCountError, other.showTermDocCountError);
}
}
| {'content_hash': '385ad995b522c67066c919bde0e7fcc6', 'timestamp': '', 'source': 'github', 'line_count': 283, 'max_line_length': 140, 'avg_line_length': 39.724381625441694, 'alnum_prop': 0.6944493862302081, 'repo_name': 'jbertouch/elasticsearch', 'id': 'bc0c593d4bed71d3b3cba9f24924c0387f0f6d3e', 'size': '12030', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/TermsAggregatorBuilder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '8172'}, {'name': 'Batchfile', 'bytes': '11683'}, {'name': 'Emacs Lisp', 'bytes': '3341'}, {'name': 'FreeMarker', 'bytes': '45'}, {'name': 'Groovy', 'bytes': '208816'}, {'name': 'HTML', 'bytes': '5595'}, {'name': 'Java', 'bytes': '33336597'}, {'name': 'Perl', 'bytes': '6923'}, {'name': 'Python', 'bytes': '75439'}, {'name': 'Ruby', 'bytes': '1917'}, {'name': 'Shell', 'bytes': '90887'}]} |
<!-- HTML header for doxygen 1.8.10-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>Intel® Enhanced Privacy ID SDK: Epid11GtElemStr Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="epidstyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname"><a
onclick="storeLink('index.html')"
id="projectlink"
class="index.html"
href="index.html">Intel® Enhanced Privacy ID SDK</a>
 <span id="projectnumber">8.0.0</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('struct_epid11_gt_elem_str.html','');});
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#pub-attribs">Data Fields</a> </div>
<div class="headertitle">
<div class="title">Epid11GtElemStr Struct Reference<div class="ingroups"><a class="el" href="group___epid_module.html">epid</a> » <a class="el" href="group___epid_common.html">common</a> » <a class="el" href="group___epid_types.html">types</a> » <a class="el" href="group___epid11_types.html">Intel(R) EPID 1.1 specific types</a></div></div> </div>
</div><!--header-->
<div class="contents">
<p>Serialized Intel(R) EPID 1.1 GT element.
<a href="struct_epid11_gt_elem_str.html#details">More...</a></p>
<p><code>#include <epid/defs/include/epid/1.1/types.h></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Data Fields</h2></td></tr>
<tr class="memitem:aed8dd86f1696c2f3537154fc904bf2b0"><td class="memItemLeft" align="right" valign="top"><a id="aed8dd86f1696c2f3537154fc904bf2b0"></a>
<a class="el" href="struct_fq3_elem_str.html">Fq3ElemStr</a> </td><td class="memItemRight" valign="bottom"><a class="el" href="struct_epid11_gt_elem_str.html#aed8dd86f1696c2f3537154fc904bf2b0">a</a> [2]</td></tr>
<tr class="memdesc:aed8dd86f1696c2f3537154fc904bf2b0"><td class="mdescLeft"> </td><td class="mdescRight">an element in Fq3 <br /></td></tr>
<tr class="separator:aed8dd86f1696c2f3537154fc904bf2b0"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><p>Serialized Intel(R) EPID 1.1 GT element. </p>
</div><hr/>The documentation for this struct was generated from the following file:<ul>
<li>epid/defs/include/epid/1.1/<a class="el" href="1_81_2types_8h.html">types.h</a></li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- HTML footer for doxygen 1.8.10-->
<!-- start footer part -->
<div id="nav-path" class="navpath">
<!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="struct_epid11_gt_elem_str.html">Epid11GtElemStr</a></li>
<li class="footer">
© 2016-2018 Intel Corporation
</li>
</ul>
</div>
</body>
</html>
| {'content_hash': '5c15d7793187cd45eba01d713952cabf', 'timestamp': '', 'source': 'github', 'line_count': 97, 'max_line_length': 367, 'avg_line_length': 46.04123711340206, 'alnum_prop': 0.6549484997760859, 'repo_name': 'Intel-EPID-SDK/epid-sdk', 'id': '09a35db29c4c740557ad8ca16b2df3ee105ff66e', 'size': '4466', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/html/struct_epid11_gt_elem_str.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '2514793'}, {'name': 'Batchfile', 'bytes': '1513'}, {'name': 'C', 'bytes': '12206600'}, {'name': 'C++', 'bytes': '3886712'}, {'name': 'CMake', 'bytes': '169664'}, {'name': 'Makefile', 'bytes': '4525'}, {'name': 'POV-Ray SDL', 'bytes': '10723'}, {'name': 'Python', 'bytes': '430736'}, {'name': 'Shell', 'bytes': '10087'}, {'name': 'Starlark', 'bytes': '13532'}]} |
include Java
include_class('java.lang.Integer') {|package,name| "J#{name}" }
include_class('java.lang.Long') {|package,name| "J#{name}" }
include_class('java.lang.Boolean') {|package,name| "J#{name}" }
module HBaseConstants
COLUMN = "COLUMN"
COLUMNS = "COLUMNS"
TIMESTAMP = "TIMESTAMP"
TIMERANGE = "TIMERANGE"
NAME = org.apache.hadoop.hbase.HConstants::NAME
VERSIONS = org.apache.hadoop.hbase.HConstants::VERSIONS
IN_MEMORY = org.apache.hadoop.hbase.HConstants::IN_MEMORY
STOPROW = "STOPROW"
STARTROW = "STARTROW"
ENDROW = STOPROW
RAW = "RAW"
LIMIT = "LIMIT"
METHOD = "METHOD"
MAXLENGTH = "MAXLENGTH"
CACHE_BLOCKS = "CACHE_BLOCKS"
REPLICATION_SCOPE = "REPLICATION_SCOPE"
INTERVAL = 'INTERVAL'
CACHE = 'CACHE'
FILTER = 'FILTER'
SPLITS = 'SPLITS'
SPLITS_FILE = 'SPLITS_FILE'
SPLITALGO = 'SPLITALGO'
NUMREGIONS = 'NUMREGIONS'
# Load constants from hbase java API
def self.promote_constants(constants)
# The constants to import are all in uppercase
constants.each do |c|
next if c =~ /DEFAULT_.*/ || c != c.upcase
next if eval("defined?(#{c})")
eval("#{c} = '#{c}'")
end
end
promote_constants(org.apache.hadoop.hbase.HColumnDescriptor.constants)
promote_constants(org.apache.hadoop.hbase.HTableDescriptor.constants)
end
# Include classes definition
require 'hbase/hbase'
require 'hbase/admin'
require 'hbase/table'
require 'hbase/replication_admin'
require 'hbase/security'
| {'content_hash': 'f3cae5dcfce84dedfd23f511e71e803e', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 72, 'avg_line_length': 28.647058823529413, 'alnum_prop': 0.6947296372347707, 'repo_name': 'indi60/hbase-pmc', 'id': '2a4abcb2ed7a28de6dfd2b16b96031d2208d11db', 'size': '2774', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'target/hbase-0.94.1/hbase-0.94.1/lib/ruby/hbase.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '19836'}, {'name': 'CSS', 'bytes': '36615'}, {'name': 'Java', 'bytes': '25566933'}, {'name': 'Makefile', 'bytes': '2514'}, {'name': 'PHP', 'bytes': '14700'}, {'name': 'Perl', 'bytes': '17496'}, {'name': 'Python', 'bytes': '29070'}, {'name': 'Ruby', 'bytes': '739196'}, {'name': 'Shell', 'bytes': '162419'}, {'name': 'Thrift', 'bytes': '69092'}, {'name': 'XSLT', 'bytes': '7010'}]} |
<!doctype html>
<html>
<title>npm-logout</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-logout.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-logout.html">npm-logout</a></h1> <p>Log out of the registry</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm logout [--registry=<url>] [--scope=<@scope>]
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>When logged into a registry that supports token-based authentication, tell the
server to end this token's session. This will invalidate the token everywhere
you're using it, not just for the current environment.</p>
<p>When logged into a legacy registry that uses username and password authentication, this will
clear the credentials in your user configuration. In this case, it will <em>only</em> affect
the current environment.</p>
<p>If <code>--scope</code> is provided, this will find the credentials for the registry
connected to that scope, if set.</p>
<h2 id="configuration">CONFIGURATION</h2>
<h3 id="registry">registry</h3>
<p>Default: <a href="http://registry.npmjs.org/">http://registry.npmjs.org/</a></p>
<p>The base URL of the npm package registry. If <code>scope</code> is also specified,
it takes precedence.</p>
<h3 id="scope">scope</h3>
<p>Default: none</p>
<p>If specified, the user and login credentials given will be associated
with the specified scope. See <code><a href="../misc/npm-scope.html">npm-scope(7)</a></code>. You can use both at the same time,
e.g.</p>
<pre><code>npm adduser --registry=http://myregistry.example.com --scope=@myco
</code></pre><p>This will set a registry for the given scope and login or create a user for
that registry at the same time.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-adduser.html">npm-adduser(1)</a></li>
<li><a href="../misc/npm-registry.html">npm-registry(7)</a></li>
<li><a href="../cli/npm-config.html">npm-config(1)</a></li>
<li><a href="../misc/npm-config.html">npm-config(7)</a></li>
<li><a href="../files/npmrc.html">npmrc(5)</a></li>
<li><a href="../cli/npm-whoami.html">npm-whoami(1)</a></li>
</ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-logout — [email protected]</p>
| {'content_hash': '04b60ecd86935c397ff2415ffcfa6aad', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 807, 'avg_line_length': 75.59322033898304, 'alnum_prop': 0.707847533632287, 'repo_name': 'node-hocus-pocus/thaumaturgy', 'id': '0a8a14d794858cdd5b9567e07aab9518fe718d49', 'size': '4460', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/npm3/html/doc/cli/npm-logout.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1572'}, {'name': 'CSS', 'bytes': '11270'}, {'name': 'Groff', 'bytes': '602872'}, {'name': 'HTML', 'bytes': '1281248'}, {'name': 'JavaScript', 'bytes': '1612736'}, {'name': 'Makefile', 'bytes': '10146'}, {'name': 'Shell', 'bytes': '40429'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 09 17:08:24 PDT 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class com.fasterxml.jackson.databind.deser.DeserializerFactory (jackson-databind 2.1.0 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.databind.deser.DeserializerFactory (jackson-databind 2.1.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/fasterxml/jackson/databind/deser//class-useDeserializerFactory.html" target="_top"><B>FRAMES</B></A>
<A HREF="DeserializerFactory.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>com.fasterxml.jackson.databind.deser.DeserializerFactory</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#com.fasterxml.jackson.databind"><B>com.fasterxml.jackson.databind</B></A></TD>
<TD>Contains basic mapper (conversion) functionality that
allows for converting between regular streaming json content and
Java objects (beans or Tree Model: support for both is via
<A HREF="../../../../../../com/fasterxml/jackson/databind/ObjectMapper.html" title="class in com.fasterxml.jackson.databind"><CODE>ObjectMapper</CODE></A> class, as well
as convenience methods included in
<A HREF="http://fasterxml.github.com/jackson-core/javadoc/2.1.0/com/fasterxml/jackson/core/JsonParser.html?is-external=true" title="class or interface in com.fasterxml.jackson.core"><CODE>JsonParser</CODE></A> </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#com.fasterxml.jackson.databind.deser"><B>com.fasterxml.jackson.databind.deser</B></A></TD>
<TD>Contains implementation classes of deserialization part of
data binding. </TD>
</TR>
</TABLE>
<P>
<A NAME="com.fasterxml.jackson.databind"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> in <A HREF="../../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</A> declared as <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>DeserializationContext.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html#_factory">_factory</A></B></CODE>
<BR>
Read-only factory instance; exposed to let
owners (<code>ObjectMapper</code>, <code>ObjectReader</code>)
access it.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</A> that return <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>DeserializationContext.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html#getFactory()">getFactory</A></B>()</CODE>
<BR>
Method for getting current <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser"><CODE>DeserializerFactory</CODE></A>.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../../com/fasterxml/jackson/databind/package-summary.html">com.fasterxml.jackson.databind</A> with parameters of type <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html#DeserializationContext(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.deser.DeserializerFactory)">DeserializationContext</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html" title="class in com.fasterxml.jackson.databind">DeserializationContext</A> src,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html#DeserializationContext(com.fasterxml.jackson.databind.deser.DeserializerFactory)">DeserializationContext</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> df)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html#DeserializationContext(com.fasterxml.jackson.databind.deser.DeserializerFactory, com.fasterxml.jackson.databind.deser.DeserializerCache)">DeserializationContext</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> df,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerCache</A> cache)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="com.fasterxml.jackson.databind.deser"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> in <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/package-summary.html">com.fasterxml.jackson.databind.deser</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Subclasses of <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> in <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/package-summary.html">com.fasterxml.jackson.databind.deser</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">BasicDeserializerFactory</A></B></CODE>
<BR>
Abstract factory base class that can provide deserializers for standard
JDK classes, including collection classes and simple heuristics for
"upcasting" commmon collection interface types
(such as <A HREF="http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html?is-external=true" title="class or interface in java.util"><CODE>Collection</CODE></A>).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">BeanDeserializerFactory</A></B></CODE>
<BR>
Concrete deserializer factory class that adds full Bean deserializer
construction logic using class introspection.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/package-summary.html">com.fasterxml.jackson.databind.deser</A> that return <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>DeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html#withAbstractTypeResolver(com.fasterxml.jackson.databind.AbstractTypeResolver)">withAbstractTypeResolver</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/AbstractTypeResolver.html" title="class in com.fasterxml.jackson.databind">AbstractTypeResolver</A> resolver)</CODE>
<BR>
Convenience method for creating a new factory instance with additional
<A HREF="../../../../../../com/fasterxml/jackson/databind/AbstractTypeResolver.html" title="class in com.fasterxml.jackson.databind"><CODE>AbstractTypeResolver</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>BasicDeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.html#withAbstractTypeResolver(com.fasterxml.jackson.databind.AbstractTypeResolver)">withAbstractTypeResolver</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/AbstractTypeResolver.html" title="class in com.fasterxml.jackson.databind">AbstractTypeResolver</A> resolver)</CODE>
<BR>
Convenience method for creating a new factory instance with additional
<A HREF="../../../../../../com/fasterxml/jackson/databind/AbstractTypeResolver.html" title="class in com.fasterxml.jackson.databind"><CODE>AbstractTypeResolver</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>DeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html#withAdditionalDeserializers(com.fasterxml.jackson.databind.deser.Deserializers)">withAdditionalDeserializers</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/Deserializers.html" title="interface in com.fasterxml.jackson.databind.deser">Deserializers</A> additional)</CODE>
<BR>
Convenience method for creating a new factory instance with additional deserializer
provider.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>BasicDeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.html#withAdditionalDeserializers(com.fasterxml.jackson.databind.deser.Deserializers)">withAdditionalDeserializers</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/Deserializers.html" title="interface in com.fasterxml.jackson.databind.deser">Deserializers</A> additional)</CODE>
<BR>
Convenience method for creating a new factory instance with additional deserializer
provider.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>DeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html#withAdditionalKeyDeserializers(com.fasterxml.jackson.databind.deser.KeyDeserializers)">withAdditionalKeyDeserializers</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/KeyDeserializers.html" title="interface in com.fasterxml.jackson.databind.deser">KeyDeserializers</A> additional)</CODE>
<BR>
Convenience method for creating a new factory instance with additional
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/KeyDeserializers.html" title="interface in com.fasterxml.jackson.databind.deser"><CODE>KeyDeserializers</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>BasicDeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.html#withAdditionalKeyDeserializers(com.fasterxml.jackson.databind.deser.KeyDeserializers)">withAdditionalKeyDeserializers</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/KeyDeserializers.html" title="interface in com.fasterxml.jackson.databind.deser">KeyDeserializers</A> additional)</CODE>
<BR>
Convenience method for creating a new factory instance with additional
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/KeyDeserializers.html" title="interface in com.fasterxml.jackson.databind.deser"><CODE>KeyDeserializers</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>BeanDeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.html#withConfig(com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig)">withConfig</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/cfg/DeserializerFactoryConfig.html" title="class in com.fasterxml.jackson.databind.cfg">DeserializerFactoryConfig</A> config)</CODE>
<BR>
Method used by module registration functionality, to construct a new bean
deserializer factory
with different configuration settings.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected abstract <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>BasicDeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.html#withConfig(com.fasterxml.jackson.databind.cfg.DeserializerFactoryConfig)">withConfig</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/cfg/DeserializerFactoryConfig.html" title="class in com.fasterxml.jackson.databind.cfg">DeserializerFactoryConfig</A> config)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>DeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html#withDeserializerModifier(com.fasterxml.jackson.databind.deser.BeanDeserializerModifier)">withDeserializerModifier</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BeanDeserializerModifier.html" title="class in com.fasterxml.jackson.databind.deser">BeanDeserializerModifier</A> modifier)</CODE>
<BR>
Convenience method for creating a new factory instance with additional
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BeanDeserializerModifier.html" title="class in com.fasterxml.jackson.databind.deser"><CODE>BeanDeserializerModifier</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>BasicDeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.html#withDeserializerModifier(com.fasterxml.jackson.databind.deser.BeanDeserializerModifier)">withDeserializerModifier</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BeanDeserializerModifier.html" title="class in com.fasterxml.jackson.databind.deser">BeanDeserializerModifier</A> modifier)</CODE>
<BR>
Convenience method for creating a new factory instance with additional
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BeanDeserializerModifier.html" title="class in com.fasterxml.jackson.databind.deser"><CODE>BeanDeserializerModifier</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>DeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html#withValueInstantiators(com.fasterxml.jackson.databind.deser.ValueInstantiators)">withValueInstantiators</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/ValueInstantiators.html" title="interface in com.fasterxml.jackson.databind.deser">ValueInstantiators</A> instantiators)</CODE>
<BR>
Convenience method for creating a new factory instance with additional
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/ValueInstantiators.html" title="interface in com.fasterxml.jackson.databind.deser"><CODE>ValueInstantiators</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></CODE></FONT></TD>
<TD><CODE><B>BasicDeserializerFactory.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.html#withValueInstantiators(com.fasterxml.jackson.databind.deser.ValueInstantiators)">withValueInstantiators</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/ValueInstantiators.html" title="interface in com.fasterxml.jackson.databind.deser">ValueInstantiators</A> instantiators)</CODE>
<BR>
Convenience method for creating a new factory instance with additional
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/ValueInstantiators.html" title="interface in com.fasterxml.jackson.databind.deser"><CODE>ValueInstantiators</CODE></A>.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/package-summary.html">com.fasterxml.jackson.databind.deser</A> with parameters of type <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../com/fasterxml/jackson/databind/JsonDeserializer.html" title="class in com.fasterxml.jackson.databind">JsonDeserializer</A><<A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A>></CODE></FONT></TD>
<TD><CODE><B>DeserializerCache.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html#_createAndCache2(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.deser.DeserializerFactory, com.fasterxml.jackson.databind.JavaType)">_createAndCache2</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html" title="class in com.fasterxml.jackson.databind">DeserializationContext</A> ctxt,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory,
<A HREF="../../../../../../com/fasterxml/jackson/databind/JavaType.html" title="class in com.fasterxml.jackson.databind">JavaType</A> type)</CODE>
<BR>
Method that handles actual construction (via factory) and caching (both
intermediate and eventual)</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../com/fasterxml/jackson/databind/JsonDeserializer.html" title="class in com.fasterxml.jackson.databind">JsonDeserializer</A><<A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A>></CODE></FONT></TD>
<TD><CODE><B>DeserializerCache.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html#_createAndCacheValueDeserializer(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.deser.DeserializerFactory, com.fasterxml.jackson.databind.JavaType)">_createAndCacheValueDeserializer</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html" title="class in com.fasterxml.jackson.databind">DeserializationContext</A> ctxt,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory,
<A HREF="../../../../../../com/fasterxml/jackson/databind/JavaType.html" title="class in com.fasterxml.jackson.databind">JavaType</A> type)</CODE>
<BR>
Method that will try to create a deserializer for given type,
and resolve and cache it if necessary</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../com/fasterxml/jackson/databind/JsonDeserializer.html" title="class in com.fasterxml.jackson.databind">JsonDeserializer</A><<A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A>></CODE></FONT></TD>
<TD><CODE><B>DeserializerCache.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html#_createDeserializer(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.deser.DeserializerFactory, com.fasterxml.jackson.databind.JavaType)">_createDeserializer</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html" title="class in com.fasterxml.jackson.databind">DeserializationContext</A> ctxt,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory,
<A HREF="../../../../../../com/fasterxml/jackson/databind/JavaType.html" title="class in com.fasterxml.jackson.databind">JavaType</A> type)</CODE>
<BR>
Method that does the heavy lifting of checking for per-type annotations,
find out full type, and figure out which actual factory method
to call.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/KeyDeserializer.html" title="class in com.fasterxml.jackson.databind">KeyDeserializer</A></CODE></FONT></TD>
<TD><CODE><B>DeserializerCache.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html#findKeyDeserializer(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.deser.DeserializerFactory, com.fasterxml.jackson.databind.JavaType)">findKeyDeserializer</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html" title="class in com.fasterxml.jackson.databind">DeserializationContext</A> ctxt,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory,
<A HREF="../../../../../../com/fasterxml/jackson/databind/JavaType.html" title="class in com.fasterxml.jackson.databind">JavaType</A> type)</CODE>
<BR>
Method called to get hold of a deserializer to use for deserializing
keys for <A HREF="http://docs.oracle.com/javase/6/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util"><CODE>Map</CODE></A>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/JsonDeserializer.html" title="class in com.fasterxml.jackson.databind">JsonDeserializer</A><<A HREF="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A>></CODE></FONT></TD>
<TD><CODE><B>DeserializerCache.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html#findValueDeserializer(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.deser.DeserializerFactory, com.fasterxml.jackson.databind.JavaType)">findValueDeserializer</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html" title="class in com.fasterxml.jackson.databind">DeserializationContext</A> ctxt,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory,
<A HREF="../../../../../../com/fasterxml/jackson/databind/JavaType.html" title="class in com.fasterxml.jackson.databind">JavaType</A> propertyType)</CODE>
<BR>
Method called to get hold of a deserializer for a value of given type;
or if no such deserializer can be found, a default handler (which
may do a best-effort generic serialization or just simply
throw an exception when invoked).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B>DeserializerCache.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html#hasValueDeserializerFor(com.fasterxml.jackson.databind.DeserializationContext, com.fasterxml.jackson.databind.deser.DeserializerFactory, com.fasterxml.jackson.databind.JavaType)">hasValueDeserializerFor</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/DeserializationContext.html" title="class in com.fasterxml.jackson.databind">DeserializationContext</A> ctxt,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory,
<A HREF="../../../../../../com/fasterxml/jackson/databind/JavaType.html" title="class in com.fasterxml.jackson.databind">JavaType</A> type)</CODE>
<BR>
Method called to find out whether provider would be able to find
a deserializer for given type, using a root reference (i.e.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.html" title="class in com.fasterxml.jackson.databind.deser">DefaultDeserializationContext</A></CODE></FONT></TD>
<TD><CODE><B>DefaultDeserializationContext.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.html#with(com.fasterxml.jackson.databind.deser.DeserializerFactory)">with</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory)</CODE>
<BR>
Fluent factory method used for constructing a blueprint instance
with different factory</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.html" title="class in com.fasterxml.jackson.databind.deser">DefaultDeserializationContext</A></CODE></FONT></TD>
<TD><CODE><B>DefaultDeserializationContext.Impl.</B><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.Impl.html#with(com.fasterxml.jackson.databind.deser.DeserializerFactory)">with</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/package-summary.html">com.fasterxml.jackson.databind.deser</A> with parameters of type <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.Impl.html#DefaultDeserializationContext.Impl(com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.Impl, com.fasterxml.jackson.databind.deser.DeserializerFactory)">DefaultDeserializationContext.Impl</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.Impl.html" title="class in com.fasterxml.jackson.databind.deser">DefaultDeserializationContext.Impl</A> src,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.Impl.html#DefaultDeserializationContext.Impl(com.fasterxml.jackson.databind.deser.DeserializerFactory)">DefaultDeserializationContext.Impl</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> df)</CODE>
<BR>
Default constructor for a blueprint object, which will use the standard
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html" title="class in com.fasterxml.jackson.databind.deser"><CODE>DeserializerCache</CODE></A>, given factory.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.html#DefaultDeserializationContext(com.fasterxml.jackson.databind.deser.DefaultDeserializationContext, com.fasterxml.jackson.databind.deser.DeserializerFactory)">DefaultDeserializationContext</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.html" title="class in com.fasterxml.jackson.databind.deser">DefaultDeserializationContext</A> src,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> factory)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DefaultDeserializationContext.html#DefaultDeserializationContext(com.fasterxml.jackson.databind.deser.DeserializerFactory, com.fasterxml.jackson.databind.deser.DeserializerCache)">DefaultDeserializationContext</A></B>(<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerFactory</A> df,
<A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerCache.html" title="class in com.fasterxml.jackson.databind.deser">DeserializerCache</A> cache)</CODE>
<BR>
Constructor that will pass specified deserializer factory and
cache: cache may be null (in which case default implementation
will be used), factory can not be null</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/fasterxml/jackson/databind/deser/DeserializerFactory.html" title="class in com.fasterxml.jackson.databind.deser"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/fasterxml/jackson/databind/deser//class-useDeserializerFactory.html" target="_top"><B>FRAMES</B></A>
<A HREF="DeserializerFactory.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2012 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.
</BODY>
</HTML>
| {'content_hash': '6dc409b838e2ec58c8a5593eae4ac0aa', 'timestamp': '', 'source': 'github', 'line_count': 522, 'max_line_length': 534, 'avg_line_length': 83.5536398467433, 'alnum_prop': 0.7055141579731744, 'repo_name': 'FasterXML/jackson-databind', 'id': 'a5e73199759e87ffdd38fce4f1e92aa7865e5a4f', 'size': '43615', 'binary': False, 'copies': '1', 'ref': 'refs/heads/2.15', 'path': 'docs/javadoc/2.1/com/fasterxml/jackson/databind/deser/class-use/DeserializerFactory.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '7940640'}, {'name': 'Logos', 'bytes': '173041'}, {'name': 'Shell', 'bytes': '264'}]} |
class AddVoteCacheColumnsToObservations < ActiveRecord::Migration
def change
add_column :observations, :cached_votes_total, :integer, :default => 0
add_index :observations, :cached_votes_total
end
end
| {'content_hash': '28e3eae0da673d080e3ce3f68c6a25ac', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 74, 'avg_line_length': 35.666666666666664, 'alnum_prop': 0.7570093457943925, 'repo_name': 'HotFusionMan/inaturalist', 'id': '44f706497af4bb36ea85696633918fc4c79b550d', 'size': '214', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'db/migrate/20150614212053_add_vote_cache_columns_to_observations.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '277452'}, {'name': 'HTML', 'bytes': '1530929'}, {'name': 'JavaScript', 'bytes': '918473'}, {'name': 'PHP', 'bytes': '9941'}, {'name': 'PLpgSQL', 'bytes': '414260'}, {'name': 'Ruby', 'bytes': '2580573'}, {'name': 'Shell', 'bytes': '1548'}, {'name': 'XSLT', 'bytes': '7923'}]} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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("Common.Piba")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Common.Piba")]
[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("dd8ea4fd-68a8-47f4-9c11-3951c3ccdaef")]
// 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 Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {'content_hash': '5927793dba5ffea0176055563c25e27b', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 84, 'avg_line_length': 38.75, 'alnum_prop': 0.7433691756272401, 'repo_name': 'eladmatari/UmbracoPropertiesGenerator', 'id': '15eb0dc22715d9336c0862bc876ad4feae81cc27', 'size': '1398', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Common.Piba/Properties/AssemblyInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '273694'}, {'name': 'C#', 'bytes': '99585'}, {'name': 'CSS', 'bytes': '271916'}, {'name': 'HTML', 'bytes': '706233'}, {'name': 'JavaScript', 'bytes': '4667042'}, {'name': 'XSLT', 'bytes': '48541'}]} |
<resources>
<style name="Material"></style>
<style name="Material.Drawable"></style>
<style name="Material.Widget"></style>
<style name="Material.App"></style>
<style name="Material.TextAppearance"></style>
<style name="Material.Drawable.CircularProgress">
<item name="cpd_padding">0dp</item>
<item name="cpd_initialAngle">0</item>
<item name="cpd_maxSweepAngle">270</item>
<item name="cpd_minSweepAngle">1</item>
<item name="cpd_strokeSize">4dp</item>
<item name="cpd_strokeColor">?attr/colorPrimary</item>
<item name="cpd_strokeSecondaryColor">@android:color/transparent</item>
<item name="cpd_reverse">false</item>
<item name="cpd_rotateDuration">1000</item>
<item name="cpd_transformDuration">600</item>
<item name="cpd_keepDuration">200</item>
<item name="cpd_transformInterpolator">@android:anim/decelerate_interpolator</item>
<item name="pv_progressMode">indeterminate</item>
<item name="cpd_inAnimDuration">0</item>
<item name="cpd_outAnimDuration">@android:integer/config_mediumAnimTime</item>
</style>
<style name="Material.Drawable.CircularProgress.Determinate" parent="Material.Drawable.CircularProgress">
<item name="pv_progressMode">determinate</item>
<item name="cpd_inAnimDuration">@android:integer/config_mediumAnimTime</item>
</style>
<style name="Material.Drawable.LinearProgress">
<item name="lpd_maxLineWidth">75%</item>
<item name="lpd_minLineWidth">10%</item>
<item name="lpd_strokeSize">4dp</item>
<item name="lpd_strokeColor">?attr/colorPrimary</item>
<item name="lpd_strokeSecondaryColor">?attr/colorControlNormal</item>
<item name="lpd_reverse">false</item>
<item name="lpd_travelDuration">1000</item>
<item name="lpd_transformDuration">600</item>
<item name="lpd_keepDuration">200</item>
<item name="lpd_transformInterpolator">@android:anim/decelerate_interpolator</item>
<item name="pv_progressMode">indeterminate</item>
<item name="lpd_inAnimDuration">@android:integer/config_mediumAnimTime</item>
<item name="lpd_outAnimDuration">@android:integer/config_mediumAnimTime</item>
<item name="lpd_verticalAlign">bottom</item>
</style>
<style name="Material.Drawable.LinearProgress.Determinate" parent="Material.Drawable.LinearProgress">
<item name="pv_progressMode">determinate</item>
</style>
<style name="Material.Drawable.LinearProgress.Query" parent="Material.Drawable.LinearProgress">
<item name="pv_progressMode">query</item>
</style>
<style name="Material.Drawable.LinearProgress.Buffer" parent="Material.Drawable.LinearProgress">
<item name="pv_progressMode">buffer</item>
</style>
<style name="Material.Widget.ProgressView">
<item name="pv_progress">0</item>
</style>
<style name="Material.Widget.ProgressView.Circular" parent="Material.Widget.ProgressView">
<item name="pv_autostart">true</item>
<item name="pv_circular">true</item>
<item name="pv_progressStyle">@style/Material.Drawable.CircularProgress</item>
<item name="pv_progressMode">indeterminate</item>
</style>
<style name="Material.Widget.ProgressView.Circular.Determinate" parent="Material.Widget.ProgressView.Circular">
<item name="pv_progressStyle">@style/Material.Drawable.CircularProgress.Determinate</item>
<item name="pv_progressMode">determinate</item>
</style>
<style name="Material.Widget.ProgressView.Linear" parent="Material.Widget.ProgressView">
<item name="pv_autostart">true</item>
<item name="pv_circular">false</item>
<item name="pv_progressStyle">@style/Material.Drawable.LinearProgress</item>
<item name="pv_progressMode">indeterminate</item>
</style>
<style name="Material.Widget.ProgressView.Linear.Determinate" parent="Material.Widget.ProgressView.Linear">
<item name="pv_progressStyle">@style/Material.Drawable.LinearProgress.Determinate</item>
<item name="pv_progressMode">determinate</item>
</style>
<style name="Material.Widget.ProgressView.Linear.Query" parent="Material.Widget.ProgressView.Linear">
<item name="pv_progressStyle">@style/Material.Drawable.LinearProgress.Query</item>
<item name="pv_progressMode">query</item>
</style>
<style name="Material.Widget.ProgressView.Linear.Buffer" parent="Material.Widget.ProgressView.Linear">
<item name="pv_progressStyle">@style/Material.Drawable.LinearProgress.Buffer</item>
<item name="pv_progressMode">buffer</item>
</style>
<style name="Material.Drawable.Ripple">
<item name="rd_enable">true</item>
<item name="rd_inInterpolator">@android:anim/decelerate_interpolator</item>
<item name="rd_outInterpolator">@android:anim/decelerate_interpolator</item>
<item name="rd_maskType">rectangle</item>
<item name="rd_cornerRadius">2dp</item>
<item name="rd_padding">0dp</item>
<item name="rd_delayClick">none</item>
</style>
<style name="Material.Drawable.Ripple.Touch" parent="Material.Drawable.Ripple">
<item name="rd_backgroundColor">#26CCCCCC</item>
<item name="rd_backgroundAnimDuration">200</item>
<item name="rd_maxRippleRadius">48dp</item>
<item name="rd_rippleColor">#19CCCCCC</item>
<item name="rd_rippleAnimDuration">300</item>
<item name="rd_rippleType">touch</item>
</style>
<style name="Material.Drawable.Ripple.Touch.MatchView" parent="Material.Drawable.Ripple.Touch">
<item name="rd_maxRippleRadius">match_view</item>
</style>
<style name="Material.Drawable.Ripple.Touch.Light" parent="Material.Drawable.Ripple.Touch">
<item name="rd_backgroundColor">#33999999</item>
<item name="rd_rippleColor">#33999999</item>
</style>
<style name="Material.Drawable.Ripple.Touch.MatchView.Light" parent="Material.Drawable.Ripple.Touch">
<item name="rd_maxRippleRadius">match_view</item>
<item name="rd_backgroundColor">#33999999</item>
<item name="rd_rippleColor">#33999999</item>
</style>
<style name="Material.Drawable.Ripple.Wave" parent="Material.Drawable.Ripple">
<item name="rd_maxRippleRadius">48dp</item>
<item name="rd_rippleColor">#3FCCCCCC</item>
<item name="rd_rippleAnimDuration">200</item>
<item name="rd_rippleType">wave</item>
</style>
<style name="Material.Drawable.Ripple.Wave.Light" parent="Material.Drawable.Ripple.Wave">
<item name="rd_rippleColor">#66999999</item>
</style>
<style name="Material.Drawable.NavigationDrawerIcon">
<item name="lmd_state">@xml/nav_states</item>
<item name="lmd_curState">0</item>
<item name="lmd_padding">6dp</item>
<item name="lmd_animDuration">@android:integer/config_mediumAnimTime</item>
<item name="lmd_interpolator">@android:anim/accelerate_decelerate_interpolator</item>
<item name="lmd_strokeSize">3dp</item>
<item name="lmd_strokeColor">#FFFFFFFF</item>
<item name="lmd_strokeCap">butt</item>
<item name="lmd_strokeJoin">miter</item>
<item name="lmd_clockwise">true</item>
<item name="lmd_layoutDirection">locale</item>
</style>
<style name="Material.Drawable.NavigationDrawerIcon.Light" parent="Material.Drawable.NavigationDrawerIcon">
<item name="lmd_strokeColor">#87000000</item>
</style>
<style name="Material.Drawable.NavigationDrawer">
<item name="nd_ripple">@style/Material.Drawable.Ripple.Touch</item>
<item name="nd_icon">@style/Material.Drawable.NavigationDrawerIcon</item>
</style>
<style name="Material.Drawable.NavigationDrawer.Light">
<item name="nd_ripple">@style/Material.Drawable.Ripple.Touch.Light</item>
<item name="nd_icon">@style/Material.Drawable.NavigationDrawerIcon.Light</item>
</style>
<style name="Material.Drawable.RadioButton">
<item name="rbd_width">32dp</item>
<item name="rbd_height">32dp</item>
<item name="rbd_strokeSize">2dp</item>
<item name="rbd_radius">10dp</item>
<item name="rbd_innerRadius">5dp</item>
<item name="rbd_animDuration">@android:integer/config_mediumAnimTime</item>
</style>
<style name="Material.Drawable.CheckBox">
<item name="cbd_width">32dp</item>
<item name="cbd_height">32dp</item>
<item name="cbd_boxSize">20dp</item>
<item name="cbd_cornerRadius">2dp</item>
<item name="cbd_strokeSize">2dp</item>
<item name="cbd_animDuration">@android:integer/config_mediumAnimTime</item>
</style>
<style name="Material.Widget.Switch">
<item name="sw_trackSize">14dp</item>
<item name="sw_trackCap">round</item>
<item name="sw_thumbRadius">10dp</item>
<item name="sw_thumbElevation">2dp</item>
<item name="sw_animDuration">@android:integer/config_shortAnimTime</item>
<item name="sw_interpolator">@android:anim/decelerate_interpolator</item>
</style>
<style name="Material.Widget.Slider">
<item name="sl_trackSize">2dp</item>
<item name="sl_trackCap">square</item>
<item name="sl_thumbBorderSize">2dp</item>
<item name="sl_thumbRadius">10dp</item>
<item name="sl_thumbFocusRadius">14dp</item>
<item name="sl_travelAnimDuration">@android:integer/config_mediumAnimTime</item>
<item name="sl_transformAnimDuration">@android:integer/config_shortAnimTime</item>
<item name="sl_interpolator">@android:anim/decelerate_interpolator</item>
<item name="sl_minValue">0</item>
<item name="sl_maxValue">100</item>
<item name="sl_stepValue">1</item>
<item name="sl_value">0</item>
<item name="sl_discreteMode">false</item>
<item name="sl_textSize">@dimen/abc_text_size_small_material</item>
<item name="sl_textColor">#FFFFFFFF</item>
</style>
<style name="Material.Widget.Slider.Discrete" parent="Material.Widget.Slider">
<item name="sl_discreteMode">true</item>
</style>
<style name="Material.Widget.TabPageIndicator">
<item name="tpi_tabPadding">12dp</item>
<item name="tpi_tabRipple">@style/Material.Drawable.Ripple.Wave</item>
<item name="tpi_indicatorHeight">2dp</item>
<item name="android:textAppearance">?attr/textAppearanceListItem</item>
<item name="tpi_mode">scroll</item>
</style>
<style name="Material.Widget.TabPageIndicator.Light" parent="Material.Widget.TabPageIndicator">
<item name="tpi_tabRipple">@style/Material.Drawable.Ripple.Wave.Light</item>
</style>
<style name="Material.Widget.TabPageIndicator.Fixed" parent="Material.Widget.TabPageIndicator">
<item name="tpi_mode">fixed</item>
</style>
<style name="Material.Widget.TabPageIndicator.Fixed.Light" parent="Material.Widget.TabPageIndicator.Light">
<item name="tpi_mode">fixed</item>
</style>
<style name="Material.Widget.FloatingActionButton" parent="Material.Drawable.Ripple.Touch">
<item name="fab_radius">28dp</item>
<item name="fab_elevation">4dp</item>
<item name="fab_iconSize">24dp</item>
<item name="fab_interpolator">@android:anim/decelerate_interpolator</item>
<item name="fab_animDuration">@android:integer/config_mediumAnimTime</item>
</style>
<style name="Material.Widget.FloatingActionButton.Light" parent="Material.Drawable.Ripple.Touch.Light">
<item name="fab_radius">28dp</item>
<item name="fab_elevation">4dp</item>
<item name="fab_iconSize">24dp</item>
<item name="fab_interpolator">@android:anim/decelerate_interpolator</item>
<item name="fab_animDuration">@android:integer/config_mediumAnimTime</item>
</style>
<style name="Material.Widget.FloatingActionButton.Mini" parent="Material.Drawable.Ripple.Touch">
<item name="fab_radius">20dp</item>
<item name="fab_elevation">4dp</item>
<item name="fab_iconSize">24dp</item>
<item name="fab_interpolator">@android:anim/decelerate_interpolator</item>
<item name="fab_animDuration">@android:integer/config_mediumAnimTime</item>
</style>
<style name="Material.Widget.FloatingActionButton.Mini.Light" parent="Material.Drawable.Ripple.Touch.Light">
<item name="fab_radius">20dp</item>
<item name="fab_elevation">4dp</item>
<item name="fab_iconSize">24dp</item>
<item name="fab_interpolator">@android:anim/decelerate_interpolator</item>
<item name="fab_animDuration">@android:integer/config_mediumAnimTime</item>
</style>
<style name="Material.Widget.SnackBar">
<item name="sb_backgroundColor">#FF323232</item>
<item name="sb_backgroundCornerRadius">0dp</item>
<item name="sb_horizontalPadding">24dp</item>
<item name="sb_verticalPadding">0dp</item>
<item name="sb_width">match_parent</item>
<item name="sb_height">48dp</item>
<item name="sb_textAppearance">@style/TextAppearance.AppCompat.Body1</item>
<item name="sb_textColor">#FFFFFFFF</item>
<item name="sb_ellipsize">end</item>
<item name="sb_actionTextAppearance">@style/TextAppearance.AppCompat.Button</item>
<item name="sb_actionTextColor">?attr/colorPrimary</item>
<item name="sb_actionRipple">@style/Material.Drawable.Ripple.Wave</item>
<item name="sb_inAnimation">@anim/abc_slide_in_bottom</item>
<item name="sb_outAnimation">@anim/abc_slide_out_bottom</item>
<item name="sb_removeOnDismiss">false</item>
</style>
<style name="Material.Widget.SnackBar.Mobile" parent="Material.Widget.SnackBar">
<item name="sb_marginStart">0dp</item>
<item name="sb_marginBottom">0dp</item>
<item name="sb_width">match_parent</item>
<item name="sb_height">48dp</item>
<item name="sb_singleLine">true</item>
</style>
<style name="Material.Widget.SnackBar.Mobile.MultiLine" parent="Material.Widget.SnackBar.Mobile">
<item name="sb_verticalPadding">18dp</item>
<item name="sb_height">wrap_content</item>
<item name="sb_singleLine">false</item>
<item name="sb_maxLines">2</item>
<item name="sb_maxHeight">80dp</item>
</style>
<style name="Material.Widget.SnackBar.Tablet" parent="Material.Widget.SnackBar">
<item name="sb_marginStart">16dp</item>
<item name="sb_marginBottom">16dp</item>
<item name="sb_width">wrap_content</item>
<item name="sb_height">48dp</item>
<item name="sb_singleLine">true</item>
<item name="sb_minWidth">288dp</item>
<item name="sb_maxWidth">568dp</item>
</style>
<style name="Material.Widget.SnackBar.Tablet.MultiLine" parent="Material.Widget.SnackBar.Tablet">
<item name="sb_verticalPadding">18dp</item>
<item name="sb_height">wrap_content</item>
<item name="sb_singleLine">false</item>
<item name="sb_maxLines">2</item>
<item name="sb_maxHeight">80dp</item>
</style>
<style name="Material.App.Dialog">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:windowIsFloating">false</item>
<item name="di_dimAmount">0.5</item>
<item name="di_backgroundColor">@color/background_floating_material_dark</item>
<item name="di_elevation">4dp</item>
<item name="di_maxElevation">4dp</item>
<item name="di_cornerRadius">2dp</item>
<item name="di_layoutDirection">locale</item>
<item name="di_titleTextAppearance">@style/TextAppearance.AppCompat.Title</item>
<item name="di_titleTextColor">@color/abc_primary_text_material_dark</item>
<item name="di_actionRipple">@style/Material.Drawable.Ripple.Wave</item>
<item name="di_actionTextAppearance">@style/TextAppearance.AppCompat.Button</item>
<item name="di_actionTextColor">?attr/colorControlActivated</item>
<item name="di_dividerColor">#1E999999</item>
<item name="di_dividerHeight">1dp</item>
<item name="di_cancelable">true</item>
<item name="di_canceledOnTouchOutside">true</item>
</style>
<style name="Material.App.Dialog.Light" parent="Material.App.Dialog">
<item name="di_backgroundColor">@color/background_floating_material_light</item>
<item name="di_titleTextColor">@color/abc_primary_text_material_light</item>
<item name="di_actionRipple">@style/Material.Drawable.Ripple.Wave.Light</item>
<item name="di_dividerColor">#1E000000</item>
</style>
<style name="Material.TextAppearance.SimpleDialog" parent="TextAppearance.AppCompat.Body1">
<item name="android:textColor">@color/abc_secondary_text_material_dark</item>
</style>
<style name="Material.TextAppearance.SimpleDialog.Light" parent="TextAppearance.AppCompat.Body1">
<item name="android:textColor">@color/abc_secondary_text_material_light</item>
</style>
<style name="Material.App.Dialog.Simple" parent="Material.App.Dialog">
<item name="di_messageTextAppearance">@style/TextAppearance.AppCompat.Body1</item>
<item name="di_messageTextColor">@color/abc_secondary_text_material_dark</item>
<item name="di_radioButtonStyle">@style/Material.Drawable.RadioButton</item>
<item name="di_checkBoxStyle">@style/Material.Drawable.CheckBox</item>
<item name="di_itemTextAppearance">@style/Material.TextAppearance.SimpleDialog</item>
<item name="di_itemHeight">48dp</item>
</style>
<style name="Material.App.Dialog.Simple.Light" parent="Material.App.Dialog.Light">
<item name="di_messageTextAppearance">@style/TextAppearance.AppCompat.Body1</item>
<item name="di_messageTextColor">@color/abc_secondary_text_material_light</item>
<item name="di_radioButtonStyle">@style/Material.Drawable.RadioButton</item>
<item name="di_checkBoxStyle">@style/Material.Drawable.CheckBox</item>
<item name="di_itemTextAppearance">@style/Material.TextAppearance.SimpleDialog.Light</item>
<item name="di_itemHeight">48dp</item>
</style>
<style name="Material.Widget.TimePicker">
<item name="tp_backgroundColor">#28999999</item>
<item name="tp_selectionColor">?attr/colorPrimary</item>
<item name="tp_selectionRadius">16dp</item>
<item name="tp_tickSize">1dp</item>
<item name="tp_textSize">@dimen/abc_text_size_caption_material</item>
<item name="tp_textStyle">normal</item>
<item name="tp_textColor">@color/abc_primary_text_material_dark</item>
<item name="tp_textHighlightColor">#FFFFFFFF</item>
<item name="tp_animDuration">@android:integer/config_mediumAnimTime</item>
<item name="tp_inInterpolator">@android:anim/decelerate_interpolator</item>
<item name="tp_outInterpolator">@android:anim/decelerate_interpolator</item>
<item name="tp_mode">hour</item>
</style>
<style name="Material.Widget.TimePicker.Light" parent="Material.Widget.TimePicker">
<item name="tp_textColor">@color/abc_primary_text_material_light</item>
</style>
<style name="Material.App.Dialog.TimePicker" parent="Material.App.Dialog">
<item name="tp_backgroundColor">#28999999</item>
<item name="tp_selectionColor">?attr/colorPrimary</item>
<item name="tp_selectionRadius">16dp</item>
<item name="tp_tickSize">1dp</item>
<item name="tp_textSize">@dimen/abc_text_size_caption_material</item>
<item name="tp_textStyle">normal</item>
<item name="tp_textColor">@color/abc_primary_text_material_dark</item>
<item name="tp_textHighlightColor">#FFFFFFFF</item>
<item name="tp_animDuration">@android:integer/config_mediumAnimTime</item>
<item name="tp_inInterpolator">@android:anim/decelerate_interpolator</item>
<item name="tp_outInterpolator">@android:anim/decelerate_interpolator</item>
<item name="tp_mode">hour</item>
<item name="tp_headerHeight">120dp</item>
<item name="tp_textTimeSize">@dimen/abc_text_size_display_2_material</item>
<item name="tp_textTimeColor">#90FFFFFF</item>
<item name="tp_leadingZero">false</item>
</style>
<style name="Material.App.Dialog.TimePicker.Light" parent="Material.App.Dialog.Light">
<item name="tp_backgroundColor">#28999999</item>
<item name="tp_selectionColor">?attr/colorPrimary</item>
<item name="tp_selectionRadius">16dp</item>
<item name="tp_tickSize">1dp</item>
<item name="tp_textSize">@dimen/abc_text_size_caption_material</item>
<item name="tp_textStyle">normal</item>
<item name="tp_textColor">@color/abc_primary_text_material_light</item>
<item name="tp_textHighlightColor">#FFFFFFFF</item>
<item name="tp_animDuration">@android:integer/config_mediumAnimTime</item>
<item name="tp_inInterpolator">@android:anim/decelerate_interpolator</item>
<item name="tp_outInterpolator">@android:anim/decelerate_interpolator</item>
<item name="tp_mode">hour</item>
<item name="tp_headerHeight">120dp</item>
<item name="tp_textTimeSize">@dimen/abc_text_size_display_2_material</item>
<item name="tp_textTimeColor">#90FFFFFF</item>
<item name="tp_leadingZero">false</item>
</style>
<style name="Material.Widget.YearPicker">
<item name="dp_yearTextSize">@dimen/abc_text_size_title_material</item>
<item name="dp_yearItemHeight">48dp</item>
<item name="dp_textColor">@color/abc_primary_text_material_dark</item>
<item name="dp_textHighlightColor">#FFFFFFFF</item>
<item name="dp_selectionColor">?attr/colorPrimary</item>
<item name="dp_animDuration">@android:integer/config_mediumAnimTime</item>
<item name="dp_inInterpolator">@android:anim/decelerate_interpolator</item>
<item name="dp_outInterpolator">@android:anim/decelerate_interpolator</item>
<item name="dp_textStyle">normal</item>
</style>
<style name="Material.Widget.YearPicker.Light" parent="Material.Widget.TimePicker">
<item name="dp_textColor">@color/abc_primary_text_material_light</item>
</style>
<style name="Material.Widget.DatePicker">
<item name="dp_dayTextSize">@dimen/abc_text_size_caption_material</item>
<item name="dp_textLabelColor">@color/abc_secondary_text_material_dark</item>
<item name="dp_textDisableColor">@color/abc_secondary_text_material_dark</item>
<item name="dp_textHighlightColor">#FFFFFFFF</item>
<item name="dp_textColor">@color/abc_primary_text_material_dark</item>
<item name="dp_selectionColor">?attr/colorPrimary</item>
<item name="dp_animDuration">@android:integer/config_mediumAnimTime</item>
<item name="dp_inInterpolator">@android:anim/decelerate_interpolator</item>
<item name="dp_outInterpolator">@android:anim/decelerate_interpolator</item>
<item name="dp_textStyle">normal</item>
</style>
<style name="Material.Widget.DatePicker.Light" parent="Material.Widget.DatePicker">
<item name="dp_textLabelColor">@color/abc_secondary_text_material_light</item>
<item name="dp_textDisableColor">@color/abc_secondary_text_material_light</item>
<item name="dp_textColor">@color/abc_primary_text_material_light</item>
</style>
<style name="Material.App.Dialog.DatePicker" parent="Material.App.Dialog">
<item name="dp_yearTextSize">@dimen/abc_text_size_title_material</item>
<item name="dp_yearItemHeight">48dp</item>
<item name="dp_textColor">@color/abc_primary_text_material_dark</item>
<item name="dp_textHighlightColor">#FFFFFFFF</item>
<item name="dp_selectionColor">?attr/colorPrimary</item>
<item name="dp_animDuration">@android:integer/config_mediumAnimTime</item>
<item name="dp_inInterpolator">@android:anim/decelerate_interpolator</item>
<item name="dp_outInterpolator">@android:anim/decelerate_interpolator</item>
<item name="dp_textStyle">normal</item>
<item name="dp_dayTextSize">@dimen/abc_text_size_caption_material</item>
<item name="dp_textLabelColor">@color/abc_secondary_text_material_dark</item>
<item name="dp_textDisableColor">@color/abc_secondary_text_material_dark</item>
<item name="dp_headerPrimaryHeight">144dp</item>
<item name="dp_headerSecondaryHeight">32dp</item>
<item name="dp_headerPrimaryColor">?attr/colorPrimary</item>
<item name="dp_headerSecondaryColor">?attr/colorPrimaryDark</item>
<item name="dp_headerPrimaryTextSize">@dimen/abc_text_size_display_2_material</item>
<item name="dp_headerSecondaryTextSize">@dimen/abc_text_size_headline_material</item>
<item name="dp_textHeaderColor">#90FFFFFF</item>
</style>
<style name="Material.App.Dialog.DatePicker.Light" parent="Material.App.Dialog.Light">
<item name="dp_yearTextSize">@dimen/abc_text_size_title_material</item>
<item name="dp_yearItemHeight">48dp</item>
<item name="dp_textColor">@color/abc_primary_text_material_light</item>
<item name="dp_textHighlightColor">#FFFFFFFF</item>
<item name="dp_selectionColor">?attr/colorPrimary</item>
<item name="dp_animDuration">@android:integer/config_mediumAnimTime</item>
<item name="dp_inInterpolator">@android:anim/decelerate_interpolator</item>
<item name="dp_outInterpolator">@android:anim/decelerate_interpolator</item>
<item name="dp_textStyle">normal</item>
<item name="dp_dayTextSize">@dimen/abc_text_size_caption_material</item>
<item name="dp_textLabelColor">@color/abc_secondary_text_material_light</item>
<item name="dp_textDisableColor">@color/abc_secondary_text_material_light</item>
<item name="dp_headerPrimaryHeight">144dp</item>
<item name="dp_headerSecondaryHeight">32dp</item>
<item name="dp_headerPrimaryColor">?attr/colorPrimary</item>
<item name="dp_headerSecondaryColor">?attr/colorPrimaryDark</item>
<item name="dp_headerPrimaryTextSize">@dimen/abc_text_size_display_2_material</item>
<item name="dp_headerSecondaryTextSize">@dimen/abc_text_size_headline_material</item>
<item name="dp_textHeaderColor">#90FFFFFF</item>
</style>
<style name="Material.Widget.EditText">
<item name="et_labelEnable">true</item>
<item name="et_labelPadding">0dp</item>
<item name="et_labelTextAppearance">@style/TextAppearance.AppCompat.Caption</item>
<item name="et_labelTextColor">@color/abc_secondary_text_material_dark</item>
<item name="et_labelEllipsize">end</item>
<item name="et_labelInAnim">@anim/abc_fade_in</item>
<item name="et_labelOutAnim">@anim/abc_fade_out</item>
<item name="et_dividerErrorColor">?attr/colorAccent</item>
<item name="et_dividerAnimDuration">@android:integer/config_shortAnimTime</item>
<item name="et_dividerHeight">2dp</item>
<item name="et_dividerPadding">0dp</item>
<item name="et_dividerCompoundPadding">true</item>
<item name="et_supportTextAppearance">@style/TextAppearance.AppCompat.Caption</item>
<item name="et_supportTextColor">@color/abc_secondary_text_material_dark</item>
<item name="et_supportTextErrorColor">?attr/colorAccent</item>
<item name="et_supportEllipsize">end</item>
<item name="et_autoCompleteMode">none</item>
</style>
<style name="Material.Widget.EditText.Light" parent="Material.Widget.EditText">
<item name="et_labelTextColor">@color/abc_secondary_text_material_light</item>
<item name="et_supportTextColor">@color/abc_secondary_text_material_light</item>
</style>
<style name="Material.Widget.Spinner">
<item name="spn_labelEnable">false</item>
<item name="spn_labelPadding">0dp</item>
<item name="spn_labelTextAppearance">@style/TextAppearance.AppCompat.Caption</item>
<item name="spn_labelTextColor">@color/abc_secondary_text_material_dark</item>
<item name="spn_labelEllipsize">end</item>
<item name="spn_dividerHeight">2dp</item>
<item name="spn_dividerPadding">0dp</item>
<item name="spn_dividerAnimDuration">@android:integer/config_shortAnimTime</item>
<item name="spn_arrowColor">?attr/colorControlNormal</item>
<item name="spn_arrowSize">4dp</item>
<item name="spn_arrowPadding">8dp</item>
<item name="spn_popupItemAnimation">@anim/abc_slide_in_bottom</item>
<item name="spn_popupItemAnimOffset">120</item>
</style>
<style name="Material.Widget.Spinner.Light" parent="Material.Widget.Spinner">
<item name="spn_labelTextColor">@color/abc_secondary_text_material_light</item>
</style>
</resources>
| {'content_hash': 'a88b8c67d2cfb11b3df208c4ad91b3f5', 'timestamp': '', 'source': 'github', 'line_count': 564, 'max_line_length': 115, 'avg_line_length': 51.991134751773046, 'alnum_prop': 0.6774886607782287, 'repo_name': 'leerduo/material', 'id': '904faf49d72e72ae57c2b8afde82ecfc19125d16', 'size': '29323', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'lib/src/main/res/values/styles.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '964047'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.