language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def do(self, repetitions=1, locations=np.arange(-0.5, 0.6, 0.2), plot=True):
"""generates, plots and saves function values ``func(y)``,
where ``y`` is 'close' to `x` (see `__init__()`). The data are stored in
the ``res`` attribute and the class instance is saved in a file
with (the weired) name ``str(func)``.
Parameters
----------
`repetitions`
for each point, only for noisy functions is >1 useful. For
``repetitions==0`` only already generated data are plotted.
`locations`
coordinated wise deviations from the middle point given in `__init__`
"""
if not repetitions:
self.plot()
return
res = self.res
for i in xrange(len(self.basis)): # i-th coordinate
if i not in res:
res[i] = {}
# xx = np.array(self.x)
# TODO: store res[i]['dx'] = self.basis[i] here?
for dx in locations:
xx = self.x + dx * self.basis[i]
xkey = dx # xx[i] if (self.basis == np.eye(len(self.basis))).all() else dx
if xkey not in res[i]:
res[i][xkey] = []
n = repetitions
while n > 0:
n -= 1
res[i][xkey].append(self.func(xx, *self.args))
if plot:
self.plot()
self.save()
return self |
java | public static void addDynamicProperties(
CmsObject cms,
CmsCmisTypeManager typeManager,
PropertiesImpl props,
String typeId,
CmsResource resource,
Set<String> filter) {
List<I_CmsPropertyProvider> providers = typeManager.getPropertyProviders();
for (I_CmsPropertyProvider provider : providers) {
String propertyName = CmsCmisTypeManager.PROPERTY_PREFIX_DYNAMIC + provider.getName();
if (!checkAddProperty(typeManager, props, typeId, filter, propertyName)) {
continue;
}
try {
String value = provider.getPropertyValue(cms, resource);
addPropertyString(typeManager, props, typeId, filter, propertyName, value);
} catch (Throwable t) {
addPropertyString(typeManager, props, typeId, filter, propertyName, null);
}
}
} |
python | def create_tags_from_dict(cls, tag_dict):
"""
Build a tuple of list of Tag objects based on the tag_dict.
The tuple contains 3 lists.
- The first list contains skill tags
- The second list contains misconception tags
- The third list contains category tags
"""
tag_list_common = []
tag_list_misconception = []
tag_list_organisational = []
for tag in tag_dict:
try:
id = tag_dict[tag]["id"]
name = tag_dict[tag]["name"]
visible = tag_dict[tag]["visible"]
description = tag_dict[tag]["description"]
type = tag_dict[tag]["type"]
if type == 2:
tag_list_organisational.insert(int(tag), Tag(id, name, description, visible, type))
elif type == 1:
tag_list_misconception.insert(int(tag), Tag(id, name, description, visible, type))
else:
tag_list_common.insert(int(tag), Tag(id, name, description, visible, type))
except KeyError:
pass
return tag_list_common, tag_list_misconception, tag_list_organisational |
java | @Override
protected ClassEntry getClassEntry(String name, String pathName)
throws ClassNotFoundException
{
if (_pathMap != null) {
JarMap.JarList jarEntryList = _pathMap.get(pathName);
if (jarEntryList != null) {
JarEntry jarEntry = jarEntryList.getEntry();
PathImpl path = jarEntry.getJarPath();
PathImpl filePath = path.lookup(pathName);
return createEntry(name, pathName, jarEntry, filePath);
}
}
else {
// Find the path corresponding to the class
for (int i = 0; i < _jarList.size(); i++) {
JarEntry jarEntry = _jarList.get(i);
JarPath path = jarEntry.getJarPath();
Jar jar = path.getJar();
try {
ZipEntry zipEntry = jar.getZipEntry(pathName);
// if (filePath.canRead() && filePath.getLength() > 0) {
if (zipEntry != null && zipEntry.getSize() > 0) {
PathImpl filePath = path.lookup(pathName);
return createEntry(name, pathName, jarEntry, filePath);
}
} catch (IOException e) {
log.log(Level.FINER, e.toString(), e);
}
}
}
return null;
} |
java | protected void write(JsonWriter out, T value, TypeAdapter<JsonElement> elementAdapter, TypeAdapter<T> delegate) throws IOException {
JsonElement tree = delegate.toJsonTree(value);
beforeWrite(value, tree);
elementAdapter.write(out, tree);
} |
python | def _read_managed_gavs(artifact, repo_url=None, mgmt_type=MGMT_TYPE.DEPENDENCIES, mvn_repo_local=None):
"""
Reads all artifacts managed in dependencyManagement section of effective pom of the given artifact. It places the
repo_url in settings.xml and then runs help:effective-pom with these settings. There should be the POM with its
parent and dependencies available in the repository and there should also be all plugins available needed to execute
help:effective-pom goal.
:param artifact: MavenArtifact instance representing the POM
:param repo_url: repository URL to use
:param mgmt_type: type of management to read, values available are defined in MGMT_TYPE class
:param mvn_repo_local: path to local Maven repository to be used when getting effective POM
:returns: dictionary, where key is the management type and value is the list of artifacts managed by
dependencyManagement/pluginManagement or None, if a problem occurs
"""
# download the pom
pom_path = download_pom(repo_url, artifact)
if pom_path:
pom_dir = os.path.split(pom_path)[0]
# get effective pom
eff_pom = get_effective_pom(pom_dir, repo_url, mvn_repo_local)
shutil.rmtree(pom_dir, True)
if not eff_pom:
return None
# read dependencyManagement/pluginManagement section
managed_arts = read_management(eff_pom, mgmt_type)
else:
managed_arts = None
return managed_arts |
python | def bundle_javascript(context: Context):
"""
Compiles javascript
"""
args = ['--bail']
if context.verbosity > 0:
args.append('--verbose')
if not context.use_colour:
args.append('--no-colors')
return context.node_tool('webpack', *args) |
java | @Override
public void process(List<EllipseRotated_F64> ellipses , List<List<EllipsesIntoClusters.Node>> clusters ) {
foundGrids.reset();
for (int i = 0; i < clusters.size(); i++) {
List<EllipsesIntoClusters.Node> cluster = clusters.get(i);
int clusterSize = cluster.size();
if( clusterSize < 2 )
continue;
computeNodeInfo(ellipses, cluster);
// finds all the nodes in the outside of the cluster
if( !findContour(false) ) {
if( verbose ) System.out.println("Contour find failed");
continue;
}
// Find corner to start alignment
NodeInfo corner = selectSeedCorner();
corner.marked = true;
boolean ccw = UtilAngle.distanceCCW(direction(corner,corner.right),direction(corner,corner.left)) > Math.PI;
// find the row and column which the corner is a member of
List<NodeInfo> cornerRow = findLine(corner,corner.left,clusterSize, null,ccw);
List<NodeInfo> cornerColumn = findLine(corner,corner.right,clusterSize, null,!ccw);
if( cornerRow == null || cornerColumn == null ) {
if( verbose )System.out.println("Corner row/column line find failed");
continue;
}
// Go down the columns and find each of the rows
List<List<NodeInfo>> gridByRows = new ArrayList<>();
gridByRows.add( cornerRow );
boolean failed = false;
for (int j = 1; j < cornerColumn.size(); j++) {
List<NodeInfo> prev = gridByRows.get( j - 1);
NodeInfo seed = cornerColumn.get(j);
NodeInfo next = selectSeedNext(prev.get(0),prev.get(1), seed,ccw);
if( next == null ) {
if( verbose )
System.out.println("Outer column with a row that has only one element");
failed = true;
break;
}
List<NodeInfo> row = findLine( seed , next, clusterSize, null,ccw);
gridByRows.add( row );
}
if( failed )
continue;
// perform sanity checks
if( !checkGridSize(gridByRows, cluster.size()) ) {
if( verbose ) {
System.out.println("grid size check failed");
for (int j = 0; j < gridByRows.size(); j++) {
System.out.println(" row "+gridByRows.get(j).size());
}
}
continue;
}
if( checkDuplicates(gridByRows) ) {
if( verbose ) System.out.println("contains duplicates");
continue;
}
createRegularGrid(gridByRows,foundGrids.grow());
}
} |
java | public boolean setValue(int ch, int value)
{
// valid, uncompacted trie and valid c?
if (m_isCompacted_ || ch > UCharacter.MAX_VALUE || ch < 0) {
return false;
}
int block = getDataBlock(ch);
if (block < 0) {
return false;
}
m_data_[block + (ch & MASK_)] = value;
return true;
} |
java | public Head getHead() {
if (EntityMention_Type.featOkTst && ((EntityMention_Type)jcasType).casFeat_head == null)
jcasType.jcas.throwFeatMissing("head", "de.julielab.jules.types.ace.EntityMention");
return (Head)(jcasType.ll_cas.ll_getFSForRef(jcasType.ll_cas.ll_getRefValue(addr, ((EntityMention_Type)jcasType).casFeatCode_head)));} |
java | public Object getProperty(Class aClass, Object object, String property, boolean b, boolean b1) {
if (null == interceptor) {
return super.getProperty(aClass, object, property, b, b1);
}
if (interceptor instanceof PropertyAccessInterceptor) {
PropertyAccessInterceptor pae = (PropertyAccessInterceptor) interceptor;
Object result = pae.beforeGet(object, property);
if (interceptor.doInvoke()) {
result = super.getProperty(aClass, object, property, b, b1);
}
return result;
}
return super.getProperty(aClass, object, property, b, b1);
} |
java | @Override
public void initialize(Integer pollingPeriodMs) {
if (timer == null) {
timer = new Timer();
TimerTask task = new TimerTask() {
/* (non-Javadoc)
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
try {
log.info("Launching periodic finalization...");
snapshotManager.finalizeSnapshots();
restoreManager.finalizeRestores();
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
if (pollingPeriodMs == null || pollingPeriodMs < 1) {
pollingPeriodMs = DEFAULT_POLLING_PERIOD_MS;
}
timer.schedule(task, new Date(), pollingPeriodMs);
log.info("Finalization scheduled to run every "
+ pollingPeriodMs + " milliseconds.");
}
} |
python | def _java_is_subclass(cls, obj, class_name):
"""Given a deserialized JavaObject as returned by the javaobj library,
determine whether it's a subclass of the given class name.
"""
clazz = obj.get_class()
while clazz:
if clazz.name == class_name:
return True
clazz = clazz.superclass
return False |
java | static String getPipeName(final String fieldName, final Pipe annot) {
String attributeName = null;
if (annot.name().equals("")) {
attributeName = fieldName;
} else {
attributeName = annot.name();
}
return attributeName;
} |
java | public void setupEnvironment(Hashtable<String, Object> env, String userDn, String password) {
env.put(Context.SECURITY_AUTHENTICATION, SIMPLE_AUTHENTICATION);
env.put(Context.SECURITY_PRINCIPAL, userDn);
env.put(Context.SECURITY_CREDENTIALS, password);
} |
java | public <T1> Mutable<T1> mapInputToObj(final Function<T1, Integer> fn) {
final MutableInt host = this;
return new Mutable<T1>() {
@Override
public Mutable<T1> set(final T1 value) {
host.set(fn.apply(value));
return this;
}
};
} |
python | def get_ascii(self, show_internal=True, compact=False, attributes=None):
"""
Returns a string containing an ascii drawing of the tree.
Parameters:
-----------
show_internal:
include internal edge names.
compact:
use exactly one line per tip.
attributes:
A list of node attributes to shown in the ASCII representation.
"""
(lines, mid) = self._asciiArt(show_internal=show_internal,
compact=compact,
attributes=attributes)
return '\n'+'\n'.join(lines) |
java | public synchronized int addElement(E theElement) {
if (theElement == null) {
return -1;
}
if (elementCount == currentCapacity) {
// try to expand the table to handle the new value, if that fails
// then it will throw an illegalstate exception
expandTable();
}
int theIndex = occupiedSlots.nextClearBit(0);
if (theIndex < 0 || theIndex > currentCapacity - 1) {
throw new IllegalStateException("No space available for element");
}
theElementArray[theIndex] = theElement;
elementCount++;
occupiedSlots.set(theIndex);
return theIndex;
} |
java | @Pure
public BusItineraryHalt[] toValidBusHaltArray() {
final BusItineraryHalt[] tab = new BusItineraryHalt[this.validHalts.size()];
return this.validHalts.toArray(tab);
} |
python | def fetch(self, kernel_version, manifest_type):
"""
Search repository for kernel module matching kernel_version
:type kernel_version: str
:param kernel_version: kernel version to search repository on
:type manifest_type: str
:param manifest_type: kernel module manifest to search on
"""
metadata = self.get_metadata()
logger.debug("parsed metadata: {0}".format(metadata))
manifest = self.get_manifest(metadata['manifests'][manifest_type])
try:
module = manifest[kernel_version]
logger.debug("found module {0}".format(module))
except KeyError:
raise KernelModuleNotFoundError(kernel_version, self.url)
path = self.fetch_module(module)
return path |
python | def get_subdirs(directory):
"""
Returns: a list of subdirectories of the given directory
"""
return [os.path.join(directory, name)
for name in os.listdir(directory)
if os.path.isdir(os.path.join(directory, name))] |
java | public Observable<SourceUploadDefinitionInner> getBuildSourceUploadUrlAsync(String resourceGroupName, String registryName) {
return getBuildSourceUploadUrlWithServiceResponseAsync(resourceGroupName, registryName).map(new Func1<ServiceResponse<SourceUploadDefinitionInner>, SourceUploadDefinitionInner>() {
@Override
public SourceUploadDefinitionInner call(ServiceResponse<SourceUploadDefinitionInner> response) {
return response.body();
}
});
} |
python | def node(self, source, args=(), env={}):
"""
Calls node with an inline source.
Returns decoded output of stdout and stderr; decoding determine
by locale.
"""
return self._exec(self.node_bin, source, args=args, env=env) |
java | @Override
public boolean isReadOnly(ELContext context)
throws PropertyNotFoundException, ELException {
EvaluationContext ctx = new EvaluationContext(context, this.fnMapper,
this.varMapper);
context.notifyBeforeEvaluation(getExpressionString());
boolean result = this.getNode().isReadOnly(ctx);
context.notifyAfterEvaluation(getExpressionString());
return result;
} |
java | public JBBPTextWriter Byte(final byte[] array, int off, int len) throws IOException {
ensureValueMode();
while (len-- > 0) {
Byte(array[off++]);
}
return this;
} |
java | public static List<Annotation> selectCovered(CAS cas,
AnnotationFS coveringAnnotation) {
final int begin = coveringAnnotation.getBegin();
final int end = coveringAnnotation.getEnd();
final List<Annotation> list = new ArrayList<Annotation>();
final FSIterator<AnnotationFS> it = cas.getAnnotationIndex().iterator();
// Try to seek the insertion point.
it.moveTo(coveringAnnotation);
// If the insertion point is beyond the index, move back to the last.
if (!it.isValid()) {
it.moveToLast();
if (!it.isValid()) {
return list;
}
}
// Ignore type priorities by seeking to the first that has the same
// begin
boolean moved = false;
while (it.isValid() && (it.get()).getBegin() >= begin) {
it.moveToPrevious();
moved = true;
}
// If we moved, then we are now on one starting before the requested
// begin, so we have to
// move one ahead.
if (moved) {
it.moveToNext();
}
// If we managed to move outside the index, start at first.
if (!it.isValid()) {
it.moveToFirst();
}
// Skip annotations whose start is before the start parameter.
while (it.isValid() && (it.get()).getBegin() < begin) {
it.moveToNext();
}
boolean strict = true;
while (it.isValid()) {
AnnotationFS a = it.get();
if (!(a instanceof Annotation))
continue;
// If the start of the current annotation is past the end parameter,
// we're done.
if (a.getBegin() > end) {
break;
}
it.moveToNext();
if (strict && a.getEnd() > end) {
continue;
}
checkArgument(a.getBegin() >= coveringAnnotation.getBegin(),
"Illegal begin " + a.getBegin() + " in ["
+ coveringAnnotation.getBegin() + ".."
+ coveringAnnotation.getEnd() + "]");
checkArgument(
a.getEnd() <= coveringAnnotation.getEnd(),
"Illegal end " + a.getEnd() + " in ["
+ coveringAnnotation.getBegin() + ".."
+ coveringAnnotation.getEnd() + "]");
if (!a.equals(coveringAnnotation) && !BlueCasUtil.isDocAnnot(a)) {
list.add((Annotation) a);
}
}
return unmodifiableList(list);
} |
python | def make_table(self):
"""Make numpy array from timeseries data."""
num_records = int(np.sum([1 for frame in self.timeseries]))
dtype = [
("frame",float),("time",float),("proteinring",list),
("ligand_ring_ids",list),("distance",float),("angle",float),
("offset",float),("type","|U4"),("resid",int),("resname","|U4"),("segid","|U8") ]
out = np.empty((num_records,),dtype=dtype)
cursor=0
for contact in self.timeseries:
out[cursor] = (contact.frame, contact.time,contact.proteinring,contact.ligandring,contact.distance,contact.angle,contact.offset,contact.type,contact.resid,contact.resname,contact.segid)
cursor+=1
return out.view(np.recarray) |
java | public boolean exists(String nodeDN)
throws NamingException
{
try
{
ctx.search(nodeDN, "(objectclass=*)", existanceConstraints);
return true;
}
catch (NameNotFoundException e)
{
return false;
}
catch (NullPointerException e)
{
if (ctx != null
&& ctx.getEnvironment().get("java.naming.factory.initial").toString()
.indexOf("dsml") > 0)
return false;
else
throw e;
}
} |
python | def factoring_qaoa(n_step, num, minimizer=None, sampler=None, verbose=True):
"""Do the Number partition QAOA.
:param num: The number to be factoring.
:param n_step: The number of step of QAOA
:param edges: The edges list of the graph.
:returns result of QAOA
"""
def get_nbit(n):
m = 1
while 2**m < n:
m += 1
return m
n1_bits = get_nbit(int(num**0.5)) - 1
n2_bits = get_nbit(int(num**0.5))
def mk_expr(offset, n):
expr = pauli.Expr.from_number(1)
for i in range(n):
expr = expr + 2**(i + 1) * q(i + offset)
return expr
def bitseparator(bits):
assert len(bits) == n1_bits + n2_bits
p = 1
m = 1
for b in bits[:n1_bits]:
if b:
p += 2**m
m += 1
q = 1
m = 1
for b in bits[n1_bits:]:
if b:
q += 2**m
m += 1
return p, q
hamiltonian = (num - mk_expr(0, n1_bits) * mk_expr(n1_bits, n2_bits))**2
return vqe.Vqe(vqe.QaoaAnsatz(hamiltonian, n_step), minimizer, sampler), bitseparator |
java | public static Boolean getYesNoAttrVal(final NamedNodeMap nnm, final String name)
throws SAXException {
String val = getAttrVal(nnm, name);
if (val == null) {
return null;
}
if ((!"yes".equals(val)) && (!"no".equals(val))) {
throw new SAXException("Invalid attribute value: " + val);
}
return new Boolean("yes".equals(val));
} |
python | def clean_previous_run(self):
"""Clean variables from previous configuration,
such as schedulers, broks and external commands
:return: None
"""
# Execute the base class treatment...
super(Satellite, self).clean_previous_run()
# Clean my lists
del self.broks[:]
del self.events[:] |
java | protected void doLoginByGivenEntity(USER_ENTITY givenEntity, LoginSpecifiedOption option) {
assertGivenEntityRequired(givenEntity);
handleLoginSuccess(givenEntity, option);
} |
python | def parse_rich_header(self):
"""Parses the rich header
see http://www.ntcore.com/files/richsign.htm for more information
Structure:
00 DanS ^ checksum, checksum, checksum, checksum
10 Symbol RVA ^ checksum, Symbol size ^ checksum...
...
XX Rich, checksum, 0, 0,...
"""
# Rich Header constants
#
DANS = 0x536E6144 # 'DanS' as dword
RICH = 0x68636952 # 'Rich' as dword
# Read a block of data
#
try:
data = list(struct.unpack("<32I", self.get_data(0x80, 0x80)))
except:
# In the cases where there's not enough data to contain the Rich header
# we abort its parsing
return None
# the checksum should be present 3 times after the DanS signature
#
checksum = data[1]
if (data[0] ^ checksum != DANS
or data[2] != checksum
or data[3] != checksum):
return None
result = {"checksum": checksum}
headervalues = []
result ["values"] = headervalues
data = data[4:]
for i in xrange(len(data) / 2):
# Stop until the Rich footer signature is found
#
if data[2 * i] == RICH:
# it should be followed by the checksum
#
if data[2 * i + 1] != checksum:
self.__warnings.append('Rich Header corrupted')
break
# header values come by pairs
#
headervalues += [data[2 * i] ^ checksum, data[2 * i + 1] ^ checksum]
return result |
java | protected void indexNode(int expandedTypeID, int identity)
{
ExpandedNameTable ent = m_expandedNameTable;
short type = ent.getType(expandedTypeID);
if (DTM.ELEMENT_NODE == type)
{
int namespaceID = ent.getNamespaceID(expandedTypeID);
int localNameID = ent.getLocalNameID(expandedTypeID);
ensureSizeOfIndex(namespaceID, localNameID);
int[] index = m_elemIndexes[namespaceID][localNameID];
index[index[0]] = identity;
index[0]++;
}
} |
java | @Override
public void writeTo(final Viewable viewable,
final Class<?> type,
final Type genericType,
final Annotation[] annotations,
final MediaType mediaType,
final MultivaluedMap<String, Object> httpHeaders,
final OutputStream entityStream) throws IOException, WebApplicationException {
try {
final ResolvedViewable resolvedViewable = resolve(viewable);
if (resolvedViewable == null) {
final String message = LocalizationMessages
.TEMPLATE_NAME_COULD_NOT_BE_RESOLVED(viewable.getTemplateName());
throw new WebApplicationException(new ProcessingException(message), Response.Status.NOT_FOUND);
}
MediaType mType = resolvedViewable.getMediaType();
if (mType == null || mType.isWildcardType()) {
mType = mediaType;
}
httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, mType);
resolvedViewable.writeTo(entityStream, httpHeaders);
} catch (ViewableContextException vce) {
throw new NotFoundException(vce);
}
} |
python | def convert_idx_to_name(self, y, lens):
"""Convert label index to name.
Args:
y (list): label index list.
lens (list): true length of y.
Returns:
y: label name list.
Examples:
>>> # assumes that id2label = {1: 'B-LOC', 2: 'I-LOC'}
>>> y = [[1, 0, 0], [1, 2, 0], [1, 1, 1]]
>>> lens = [1, 2, 3]
>>> self.convert_idx_to_name(y, lens)
[['B-LOC'], ['B-LOC', 'I-LOC'], ['B-LOC', 'B-LOC', 'B-LOC']]
"""
y = [[self.id2label[idx] for idx in row[:l]]
for row, l in zip(y, lens)]
return y |
java | public static Annotation getAnnotatedChunk(List<CoreLabel> tokens, int tokenStartIndex, int tokenEndIndex, int totalTokenOffset,
Class tokenChunkKey, Class tokenTextKey, Class tokenLabelKey)
{
Annotation chunk = getAnnotatedChunk(tokens, tokenStartIndex, tokenEndIndex, totalTokenOffset);
annotateChunkText(chunk, tokenTextKey);
annotateChunkTokens(chunk, tokenChunkKey, tokenLabelKey);
return chunk;
} |
python | def python_lib_rpm_dirs(self):
"""Both arch and non-arch site-packages directories."""
libs = [self.python_lib_arch_dir, self.python_lib_non_arch_dir]
def append_rpm(path):
return os.path.join(path, 'rpm')
return map(append_rpm, libs) |
java | public static boolean containsAny(Collection source, Collection candidates) {
if (isEmpty(source) || isEmpty(candidates)) {
return false;
}
for (Object candidate : candidates) {
if (source.contains(candidate)) {
return true;
}
}
return false;
} |
java | private File extractThriftFile(String artifactId, String fileName, Set<File> thriftFiles) {
for (File thriftFile : thriftFiles) {
boolean fileFound = false;
if (fileName.equals(thriftFile.getName())) {
for (String pathComponent : thriftFile.getPath().split(File.separator)) {
if (pathComponent.equals(artifactId)) {
fileFound = true;
}
}
}
if (fileFound) {
return thriftFile;
}
}
return null;
} |
java | @Override
public void deleteSnapshots(Pattern pattern) throws IOException {
for (SnapshotDescription snapshotDescription : listSnapshots(pattern)) {
deleteSnapshot(snapshotDescription.getName());
}
} |
java | public static final void setWriter(String format, TreeWriter writer) {
String key = format.toLowerCase();
writers.put(key, writer);
if (JSON.equals(key)) {
cachedJsonWriter = writer;
}
} |
java | protected <V extends ATSecDBValidator> Set<ATError> createError(V validator, String key, String suffix, String defaultMessagePrefix, Object... arguments ) {
Set<ATError> errors = new HashSet<>(1);
if (null != validator) {
errors.add(new ATError(key,
validator.getMessageWithSuffix(suffix, arguments, defaultMessagePrefix + StringUtils.join(arguments, ','))));
} else if (null != messageSource) {
errors.add(new ATError(key,
messageSource.getMessage(key, null, defaultMessagePrefix, LocaleContextHolder.getLocale())));
} else {
errors.add(new ATError(key, defaultMessagePrefix));
}
return errors;
} |
python | def train(self, training_set, iterations=500):
"""Trains itself using the sequence data."""
if len(training_set) > 2:
self.__X = np.matrix([example[0] for example in training_set])
if self.__num_labels == 1:
self.__y = np.matrix([example[1] for example in training_set]).reshape((-1, 1))
else:
eye = np.eye(self.__num_labels)
self.__y = np.matrix([eye[example[1]] for example in training_set])
else:
self.__X = np.matrix(training_set[0])
if self.__num_labels == 1:
self.__y = np.matrix(training_set[1]).reshape((-1, 1))
else:
eye = np.eye(self.__num_labels)
self.__y = np.matrix([eye[index] for sublist in training_set[1] for index in sublist])
self.__m = self.__X.shape[0]
self.__input_layer_size = self.__X.shape[1]
self.__sizes = [self.__input_layer_size]
self.__sizes.extend(self.__hidden_layers)
self.__sizes.append(self.__num_labels)
initial_theta = []
for count in range(len(self.__sizes) - 1):
epsilon = np.sqrt(6) / np.sqrt(self.__sizes[count]+self.__sizes[count+1])
initial_theta.append(np.random.rand(self.__sizes[count+1],self.__sizes[count]+1)*2*epsilon-epsilon)
initial_theta = self.__unroll(initial_theta)
self.__thetas = self.__roll(fmin_bfgs(self.__cost_function, initial_theta, fprime=self.__cost_grad_function, maxiter=iterations)) |
python | def get_domain_and_name(self, domain_or_name):
"""
Given a ``str`` or :class:`boto.sdb.domain.Domain`, return a
``tuple`` with the following members (in order):
* In instance of :class:`boto.sdb.domain.Domain` for the requested
domain
* The domain's name as a ``str``
:type domain_or_name: ``str`` or :class:`boto.sdb.domain.Domain`
:param domain_or_name: The domain or domain name to get the domain
and name for.
:raises: :class:`boto.exception.SDBResponseError` when an invalid
domain name is specified.
:rtype: tuple
:return: A ``tuple`` with contents outlined as per above.
"""
if (isinstance(domain_or_name, Domain)):
return (domain_or_name, domain_or_name.name)
else:
return (self.get_domain(domain_or_name), domain_or_name) |
python | def reset(self):
"Close the current failed connection and prepare for a new one"
log.info("resetting client")
rpc_client = self._rpc_client
self._addrs.append(self._peer.addr)
self.__init__(self._addrs)
self._rpc_client = rpc_client
self._dispatcher.rpc_client = rpc_client
rpc_client._client = weakref.ref(self) |
java | @Override
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
char[] buf = this.buf;
int sz = buf.length;
if (endIndex > sz) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == sz)) ? toString()
: new String(buf, toInternalId(beginIndex), subLen);
} |
python | def _post_processing(kwargs, skip_translate, invalid):
'''
Additional container-specific post-translation processing
'''
# Don't allow conflicting options to be set
if kwargs.get('port_bindings') is not None \
and kwargs.get('publish_all_ports'):
kwargs.pop('port_bindings')
invalid['port_bindings'] = 'Cannot be used when publish_all_ports=True'
if kwargs.get('hostname') is not None \
and kwargs.get('network_mode') == 'host':
kwargs.pop('hostname')
invalid['hostname'] = 'Cannot be used when network_mode=True'
# Make sure volumes and ports are defined to match the binds and port_bindings
if kwargs.get('binds') is not None \
and (skip_translate is True or
all(x not in skip_translate
for x in ('binds', 'volume', 'volumes'))):
# Make sure that all volumes defined in "binds" are included in the
# "volumes" param.
auto_volumes = []
if isinstance(kwargs['binds'], dict):
for val in six.itervalues(kwargs['binds']):
try:
if 'bind' in val:
auto_volumes.append(val['bind'])
except TypeError:
continue
else:
if isinstance(kwargs['binds'], list):
auto_volume_defs = kwargs['binds']
else:
try:
auto_volume_defs = helpers.split(kwargs['binds'])
except AttributeError:
auto_volume_defs = []
for val in auto_volume_defs:
try:
auto_volumes.append(helpers.split(val, ':')[1])
except IndexError:
continue
if auto_volumes:
actual_volumes = kwargs.setdefault('volumes', [])
actual_volumes.extend([x for x in auto_volumes
if x not in actual_volumes])
# Sort list to make unit tests more reliable
actual_volumes.sort()
if kwargs.get('port_bindings') is not None \
and all(x not in skip_translate
for x in ('port_bindings', 'expose', 'ports')):
# Make sure that all ports defined in "port_bindings" are included in
# the "ports" param.
ports_to_bind = list(kwargs['port_bindings'])
if ports_to_bind:
ports_to_open = set(kwargs.get('ports', []))
ports_to_open.update([helpers.get_port_def(x) for x in ports_to_bind])
kwargs['ports'] = list(ports_to_open)
if 'ports' in kwargs \
and all(x not in skip_translate for x in ('expose', 'ports')):
# TCP ports should only be passed as the port number. Normalize the
# input so a port definition of 80/tcp becomes just 80 instead of
# (80, 'tcp').
for index, _ in enumerate(kwargs['ports']):
try:
if kwargs['ports'][index][1] == 'tcp':
kwargs['ports'][index] = ports_to_open[index][0]
except TypeError:
continue |
java | @CanIgnoreReturnValue // some processors won't return a useful result
public static <T> T readLines(File file, Charset charset, LineProcessor<T> callback)
throws IOException {
return asCharSource(file, charset).readLines(callback);
} |
java | public synchronized NetworkServiceDescriptorAgent getNetworkServiceDescriptorAgent() {
if (this.networkServiceDescriptorAgent == null) {
if (isService) {
this.networkServiceDescriptorAgent =
new NetworkServiceDescriptorAgent(
this.serviceName,
this.projectId,
this.sslEnabled,
this.nfvoIp,
this.nfvoPort,
this.version,
this.serviceKey);
} else {
this.networkServiceDescriptorAgent =
new NetworkServiceDescriptorAgent(
this.username,
this.password,
this.projectId,
this.sslEnabled,
this.nfvoIp,
this.nfvoPort,
this.version);
}
}
return this.networkServiceDescriptorAgent;
} |
python | def set_role(self, name, value=None, default=False, disable=False):
"""Configures the user role vale in EOS
Args:
name (str): The name of the user to create
value (str): The value to configure for the user role
default (bool): Configure the user role using the EOS CLI
default command
disable (bool): Negate the user role using the EOS CLI no command
Returns:
True if the operation was successful otherwise False
"""
cmd = self.command_builder('username %s role' % name, value=value,
default=default, disable=disable)
return self.configure(cmd) |
python | def attribute_md5(self):
"""
The MD5 of all attributes is calculated by first generating a
utf-8 string from each attribute and MD5-ing the concatenation
of them all. Each attribute is encoded with some bytes that
describe the length of each part and the type of attribute.
Not yet implemented:
List types (https://github.com/aws/aws-sdk-java/blob/7844c64cf248aed889811bf2e871ad6b276a89ca/aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/MessageMD5ChecksumHandler.java#L58k)
"""
def utf8(str):
if isinstance(str, six.string_types):
return str.encode('utf-8')
return str
md5 = hashlib.md5()
struct_format = "!I".encode('ascii') # ensure it's a bytestring
for name in sorted(self.message_attributes.keys()):
attr = self.message_attributes[name]
data_type = attr['data_type']
encoded = utf8('')
# Each part of each attribute is encoded right after it's
# own length is packed into a 4-byte integer
# 'timestamp' -> b'\x00\x00\x00\t'
encoded += struct.pack(struct_format, len(utf8(name))) + utf8(name)
# The datatype is additionally given a final byte
# representing which type it is
encoded += struct.pack(struct_format, len(data_type)) + utf8(data_type)
encoded += TRANSPORT_TYPE_ENCODINGS[data_type]
if data_type == 'String' or data_type == 'Number':
value = attr['string_value']
elif data_type == 'Binary':
print(data_type, attr['binary_value'], type(attr['binary_value']))
value = base64.b64decode(attr['binary_value'])
else:
print("Moto hasn't implemented MD5 hashing for {} attributes".format(data_type))
# The following should be enough of a clue to users that
# they are not, in fact, looking at a correct MD5 while
# also following the character and length constraints of
# MD5 so as not to break client softwre
return('deadbeefdeadbeefdeadbeefdeadbeef')
encoded += struct.pack(struct_format, len(utf8(value))) + utf8(value)
md5.update(encoded)
return md5.hexdigest() |
java | public final int getInt16(final int pos) {
final int position = origin + pos;
if (pos + 1 >= limit || pos < 0) throw new IllegalArgumentException("limit excceed: "
+ (pos < 0 ? pos : (pos + 1)));
byte[] buf = buffer;
return (0xff & buf[position]) | ((buf[position + 1]) << 8);
} |
python | def get_param(self, name):
"""
Get a WinDivert parameter. See pydivert.Param for the list of parameters.
The remapped function is WinDivertGetParam::
BOOL WinDivertGetParam(
__in HANDLE handle,
__in WINDIVERT_PARAM param,
__out UINT64 *pValue
);
For more info on the C call visit: http://reqrypt.org/windivert-doc.html#divert_get_param
:return: The parameter value.
"""
value = c_uint64(0)
windivert_dll.WinDivertGetParam(self._handle, name, byref(value))
return value.value |
python | def json_request(endpoint, verb='GET', session_options=None, **options):
"""Like :func:`molotov.request` but extracts json from the response.
"""
req = functools.partial(_request, endpoint, verb, session_options,
json=True, **options)
return _run_in_fresh_loop(req) |
python | def translate_to_arpabet(self):
'''
转换成arpabet
:return:
'''
translations = []
for phoneme in self._phoneme_list:
if phoneme.is_vowel:
translations.append(phoneme.arpabet + self.stress.mark_arpabet())
else:
translations.append(phoneme.arpabet)
return " ".join(translations) |
python | def kill(self):
"""Kill instantiated process
:raises: `AttributeError` if instantiated process doesn't seem to satisfy `constraints <relshell.daemon_shelloperator.DaemonShellOperator>`_
"""
BaseShellOperator._close_process_input_stdin(self._batcmd.batch_to_file_s)
BaseShellOperator._wait_process(self._process, self._batcmd.sh_cmd, self._success_exitcodes)
BaseShellOperator._rm_process_input_tmpfiles(self._batcmd.batch_to_file_s)
self._process = None |
python | def indexByComponent(self, component):
"""Returns a location for the given component, or None if
it is not in the model
:param component: Component to get index for
:type component: :class:`AbstractStimulusComponent<sparkle.stim.abstract_component.AbstractStimulusComponent>`
:returns: (int, int) -- (row, column) of component
"""
for row, rowcontents in enumerate(self._segments):
if component in rowcontents:
column = rowcontents.index(component)
return (row, column) |
python | def gen_signature(priv, pub, signature_path, auto_create=False, keysize=None):
'''
Generate master public-key-signature
'''
skey = get_key(__opts__)
return skey.gen_keys_signature(priv, pub, signature_path, auto_create, keysize) |
java | protected void logEntityModification(EntityIdValue entityId,
String numberLabel, ArrayList<String> languages) {
modifiedEntities++;
System.out.println(entityId.getId() + ": adding label " + numberLabel
+ " for languages " + languages.toString() + " ("
+ modifiedEntities + " entities modified so far)");
this.logfile.println(entityId.getId() + "," + numberLabel + ",\""
+ languages.toString() + "\"");
if (modifiedEntities % 10 == 0) {
this.logfile.flush();
}
} |
python | def rerun(version="3.7.0"):
"""
Rerun last example code block with specified version of python.
"""
from commandlib import Command
Command(DIR.gen.joinpath("py{0}".format(version), "bin", "python"))(
DIR.gen.joinpath("state", "examplepythoncode.py")
).in_dir(DIR.gen.joinpath("state")).run() |
java | public <T, S> CallResults call(InputHandler<T> inputHandler, OutputHandler<S> outputHandler, String catalog, String schema, boolean useCache) throws SQLException {
AssertUtils.assertNotNull(inputHandler, nullException());
AssertUtils.assertNotNull(outputHandler, nullException());
QueryParameters params = null;
String procedureName = CallableUtils.getStoredProcedureShortNameFromSql(inputHandler.getQueryString());
boolean isFunction = CallableUtils.isFunctionCall(inputHandler.getQueryString());
T input = null;
S output = null;
boolean closeStatement = true;
CallResults<T, S> results = new CallResults(procedureName, isFunction);
if (inputHandler instanceof AbstractQueryInputHandler) {
params = callInner((AbstractQueryInputHandler) inputHandler, outputHandler);
} else if (inputHandler instanceof AbstractNamedInputHandler) {
QueryInputHandler queryInput = convertToQueryInputHandler((AbstractNamedInputHandler) inputHandler, catalog, schema, useCache);
params = callInner(queryInput, outputHandler);
} else {
throw new IllegalArgumentException();
}
results.setCallOutput((S) params.getReturn());
params.removeReturn();
if (inputHandler instanceof AbstractQueryInputHandler) {
input = (T) params;
} else if (inputHandler instanceof AbstractNamedInputHandler) {
input = (T) ((AbstractNamedInputHandler) inputHandler).updateInput(params);
} else {
throw new IllegalArgumentException();
}
results.setCallInput(input);
return results;
} |
python | def running_service_owners(
exclude=('/dev', '/home', '/media', '/proc', '/run', '/sys/', '/tmp',
'/var')
):
'''
Determine which packages own the currently running services. By default,
excludes files whose full path starts with ``/dev``, ``/home``, ``/media``,
``/proc``, ``/run``, ``/sys``, ``/tmp`` and ``/var``. This can be
overridden by passing in a new list to ``exclude``.
CLI Example:
salt myminion introspect.running_service_owners
'''
error = {}
if 'pkg.owner' not in __salt__:
error['Unsupported Package Manager'] = (
'The module for the package manager on this system does not '
'support looking up which package(s) owns which file(s)'
)
if 'file.open_files' not in __salt__:
error['Unsupported File Module'] = (
'The file module on this system does not '
'support looking up open files on the system'
)
if error:
return {'Error': error}
ret = {}
open_files = __salt__['file.open_files']()
execs = __salt__['service.execs']()
for path in open_files:
ignore = False
for bad_dir in exclude:
if path.startswith(bad_dir):
ignore = True
if ignore:
continue
if not os.access(path, os.X_OK):
continue
for service in execs:
if path == execs[service]:
pkg = __salt__['pkg.owner'](path)
ret[service] = next(six.itervalues(pkg))
return ret |
java | public RemoteCommand getRemoteCommand(Jid jid, String node) {
return new RemoteCommand(connection(), node, jid);
} |
java | @Override
public void rebuildModifiedBundles() {
List<JoinableResourceBundle> bundlesToRebuild = rsHandler.getBundlesToRebuild();
for (JoinableResourceBundle bundle : bundlesToRebuild) {
ResourceBundlePathsIterator bundlePaths = this.getBundlePaths(bundle.getId(), new NoCommentCallbackHandler(), Collections.EMPTY_MAP);
while (bundlePaths.hasNext()){
BundlePath bundlePath = bundlePaths.next();
cacheMgr.remove(TEXT_CACHE_PREFIX + bundlePath.getPath());
cacheMgr.remove(ZIP_CACHE_PREFIX + bundlePath.getPath());
}
}
rsHandler.rebuildModifiedBundles();
} |
python | def read_namespaced_job_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_job_status # noqa: E501
read status of the specified Job # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_job_status(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Job (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Job
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_job_status_with_http_info(name, namespace, **kwargs) # noqa: E501
else:
(data) = self.read_namespaced_job_status_with_http_info(name, namespace, **kwargs) # noqa: E501
return data |
python | def input_fields(self, preamble, *args):
"""Get a set of fields from the user. Optionally a preamble may be
shown to the user secribing the fields to return. The fields are
specified as the remaining arguments with each field being a a
list with the following entries:
- a programmer-visible name for the field
- a string prompt to show to the user
- one of the following values:
- string: return a string from the user
- password: return a string from the user but do not echo the
input to the screen
- boolean: return a boolean value from the user
- integer: return an integer value from the user
- the default value (optional)
Fields are requested from the user in the order specified.
Fields are returned in a dictionary with the field names being the keys
and the values being the items.
"""
self.new_section()
if preamble is not None:
self.message(preamble)
if any([True for x in args if len(x) > 3]):
self.message("""
Some questions have default answers which can be selected by
pressing 'Enter' at the prompt.""")
output_dict = { }
for field in args:
(field_name, prompt, field_type) = field[:3]
default = None
if len(field) > 3:
default = field[3]
if field_type == 'string':
output_dict[field_name] = self.input(prompt, default = default)
elif field_type == 'password':
output_dict[field_name] = self.input(prompt, no_echo=True)
elif field_type == 'boolean':
output_dict[field_name] = self.input_boolean(prompt, default = default)
elif field_type == 'integer':
output_dict[field_name] = self.input_integer(prompt, default = default)
return output_dict |
java | @Override
public boolean shouldUseLtpaIfJwtAbsent() {
// TODO Auto-generated method stub
JwtSsoBuilderConfig jwtssobuilderConfig = getJwtSSOBuilderConfig();
if (jwtssobuilderConfig != null) {
return jwtssobuilderConfig.isUseLtpaIfJwtAbsent();
}
return true;
} |
java | public static String firstCharToUpperCase(String str) {
char firstChar = str.charAt(0);
if (firstChar >= 'a' && firstChar <= 'z') {
char[] arr = str.toCharArray();
arr[0] -= ('a' - 'A');
return new String(arr);
}
return str;
} |
python | def warn(self, message, *args, **kwargs):
"""alias to message at warning level"""
self.log("warn", message, *args, **kwargs) |
python | def to_dict(self, serial=False):
'''A dictionary representing the the data of the class is returned.
Native Python objects will still exist in this dictionary (for example,
a ``datetime`` object will be returned rather than a string)
unless ``serial`` is set to True.
'''
if serial:
return dict((key, self._fields[key].to_serial(getattr(self, key)))
for key in list(self._fields.keys()) if hasattr(self, key))
else:
return dict((key, getattr(self, key)) for key in list(self._fields.keys())
if hasattr(self, key)) |
java | public void marshall(DeleteCodeRepositoryRequest deleteCodeRepositoryRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteCodeRepositoryRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteCodeRepositoryRequest.getCodeRepositoryName(), CODEREPOSITORYNAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public ObjectAccessor<T> getRedAccessor(TypeTag enclosingType) {
ObjectAccessor<T> result = buildObjectAccessor();
result.scramble(prefabValues, enclosingType);
return result;
} |
java | @Override
final CancellableTask<K, T> scheduleImpl(final T task, long period, TimeUnit unit) {
final ScheduledFuture<?> future = this.executorService.scheduleAtFixedRate(new RunnableTask(task), 0, period, unit);
return new CancellableScheduledFuture<>(task, future);
} |
python | def _handle_param_list(self, node, scope, ctxt, stream):
"""Handle ParamList nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling param list")
# params should be a list of tuples:
# [(<name>, <field_class>), ...]
params = []
for param in node.params:
self._mark_id_as_lazy(param)
param_info = self._handle_node(param, scope, ctxt, stream)
params.append(param_info)
param_list = functions.ParamListDef(params, node.coord)
return param_list |
java | public static boolean isValidInt(@Nullable final String integerStr, final int lowerBound, final int upperBound, final boolean includeLowerBound, final boolean includeUpperBound) {
if (lowerBound > upperBound) {
throw new IllegalArgumentException(ExceptionValues.INVALID_BOUNDS);
} else if (!isValidInt(integerStr)) {
return false;
}
final int aInteger = toInteger(integerStr);
final boolean respectsLowerBound = includeLowerBound ? lowerBound <= aInteger : lowerBound < aInteger;
final boolean respectsUpperBound = includeUpperBound ? aInteger <= upperBound : aInteger < upperBound;
return respectsLowerBound && respectsUpperBound;
} |
python | def _parse_all_radfuncs(self, func_name):
"""Parse all the nodes with tag func_name in the XML file."""
for node in self.root.findall(func_name):
grid = node.attrib["grid"]
values = np.array([float(s) for s in node.text.split()])
yield self.rad_grids[grid], values, node.attrib |
python | def ajContractions(self):
""" Charge et établit une liste qui donne, chaque contraction, forme non contracte qui lui correspond.
"""
for lin in lignesFichier(self.path("contractions.la")):
ass1, ass2 = tuple(lin.split(':'))
self.lemmatiseur._contractions[ass1] = ass2 |
python | def get_stp_mst_detail_output_cist_port_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ET.SubElement(output, "cist")
port = ET.SubElement(cist, "port")
interface_name = ET.SubElement(port, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
python | def storage_set(self, key, value):
"""
Store a value for the module.
"""
if not self._module:
return
self._storage_init()
module_name = self._module.module_full_name
return self._storage.storage_set(module_name, key, value) |
java | public static int searchIgnoreCase(String str, String keyw) {
return search(str.toLowerCase(), keyw.toLowerCase());
} |
java | @VisibleForTesting
Configuration getHMDriverConf() {
String topologyPackageName = new File(topologyPackageLocation).getName();
String corePackageName = new File(coreReleasePackage).getName();
// topologyName and other configurations are required by Heron Driver/Scheduler to load
// configuration files. Using REEF configuration model is better than depending on external
// persistence.
// TODO: https://github.com/apache/incubator-heron/issues/952: explore sharing across topologies
return HeronDriverConfiguration.CONF
.setMultiple(DriverConfiguration.GLOBAL_LIBRARIES, libJars)
.set(DriverConfiguration.DRIVER_IDENTIFIER, topologyName)
.set(DriverConfiguration.ON_DRIVER_STARTED, HeronSchedulerLauncher.class)
.set(DriverConfiguration.ON_EVALUATOR_ALLOCATED, ContainerAllocationHandler.class)
.set(DriverConfiguration.ON_EVALUATOR_FAILED, FailedContainerHandler.class)
.set(DriverConfiguration.ON_CONTEXT_ACTIVE, HeronWorkerLauncher.class)
.set(DriverConfiguration.ON_TASK_RUNNING, HeronWorkerStartHandler.class)
.set(DriverConfiguration.ON_TASK_COMPLETED, HeronWorkerTaskCompletedErrorHandler.class)
.set(DriverConfiguration.ON_TASK_FAILED, HeronWorkerTaskFailureHandler.class)
.set(DriverConfiguration.GLOBAL_FILES, topologyPackageLocation)
.set(DriverConfiguration.GLOBAL_FILES, coreReleasePackage)
.set(HeronDriverConfiguration.TOPOLOGY_NAME, topologyName)
.set(HeronDriverConfiguration.TOPOLOGY_JAR, topologyJar)
.set(HeronDriverConfiguration.TOPOLOGY_PACKAGE_NAME, topologyPackageName)
.set(HeronDriverConfiguration.HERON_CORE_PACKAGE_NAME, corePackageName)
.set(HeronDriverConfiguration.ROLE, role)
.set(HeronDriverConfiguration.ENV, env)
.set(HeronDriverConfiguration.CLUSTER, cluster)
.set(HeronDriverConfiguration.HTTP_PORT, 0)
.set(HeronDriverConfiguration.VERBOSE, false)
.set(YarnDriverConfiguration.QUEUE, queue)
.set(DriverConfiguration.DRIVER_MEMORY, driverMemory)
.build();
} |
java | public boolean setFeatureStyle(MarkerOptions markerOptions, FeatureRow featureRow) {
return StyleUtils.setFeatureStyle(markerOptions, featureStyleExtension, featureRow, density, iconCache);
} |
python | def WriteProtoFile(self, printer):
"""Write the messages file to out as proto."""
self.Validate()
extended_descriptor.WriteMessagesFile(
self.__file_descriptor, self.__package, self.__client_info.version,
printer) |
java | static boolean isFormula(String value, EvaluationWorkbook workbook) {
try { return FormulaParser.parse(value, (FormulaParsingWorkbook) workbook, 0, 0).length > 1; } // TODO: formulaType and sheet index are 0
catch (FormulaParseException e) { return false; }
} |
java | public boolean isLegalStartColor (int classId, int colorId)
{
ColorRecord color = getColorRecord(classId, colorId);
return (color == null) ? false : color.starter;
} |
python | def _check_train_time(self) -> None:
"""
Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes``
"""
if self._minutes is not None and (datetime.now() - self._training_start).total_seconds()/60 > self._minutes:
raise TrainingTerminated('Training terminated after more than {} minutes'.format(self._minutes)) |
python | def circle_pattern(pattern_radius,
circle_radius,
count,
center=[0.0, 0.0],
angle=None,
**kwargs):
"""
Create a Path2D representing a circle pattern.
Parameters
------------
pattern_radius : float
Radius of circle centers
circle_radius : float
The radius of each circle
count : int
Number of circles in the pattern
center : (2,) float
Center of pattern
angle : float
If defined pattern will span this angle
If None, pattern will be evenly spaced
Returns
-------------
pattern : trimesh.path.Path2D
Path containing circular pattern
"""
from .path import Path2D
if angle is None:
angles = np.linspace(0.0, np.pi * 2.0, count + 1)[:-1]
elif isinstance(angle, float) or isinstance(angle, int):
angles = np.linspace(0.0, angle, count)
else:
raise ValueError('angle must be float or int!')
# centers of circles
centers = np.column_stack((
np.cos(angles), np.sin(angles))) * pattern_radius
vert = []
ents = []
for circle_center in centers:
# (3,3) center points of arc
three = arc.to_threepoint(angles=[0, np.pi],
center=circle_center,
radius=circle_radius)
# add a single circle entity
ents.append(
entities.Arc(
points=np.arange(3) + len(vert),
closed=True))
# keep flat array by extend instead of append
vert.extend(three)
# translate vertices to pattern center
vert = np.array(vert) + center
pattern = Path2D(entities=ents,
vertices=vert,
**kwargs)
return pattern |
java | public ListJobsResult withJobListEntries(JobListEntry... jobListEntries) {
if (this.jobListEntries == null) {
setJobListEntries(new java.util.ArrayList<JobListEntry>(jobListEntries.length));
}
for (JobListEntry ele : jobListEntries) {
this.jobListEntries.add(ele);
}
return this;
} |
python | def get_instance_by_type(dst, disk, do_compress, *args, **kwargs):
"""
Args:
dst (str): The path of the new exported disk.
can contain env variables.
disk (dict): Disk attributes
(of the disk that should be exported) as
found in workdir/current/virt/VM-NAME
do_compress(bool): If true, apply compression to the exported
disk.
Returns
An instance of a subclass of DiskExportManager which
matches the disk type.
"""
disk_type = disk['type']
cls = HANDLERS.get(disk_type)
if not cls:
raise utils.LagoUserException(
'Export is not supported for disk type {}'.format(disk_type)
)
return cls(dst, disk_type, disk, do_compress, *args, **kwargs) |
java | public Buffer capacity(long capacity) {
if (capacity > maxCapacity) {
throw new IllegalArgumentException("capacity cannot be greater than maximum capacity");
} else if (capacity < this.capacity) {
throw new IllegalArgumentException("capacity cannot be decreased");
} else if (capacity != this.capacity) {
// It's possible that the bytes could already meet the requirements of the capacity.
if (offset(capacity) > bytes.size()) {
bytes.resize(Memory.Util.toPow2(offset(capacity)));
}
this.capacity = capacity;
}
return this;
} |
java | public java.util.List<com.google.appengine.v1.InboundServiceType> getInboundServicesList() {
return new com.google.protobuf.Internal.ListAdapter<
java.lang.Integer, com.google.appengine.v1.InboundServiceType>(inboundServices_, inboundServices_converter_);
} |
python | def remove_accessibility_type(self, accessibility_type=None):
"""Removes an accessibility type.
:param accessibility_type: accessibility type to remove
:type accessibility_type: ``osid.type.Type``
:raise: ``NoAccess`` -- ``Metadata.isReadOnly()`` is ``true``
:raise: ``NotFound`` -- acessibility type not found
:raise: ``NullArgument`` -- ``accessibility_type`` is ``null``
*compliance: mandatory -- This method must be implemented.*
"""
if accessibility_type is None:
raise NullArgument
metadata = Metadata(**settings.METADATA['accessibility_type'])
if metadata.is_read_only() or metadata.is_required():
raise NoAccess()
if (accessibility_type._my_map['id']) not in self._my_map['accessibility_type']:
raise NotFound()
self._my_map['accessibility_types'].remove(accessibility_type._my_map['id']) |
python | def value(self):
"""
Read the value from BACnet network
"""
try:
res = self.properties.device.properties.network.read(
"{} {} {} presentValue".format(
self.properties.device.properties.address,
self.properties.type,
str(self.properties.address),
)
)
self._trend(res)
except Exception:
raise Exception("Problem reading : {}".format(self.properties.name))
if res == "inactive":
self._key = 0
self._boolKey = False
else:
self._key = 1
self._boolKey = True
return res |
java | public static void assertEmpty(String message, DataSource dataSource) throws DBAssertionError {
DBAssert.stateAssertion(CallInfo.create(message), empty(dataSource));
} |
java | private boolean simpleReturn(CmsSSLMode mode) {
if (m_server.getValue() == null) {
return true;
}
if (mode != null) {
if (mode.equals(CmsSSLMode.NO)) {
if (((CmsSite)m_server.getValue()).getUrl().contains("http:")) {
return true;
}
} else {
if (((CmsSite)m_server.getValue()).getUrl().contains("https:")) {
return true;
}
}
}
return false;
} |
java | public void marshall(VirtualServiceData virtualServiceData, ProtocolMarshaller protocolMarshaller) {
if (virtualServiceData == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(virtualServiceData.getMeshName(), MESHNAME_BINDING);
protocolMarshaller.marshall(virtualServiceData.getMetadata(), METADATA_BINDING);
protocolMarshaller.marshall(virtualServiceData.getSpec(), SPEC_BINDING);
protocolMarshaller.marshall(virtualServiceData.getStatus(), STATUS_BINDING);
protocolMarshaller.marshall(virtualServiceData.getVirtualServiceName(), VIRTUALSERVICENAME_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public static int manhattanDistance (int x1, int y1, int x2, int y2)
{
return Math.abs(x2 - x1) + Math.abs(y2 - y1);
} |
java | public BatchGetApplicationRevisionsResult withRevisions(RevisionInfo... revisions) {
if (this.revisions == null) {
setRevisions(new com.amazonaws.internal.SdkInternalList<RevisionInfo>(revisions.length));
}
for (RevisionInfo ele : revisions) {
this.revisions.add(ele);
}
return this;
} |
java | @Nullable
public static String safeDecodeAsString (@Nullable final String sEncoded, @Nonnull final Charset aCharset)
{
ValueEnforcer.notNull (aCharset, "Charset");
if (sEncoded != null)
try
{
final byte [] aDecoded = decode (sEncoded, DONT_GUNZIP);
return new String (aDecoded, aCharset);
}
catch (final IOException ex)
{
// Fall through
}
return null;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.