language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public static Widget newShim (int width, int height)
{
Image shim = new Image(_rsrc.blank());
shim.setWidth(width + "px");
shim.setHeight(height + "px");
return shim;
} |
python | def displayable(obj):
"""
Predicate that returns whether the object is displayable or not
(i.e whether the object obeys the nesting hierarchy
"""
if isinstance(obj, Overlay) and any(isinstance(o, (HoloMap, GridSpace))
for o in obj):
return False
if isinstance(obj, HoloMap):
return not (obj.type in [Layout, GridSpace, NdLayout, DynamicMap])
if isinstance(obj, (GridSpace, Layout, NdLayout)):
for el in obj.values():
if not displayable(el):
return False
return True
return True |
java | private Map<Task, Map<LogName, LogFileDetail>> getAllLogsFileDetails(
final List<Task> allAttempts) throws IOException {
Map<Task, Map<LogName, LogFileDetail>> taskLogFileDetails =
new HashMap<Task, Map<LogName, LogFileDetail>>();
for (Task task : allAttempts) {
Map<LogName, LogFileDetail> allLogsFileDetails;
allLogsFileDetails =
TaskLog.getAllLogsFileDetails(task.getTaskID(),
task.isTaskCleanupTask());
taskLogFileDetails.put(task, allLogsFileDetails);
}
return taskLogFileDetails;
} |
java | private ApplicationException getApplicationException(Class<?> klass) // F743-14982
{
ApplicationException result = null;
if (ivApplicationExceptionMap != null)
{
result = ivApplicationExceptionMap.get(klass.getName());
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled() && result != null)
{
Tr.debug(tc, "found application-exception for " + klass.getName()
+ ", rollback=" + result.rollback() + ", inherited=" + result.inherited());
}
}
if (result == null)
{
result = klass.getAnnotation(ApplicationException.class);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled() && result != null)
{
Tr.debug(tc, "found ApplicationException for " + klass.getName()
+ ", rollback=" + result.rollback() + ", inherited=" + result.inherited());
}
}
return result;
} |
java | @Override
public void reset(final String counterName)
{
Preconditions.checkNotNull(counterName);
try
{
// Update the Counter's Status in a New TX to the RESETTING_STATE and apply the TX.
// The "new" TX ensures that no other thread nor parent transaction is performing this operation at the
// same time, since if that were the case the updateCounter would fail. This Work returns the number of
// counter shards that existed for the counter. Capture the number of shards that exist in the counter
// so that the datastore doesn't need to be hit again.
final Integer numCounterShards = ObjectifyService.ofy().transactNew(new Work<Integer>()
{
@Override
public Integer run()
{
// Use the cache here if possible, because the first two short-circuits don't really need accurate
// counts to work.
final Optional<CounterData> optCounterData = getCounterData(counterName);
// /////////////
// ShortCircuit: Do nothing - there's nothing to return.
// /////////////
if (!optCounterData.isPresent())
{
// The counter was not found, so we can't reset it.
throw new NoCounterExistsException(counterName);
}
else
{
final CounterData counterData = optCounterData.get();
// Make sure the counter can be put into the RESETTING state!
assertCounterDetailsMutatable(counterName, counterData.getCounterStatus());
counterData.setCounterStatus(CounterStatus.RESETTING);
ObjectifyService.ofy().save().entity(counterData);
return counterData.getNumShards();
}
}
});
// TODO: Refactor the below code into a transactional enqueing mechansim that either encodes all shards, or
// else creates a single task that re-enqueues itself with a decrementing number so that it will run on
// every shard and then reset the status of the counter. In this way, "reset" can be async, and work for
// shards larger than 25, but since the counter is in the RESETTING state, it won't be allowed to be
// mutated.
// For now, perform all reset operations in same TX to provide atomic rollback. Since Appengine now support
// up to 25 entities in a transaction, this will work for all counters up to 25 shards.
ObjectifyService.ofy().transactNew(new VoidWork()
{
@Override
public void vrun()
{
// For each shard, reset it. Shard Index starts at 0.
for (int shardNumber = 0; shardNumber < numCounterShards; shardNumber++)
{
final ResetCounterShardWork resetWork = new ResetCounterShardWork(counterName, shardNumber);
ObjectifyService.ofy().transact(resetWork);
}
}
});
}
finally
{
// Clear the cache to ensure that future callers get the right count.
this.memcacheSafeDelete(counterName);
// If the reset-shards loop above completes properly, OR if an exception is thrown above, the counter status
// needs to be reset to AVAILABLE. In the first case (an exception is thrown) then the reset TX will be
// rolled-back, and the counter status needs to become AVAILABLE. In the second case (the counter was
// successfully reset) the same counter status update to AVAILABLE needs to occur.
ObjectifyService.ofy().transactNew(new VoidWork()
{
/**
* Updates the {@link CounterData} status to be {@link CounterStatus#AVAILABLE}, but only if the current
* status is {@link CounterStatus#RESETTING}.
*/
@Override
public void vrun()
{
final Optional<CounterData> optCounterData = getCounterData(counterName);
if (optCounterData.isPresent())
{
final CounterData counterData = optCounterData.get();
if (counterData.getCounterStatus() == CounterStatus.RESETTING)
{
counterData.setCounterStatus(CounterStatus.AVAILABLE);
ObjectifyService.ofy().save().entity(counterData).now();
}
}
}
});
}
} |
python | def from_dict(self, d):
"""
Create a Stage from a dictionary. The change is in inplace.
:argument: python dictionary
:return: None
"""
if 'uid' in d:
if d['uid']:
self._uid = d['uid']
if 'name' in d:
if d['name']:
self._name = d['name']
if 'state' in d:
if isinstance(d['state'], str) or isinstance(d['state'], unicode):
if d['state'] in states._stage_state_values.keys():
self._state = d['state']
else:
raise ValueError(obj=self._uid,
attribute='state',
expected_value=states._stage_state_values.keys(),
actual_value=value)
else:
raise TypeError(entity='state', expected_type=str, actual_type=type(d['state']))
else:
self._state = states.INITIAL
if 'state_history' in d:
if isinstance(d['state_history'], list):
self._state_history = d['state_history']
else:
raise TypeError(entity='state_history', expected_type=list, actual_type=type(d['state_history']))
if 'parent_pipeline' in d:
if isinstance(d['parent_pipeline'], dict):
self._p_pipeline = d['parent_pipeline']
else:
raise TypeError(entity='parent_pipeline', expected_type=dict, actual_type=type(d['parent_pipeline'])) |
java | public ListS3ResourcesResult withS3Resources(S3ResourceClassification... s3Resources) {
if (this.s3Resources == null) {
setS3Resources(new java.util.ArrayList<S3ResourceClassification>(s3Resources.length));
}
for (S3ResourceClassification ele : s3Resources) {
this.s3Resources.add(ele);
}
return this;
} |
python | def put(self):
"""
Save changes made to the object to DocumentCloud.
According to DocumentCloud's docs, edits are allowed for the following
fields:
* title
* source
* description
* related_article
* access
* published_url
* data key/value pairs
Returns nothing.
"""
params = dict(
title=self.title or '',
source=self.source or '',
description=self.description or '',
related_article=self.resources.related_article or '',
published_url=self.resources.published_url or '',
access=self.access,
data=self.data,
)
self._connection.put('documents/%s.json' % self.id, params) |
java | public static <T> Collection<T> plus(Collection<T> left, Collection<T> right) {
final Collection<T> answer = cloneSimilarCollection(left, left.size() + right.size());
answer.addAll(right);
return answer;
} |
java | public Headers getHttpHeaders()
{
Headers headers = new Headers();
if ( byteRange != null ) {
StringBuilder rangeBuilder = new StringBuilder( "bytes=" );
long start;
if ( byteRange.offset >= 0 ) {
rangeBuilder.append( byteRange.offset );
start = byteRange.offset;
} else {
start = 1;
}
rangeBuilder.append( "-" );
if ( byteRange.length > 0 ) {
rangeBuilder.append( start + byteRange.length - 1 );
}
Header rangeHeader = new BasicHeader( "Range", rangeBuilder.toString() );
headers.addHeader( rangeHeader );
}
return headers;
} |
python | def remove_team_membership(self, auth, team_id, username):
"""
Remove user from team.
:param auth.Authentication auth: authentication object, must be admin-level
:param str team_id: Team's id
:param str username: Username of the user to be removed from the team
:raises NetworkFailure: if there is an error communicating with the server
:raises ApiFailure: if the request cannot be serviced
"""
url = "/admin/teams/{t}/members/{u}".format(t=team_id, u=username)
self.delete(url, auth=auth) |
java | public Set<MongoNamespace> getSynchronizedNamespaces() {
instanceLock.readLock().lock();
try {
return new HashSet<>(namespaces.keySet());
} finally {
instanceLock.readLock().unlock();
}
} |
java | private ShareTarget findShareTarget(String pkg) {
for (ShareTarget target : mShareTargets) {
if (pkg.equals(target.packageName)) {
return target;
}
}
return null;
} |
java | private ProjectFile readDatabaseFile(InputStream inputStream) throws MPXJException
{
ProjectReader reader = new AstaDatabaseFileReader();
addListeners(reader);
return reader.read(inputStream);
} |
java | public static <T> Predicate<T> or(Predicate<? super T> first, Predicate<? super T> second) {
checkArgNotNull(first, "first");
checkArgNotNull(second, "second");
return new OrPredicate<T>(ImmutableList.<Predicate<? super T>>of(first, second));
} |
python | def apply_trend_constraint(self, limit, dt, distribution_skip=False,
**kwargs):
"""
Constrains change in RV to be less than limit over time dt.
Only works if ``dRV`` and ``Plong`` attributes are defined
for population.
:param limit:
Radial velocity limit on trend. Must be
:class:`astropy.units.Quantity` object, or
else interpreted as m/s.
:param dt:
Time baseline of RV observations. Must be
:class:`astropy.units.Quantity` object; else
interpreted as days.
:param distribution_skip:
This is by default ``True``. *To be honest, I'm not
exactly sure why. Might be important, might not
(don't remember).*
:param **kwargs:
Additional keyword arguments passed to
:func:`StarPopulation.apply_constraint`.
"""
if type(limit) != Quantity:
limit = limit * u.m/u.s
if type(dt) != Quantity:
dt = dt * u.day
dRVs = np.absolute(self.dRV(dt))
c1 = UpperLimit(dRVs, limit)
c2 = LowerLimit(self.Plong, dt*4)
self.apply_constraint(JointConstraintOr(c1,c2,name='RV monitoring',
Ps=self.Plong,dRVs=dRVs),
distribution_skip=distribution_skip, **kwargs) |
java | @Override
public List<Integer> getReplicatingPartitionList(int index) {
List<Node> preferenceNodesList = new ArrayList<Node>(getNumReplicas());
List<Integer> replicationPartitionsList = new ArrayList<Integer>(getNumReplicas());
// Copy Zone based Replication Factor
HashMap<Integer, Integer> requiredRepFactor = new HashMap<Integer, Integer>();
requiredRepFactor.putAll(zoneReplicationFactor);
// Cross-check if individual zone replication factor equals global
int sum = 0;
for(Integer zoneRepFactor: requiredRepFactor.values()) {
sum += zoneRepFactor;
}
if(sum != getNumReplicas())
throw new IllegalArgumentException("Number of zone replicas is not equal to the total replication factor");
if(getPartitionToNode().length == 0) {
return new ArrayList<Integer>(0);
}
for(int i = 0; i < getPartitionToNode().length; i++) {
// add this one if we haven't already, and it can satisfy some zone
// replicationFactor
Node currentNode = getNodeByPartition(index);
if(!preferenceNodesList.contains(currentNode)) {
preferenceNodesList.add(currentNode);
if(checkZoneRequirement(requiredRepFactor, currentNode.getZoneId()))
replicationPartitionsList.add(index);
}
// if we have enough, go home
if(replicationPartitionsList.size() >= getNumReplicas())
return replicationPartitionsList;
// move to next clockwise slot on the ring
index = (index + 1) % getPartitionToNode().length;
}
// we don't have enough, but that may be okay
return replicationPartitionsList;
} |
python | def QA_util_realtime(strtime, client):
"""
查询数据库中的数据
:param strtime: strtime str字符串 -- 1999-12-11 这种格式
:param client: client pymongo.MongoClient类型 -- mongodb 数据库 从 QA_util_sql_mongo_setting 中 QA_util_sql_mongo_setting 获取
:return: Dictionary -- {'time_real': 时间,'id': id}
"""
time_stamp = QA_util_date_stamp(strtime)
coll = client.quantaxis.trade_date
temp_str = coll.find_one({'date_stamp': {"$gte": time_stamp}})
time_real = temp_str['date']
time_id = temp_str['num']
return {'time_real': time_real, 'id': time_id} |
java | @XmlElementDecl(namespace = "http://www.opengis.net/citygml/texturedsurface/2.0", name = "Material", substitutionHeadNamespace = "http://www.opengis.net/citygml/texturedsurface/2.0", substitutionHeadName = "_Appearance")
public JAXBElement<MaterialType> createMaterial(MaterialType value) {
return new JAXBElement<MaterialType>(_Material_QNAME, MaterialType.class, null, value);
} |
python | def _serialize_value(self, value):
"""
Called by :py:meth:`._serialize` to serialise an individual value.
"""
if isinstance(value, (list, tuple, set)):
return [self._serialize_value(v) for v in value]
elif isinstance(value, dict):
return dict([(k, self._serialize_value(v)) for k, v in value.items()])
elif isinstance(value, ModelBase):
return value._serialize()
elif isinstance(value, datetime.date): # includes datetime.datetime
return value.isoformat()
else:
return value |
java | @Override
public void set(long timestampMs, long value) {
long[] bucket = calcBucketOffset(timestampMs);
String redisKey = getName() + ":" + bucket[0];
String redisField = String.valueOf(bucket[1]);
try (Jedis jedis = getJedis()) {
jedis.hset(redisKey, redisField, String.valueOf(value));
if (ttlSeconds > 0) {
jedis.expire(redisKey, ttlSeconds);
}
}
} |
python | def mchirp_sampler_imf(**kwargs):
''' Draw chirp mass samples for power-law model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
mchirp-astro: array
The chirp mass samples for the population
'''
m1, m2 = draw_imf_samples(**kwargs)
mchirp_astro = mchirp_from_mass1_mass2(m1, m2)
return mchirp_astro |
java | @Override
public void pin(Object key)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.entry(tc, "pin", key);
Bucket bucket = getOrCreateBucketForKey(key); // d739870
int pinCount;
synchronized (bucket) {
Element element = bucket.findByKey(key);
if (element == null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "pin - throw NoSuchObjectException"); // d173022.12
throw new NoSuchObjectException(key);
}
element.pinned++;
pinCount = element.pinned;
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Tr.exit(tc, "pin:" + pinCount);
} |
java | public synchronized ServletStats initServletStats(String _app, String _ser) {
String _key = _app + "." + _ser;
ServletStats nStats = this.servletCountByName.get(_key);
if (nStats == null) {
nStats = new ServletStats(_app, _ser);
this.servletCountByName.put(_key, nStats);
}
return nStats;
} |
python | def randmatrix(m, n, random_seed=None):
"""Creates an m x n matrix of random values drawn using
the Xavier Glorot method."""
val = np.sqrt(6.0 / (m + n))
np.random.seed(random_seed)
return np.random.uniform(-val, val, size=(m, n)) |
python | def write_as_dot(self, f, data=None, max_levels=None):
"Write the tree in the dot language format to f."
assert (max_levels is None) or (max_levels >= 0)
def visit_node(n, levels):
lbl = "{"
if data is None:
if self.k <= max_k_labeled:
lbl = repr(n.label()).\
replace("{","\{").\
replace("}","\}").\
replace("|","\|").\
replace("<","\<").\
replace(">","\>")
else:
lbl = str(n)
else:
s = self.bucket_to_block(n.bucket)
for i in xrange(self.blocks_per_bucket):
lbl += "{%s}" % (data[s+i])
if i + 1 != self.blocks_per_bucket:
lbl += "|"
lbl += "}"
f.write(" %s [penwidth=%s,label=\"%s\"];\n"
% (n.bucket, 1, lbl))
levels += 1
if (max_levels is None) or (levels <= max_levels):
for i in xrange(self.k):
cn = n.child_node(i)
if not self.is_nil_node(cn):
visit_node(cn, levels)
f.write(" %s -> %s ;\n" % (n.bucket, cn.bucket))
f.write("// Created by SizedVirtualHeap.write_as_dot(...)\n")
f.write("digraph heaptree {\n")
f.write("node [shape=record]\n")
if (max_levels is None) or (max_levels > 0):
visit_node(self.root_node(), 1)
f.write("}\n") |
java | @Override
public Iterator<T> iterator() {
Iterator<T> transformed = Iterators.transform(rows.iterator(), row -> {
T value = mapper.map(row);
mapper.mappingComplete();
return value;
});
mapper.mappingComplete();
return transformed;
} |
python | def get_random_word(dictionary, starting_letter=None):
"""
Takes the dictionary to read from and returns a random word
optionally accepts a starting letter
"""
if starting_letter is None:
starting_letter = random.choice(list(dictionary.keys()))
try:
to_return = random.choice(dictionary[starting_letter])
except KeyError:
msg = "Dictionary does not contain a word starting with '{}'"
raise NoWordForLetter(msg.format(starting_letter))
return to_return |
java | public static void setValue(Object target, String dPath, Object value) {
setValue(target, dPath, value, false);
} |
java | private com.ibm.ws.javaee.ddmodel.webext.WebExtComponentImpl getConfigOverrides(
OverlayContainer overlay,
ArtifactContainer artifactContainer) throws UnableToAdaptException {
// No match is possible, and no errors are possible, when there are no
// web extension configuration overrides.
if ( (configurations == null) || configurations.isEmpty() ) {
return null;
}
// Maybe application information is directly available ...
ApplicationInfo appInfo = (ApplicationInfo)
overlay.getFromNonPersistentCache(artifactContainer.getPath(), ApplicationInfo.class);
// Or, maybe module information is available and application information can
// be obtained from that ...
ModuleInfo moduleInfo = null;
if ( appInfo == null ) {
moduleInfo = (ModuleInfo) overlay.getFromNonPersistentCache(artifactContainer.getPath(), ModuleInfo.class);
if ( moduleInfo == null ) {
return null;
}
appInfo = moduleInfo.getApplicationInfo();
if ( appInfo == null ) {
return null;
}
}
// Need a configuration helper ... but that is only available
// if the application information is of supported type.
if ( !(appInfo instanceof ExtendedApplicationInfo) ) {
return null;
}
NestedConfigHelper configHelper = ((ExtendedApplicationInfo) appInfo).getConfigHelper();
if ( configHelper == null ) {
return null;
}
// If the module is a bare module, it's overlay is the root overlay.
// If the module is nested, the root overlay is the parent of the
// module's overlay.
//
// The root overlay is used for marking web extension override errors:
// The errors, "module.name.invalid" and "module.name.not.specified"
// are possible. Note that each of these is recorded at most once,
// regardless of how many invalid overrides are present.
OverlayContainer rootOverlay = overlay;
if ( overlay.getParentOverlay() != null ) {
rootOverlay = overlay.getParentOverlay();
}
// The configurations were injected by the service machinery.
// Loop through these to fine one which matches the target module name.
// Generate errors along the way.
//
// What errors are generated depends on the order of processing.
//
// A web extension override which does not have a name is invalid, but
// that won't be detected unless there is a module which matches an override
// which follows the invalid override.
//
// Note that at most one error is generated, regardless of how many web
// module overrides are missing module names.
Set<String> overrideModuleNames = new HashSet<String>();
String servicePid = (String) configHelper.get("service.pid");
String extendsPid = (String) configHelper.get("ibm.extends.source.pid");
for ( com.ibm.ws.javaee.dd.webext.WebExt config : configurations ) {
com.ibm.ws.javaee.ddmodel.webext.WebExtComponentImpl configImpl =
(com.ibm.ws.javaee.ddmodel.webext.WebExtComponentImpl) config;
String parentPid = (String) configImpl.getConfigAdminProperties().get("config.parentPID");
if ( !servicePid.equals(parentPid) && !parentPid.equals(extendsPid)) {
continue;
}
if ( moduleInfo == null ) {
return configImpl;
}
// Try to match the web extension overrides to the current module based on
// the module name.
//
// Build up a list of the web extension override module names. Those are
// are used if no matching override is found for the current module.
//
// A web extension override must supply a module name. If one is detected,
// emit an error, and continue on to the next override.
String overrideModuleName = (String) configImpl.getConfigAdminProperties().get("moduleName");
if ( overrideModuleName == null ) {
if ( markError(rootOverlay, MODULE_NAME_NOT_SPECIFIED) ) {
Tr.error(tc, "module.name.not.specified", "web-ext" );
}
continue;
}
overrideModuleName = stripExtension(overrideModuleName);
overrideModuleNames.add(overrideModuleName);
if ( moduleInfo.getName().equals(overrideModuleName) ) {
return configImpl;
}
}
// If we got this far, no matching override was located.
//
// Not finding a web extension override is considered to be an error --
// if there are any web extension overrides which are specified to
// modules not named in the application descriptor.
if ( (moduleInfo != null) && !overrideModuleNames.isEmpty() ) {
if ( markError(rootOverlay, MODULE_NAME_INVALID) ) {
Application appDD = appInfo.getContainer().adapt(Application.class);
if ( appDD != null ) {
Set<String> moduleDDNames = new HashSet<String>();
for ( Module moduleDD : appDD.getModules() ) {
String moduleDDName = stripExtension( moduleDD.getModulePath() );
moduleDDNames.add(moduleDDName);
}
overrideModuleNames.removeAll(moduleDDNames);
}
if ( !overrideModuleNames.isEmpty() ) {
Tr.error(tc, "module.name.invalid", overrideModuleNames, "web-ext");
}
}
}
return null;
} |
java | public Effort createEffort(double value, Map<String, Object> attributes) {
return createEffort(value, null, null, attributes);
} |
python | def rgb2bgr(self):
""" Converts data using the cv conversion. """
new_data = cv2.cvtColor(self.raw_data, cv2.COLOR_RGB2BGR)
return ColorImage(new_data, frame=self.frame, encoding='bgr8') |
python | def cancel(self):
"""
Cancels the current lookup.
"""
if self._running:
self.interrupt()
self._running = False
self._cancelled = True
self.loadingFinished.emit() |
python | def append_manage_data_op(self, data_name, data_value, source=None):
"""Append a :class:`ManageData <stellar_base.operation.ManageData>`
operation to the list of operations.
:param str data_name: String up to 64 bytes long. If this is a new Name
it will add the given name/value pair to the account. If this Name
is already present then the associated value will be modified.
:param data_value: If not present then the existing
Name will be deleted. If present then this value will be set in the
DataEntry. Up to 64 bytes long.
:type data_value: str, bytes, None
:param str source: The source account on which data is being managed.
operation.
:return: This builder instance.
"""
op = operation.ManageData(data_name, data_value, source)
return self.append_op(op) |
java | @Override
public RoundedMoney subtract(MonetaryAmount subtrahend) {
MoneyUtils.checkAmountParameter(subtrahend, currency);
if (subtrahend.isZero()) {
return this;
}
MathContext mc = monetaryContext.get(MathContext.class);
if(mc==null){
mc = MathContext.DECIMAL64;
}
return new RoundedMoney(number.subtract(subtrahend.getNumber().numberValue(BigDecimal.class), mc),
currency, rounding);
} |
python | def print_debug(self, msg):
"""Log some debugging information to the console"""
assert isinstance(msg, bytes)
state = STATE_NAMES[self.state].encode()
console_output(b'[dbg] ' + self.display_name.encode() + b'[' + state +
b']: ' + msg + b'\n') |
python | def genExamplePlanet(binaryLetter=''):
""" Creates a fake planet with some defaults
:param `binaryLetter`: host star is part of a binary with letter binaryletter
:return:
"""
planetPar = PlanetParameters()
planetPar.addParam('discoverymethod', 'transit')
planetPar.addParam('discoveryyear', '2001')
planetPar.addParam('eccentricity', '0.09')
planetPar.addParam('inclination', '89.2')
planetPar.addParam('lastupdate', '12/12/08')
planetPar.addParam('mass', '3.9')
planetPar.addParam('name', 'Example Star {0}{1} b'.format(ac._ExampleSystemCount, binaryLetter))
planetPar.addParam('period', '111.2')
planetPar.addParam('radius', '0.92')
planetPar.addParam('semimajoraxis', '0.449')
planetPar.addParam('temperature', '339.6')
planetPar.addParam('transittime', '2454876.344')
planetPar.addParam('separation', '330', {'unit': 'AU'})
examplePlanet = Planet(planetPar.params)
examplePlanet.flags.addFlag('Fake')
exampleStar = genExampleStar(binaryLetter=binaryLetter)
exampleStar._addChild(examplePlanet)
examplePlanet.parent = exampleStar
return examplePlanet |
java | public boolean execute(GString gstring) throws SQLException {
List<Object> params = getParameters(gstring);
String sql = asSql(gstring, params);
return execute(sql, params);
} |
java | private static int parseServiceUuid(byte[] scanRecord, int currentPos, int dataLength,
int uuidLength, List<ParcelUuid> serviceUuids) {
while (dataLength > 0) {
byte[] uuidBytes = extractBytes(scanRecord, currentPos,
uuidLength);
serviceUuids.add(parseUuidFrom(uuidBytes));
dataLength -= uuidLength;
currentPos += uuidLength;
}
return currentPos;
} |
python | def postprocess_keyevent(self, event):
"""Post-process keypress event:
in InternalShell, this is method is called when shell is ready"""
event, text, key, ctrl, shift = restore_keyevent(event)
# Is cursor on the last line? and after prompt?
if len(text):
#XXX: Shouldn't it be: `if len(unicode(text).strip(os.linesep))` ?
if self.has_selected_text():
self.check_selection()
self.restrict_cursor_position(self.current_prompt_pos, 'eof')
cursor_position = self.get_position('cursor')
if key in (Qt.Key_Return, Qt.Key_Enter):
if self.is_cursor_on_last_line():
self._key_enter()
# add and run selection
else:
self.insert_text(self.get_selected_text(), at_end=True)
elif key == Qt.Key_Insert and not shift and not ctrl:
self.setOverwriteMode(not self.overwriteMode())
elif key == Qt.Key_Delete:
if self.has_selected_text():
self.check_selection()
self.remove_selected_text()
elif self.is_cursor_on_last_line():
self.stdkey_clear()
elif key == Qt.Key_Backspace:
self._key_backspace(cursor_position)
elif key == Qt.Key_Tab:
self._key_tab()
elif key == Qt.Key_Space and ctrl:
self._key_ctrl_space()
elif key == Qt.Key_Left:
if self.current_prompt_pos == cursor_position:
# Avoid moving cursor on prompt
return
method = self.extend_selection_to_next if shift \
else self.move_cursor_to_next
method('word' if ctrl else 'character', direction='left')
elif key == Qt.Key_Right:
if self.is_cursor_at_end():
return
method = self.extend_selection_to_next if shift \
else self.move_cursor_to_next
method('word' if ctrl else 'character', direction='right')
elif (key == Qt.Key_Home) or ((key == Qt.Key_Up) and ctrl):
self._key_home(shift, ctrl)
elif (key == Qt.Key_End) or ((key == Qt.Key_Down) and ctrl):
self._key_end(shift, ctrl)
elif key == Qt.Key_Up:
if not self.is_cursor_on_last_line():
self.set_cursor_position('eof')
y_cursor = self.get_coordinates(cursor_position)[1]
y_prompt = self.get_coordinates(self.current_prompt_pos)[1]
if y_cursor > y_prompt:
self.stdkey_up(shift)
else:
self.browse_history(backward=True)
elif key == Qt.Key_Down:
if not self.is_cursor_on_last_line():
self.set_cursor_position('eof')
y_cursor = self.get_coordinates(cursor_position)[1]
y_end = self.get_coordinates('eol')[1]
if y_cursor < y_end:
self.stdkey_down(shift)
else:
self.browse_history(backward=False)
elif key in (Qt.Key_PageUp, Qt.Key_PageDown):
#XXX: Find a way to do this programmatically instead of calling
# widget keyhandler (this won't work if the *event* is coming from
# the event queue - i.e. if the busy buffer is ever implemented)
ConsoleBaseWidget.keyPressEvent(self, event)
elif key == Qt.Key_Escape and shift:
self.clear_line()
elif key == Qt.Key_Escape:
self._key_escape()
elif key == Qt.Key_L and ctrl:
self.clear_terminal()
elif key == Qt.Key_V and ctrl:
self.paste()
elif key == Qt.Key_X and ctrl:
self.cut()
elif key == Qt.Key_Z and ctrl:
self.undo()
elif key == Qt.Key_Y and ctrl:
self.redo()
elif key == Qt.Key_A and ctrl:
self.selectAll()
elif key == Qt.Key_Question and not self.has_selected_text():
self._key_question(text)
elif key == Qt.Key_ParenLeft and not self.has_selected_text():
self._key_parenleft(text)
elif key == Qt.Key_Period and not self.has_selected_text():
self._key_period(text)
elif len(text) and not self.isReadOnly():
self.hist_wholeline = False
self.insert_text(text)
self._key_other(text)
else:
# Let the parent widget handle the key press event
ConsoleBaseWidget.keyPressEvent(self, event) |
python | def compare(cls, left, right):
"""
Main comparison function for all Firestore types.
@return -1 is left < right, 0 if left == right, otherwise 1
"""
# First compare the types.
leftType = TypeOrder.from_value(left).value
rightType = TypeOrder.from_value(right).value
if leftType != rightType:
if leftType < rightType:
return -1
return 1
value_type = left.WhichOneof("value_type")
if value_type == "null_value":
return 0 # nulls are all equal
elif value_type == "boolean_value":
return cls._compare_to(left.boolean_value, right.boolean_value)
elif value_type == "integer_value":
return cls.compare_numbers(left, right)
elif value_type == "double_value":
return cls.compare_numbers(left, right)
elif value_type == "timestamp_value":
return cls.compare_timestamps(left, right)
elif value_type == "string_value":
return cls._compare_to(left.string_value, right.string_value)
elif value_type == "bytes_value":
return cls.compare_blobs(left, right)
elif value_type == "reference_value":
return cls.compare_resource_paths(left, right)
elif value_type == "geo_point_value":
return cls.compare_geo_points(left, right)
elif value_type == "array_value":
return cls.compare_arrays(left, right)
elif value_type == "map_value":
return cls.compare_objects(left, right)
else:
raise ValueError("Unknown ``value_type``", str(value_type)) |
java | @Deprecated
public Object saveView(FacesContext context) {
Object stateArray[] = null;
if (!context.getAttributes().containsKey(IS_CALLED_FROM_API_CLASS)) {
SerializedView view = saveSerializedView(context);
if (null != view) {
stateArray = new Object[]{view.getStructure(),
view.getState()};
}
}
return stateArray;
} |
java | public static <E> String generateQuestion(Collection<E> args) {
if (args == null || args.size() == 0)
return "";
return generateInternal(args.size());
} |
python | def ratio_deep_compare(self, other, settings):
"""
Compares each field of the name one at a time to see if they match.
Each name field has context-specific comparison logic.
:param Name other: other Name for comparison
:return int: sequence ratio match (out of 100)
"""
if not self._is_compatible_with(other):
return 0
first, middle, last = self._compare_components(other, settings, True)
f_weight, m_weight, l_weight = self._determine_weights(other, settings)
total_weight = f_weight + m_weight + l_weight
result = (
first * f_weight +
middle * m_weight +
last * l_weight
) / total_weight
return result |
python | def _check_fill_title_row(self, row_index):
'''
Checks the given row to see if it is all titles and fills any blanks cells if that is the
case.
'''
table_row = self.table[row_index]
# Determine if the whole row is titles
prior_row = self.table[row_index-1] if row_index > 0 else table_row
for column_index in range(self.start[1], self.end[1]):
if is_num_cell(table_row[column_index]) or is_num_cell(prior_row[column_index]):
return
# Since we're a title row, stringify the row
self._stringify_row(row_index) |
python | def organisation_group_id(self):
"""
str: Organisation Group ID
"""
self._validate()
self._validate_for_organisation_group_id()
parts = []
parts.append(self.election_type)
if self.subtype:
parts.append(self.subtype)
parts.append(self.organisation)
parts.append(self.date)
return ".".join(parts) |
python | def dataframe_select(df, *cols, **filters):
'''
dataframe_select(df, k1=v1, k2=v2...) yields df after selecting all the columns in which the
given keys (k1, k2, etc.) have been selected such that the associated columns in the dataframe
contain only the rows whose cells match the given values.
dataframe_select(df, col1, col2...) selects the given columns.
dataframe_select(df, col1, col2..., k1=v1, k2=v2...) selects both.
If a value is a tuple/list of 2 elements, then it is considered a range where cells must fall
between the values. If value is a tuple/list of more than 2 elements or is a set of any length
then it is a list of values, any one of which can match the cell.
'''
ii = np.ones(len(df), dtype='bool')
for (k,v) in six.iteritems(filters):
vals = df[k].values
if pimms.is_set(v): jj = np.isin(vals, list(v))
elif pimms.is_vector(v) and len(v) == 2: jj = (v[0] <= vals) & (vals < v[1])
elif pimms.is_vector(v): jj = np.isin(vals, list(v))
else: jj = (vals == v)
ii = np.logical_and(ii, jj)
if len(ii) != np.sum(ii): df = df.loc[ii]
if len(cols) > 0: df = df[list(cols)]
return df |
java | public static void jenkins(final BitVector bv, final long seed, final long[] h) {
final long length = bv.length();
long a, b, c, from = 0;
if (length == 0) {
h[0] = seed ^ 0x8de6a918d6538324L;
h[1] = seed ^ 0x6bda2aef21654e7dL;
h[2] = seed ^ 0x36071e726d0ba0c5L;
return;
}
/* Set up the internal state */
a = b = seed;
c = ARBITRARY_BITS;
while (length - from > Long.SIZE * 2) {
a += bv.getLong(from, from + Long.SIZE);
b += bv.getLong(from + Long.SIZE, from + 2 * Long.SIZE);
c += bv.getLong(from + 2 * Long.SIZE, Math.min(from + 3 * Long.SIZE, length));
a -= b;
a -= c;
a ^= (c >>> 43);
b -= c;
b -= a;
b ^= (a << 9);
c -= a;
c -= b;
c ^= (b >>> 8);
a -= b;
a -= c;
a ^= (c >>> 38);
b -= c;
b -= a;
b ^= (a << 23);
c -= a;
c -= b;
c ^= (b >>> 5);
a -= b;
a -= c;
a ^= (c >>> 35);
b -= c;
b -= a;
b ^= (a << 49);
c -= a;
c -= b;
c ^= (b >>> 11);
a -= b;
a -= c;
a ^= (c >>> 12);
b -= c;
b -= a;
b ^= (a << 18);
c -= a;
c -= b;
c ^= (b >>> 22);
from += 3 * Long.SIZE;
}
c += length;
long residual = length - from;
if (residual > 0) {
if (residual > Long.SIZE) {
a += bv.getLong(from, from + Long.SIZE);
residual -= Long.SIZE;
}
if (residual != 0) b += bv.getLong(length - residual, length);
}
a -= b;
a -= c;
a ^= (c >>> 43);
b -= c;
b -= a;
b ^= (a << 9);
c -= a;
c -= b;
c ^= (b >>> 8);
a -= b;
a -= c;
a ^= (c >>> 38);
b -= c;
b -= a;
b ^= (a << 23);
c -= a;
c -= b;
c ^= (b >>> 5);
a -= b;
a -= c;
a ^= (c >>> 35);
b -= c;
b -= a;
b ^= (a << 49);
c -= a;
c -= b;
c ^= (b >>> 11);
a -= b;
a -= c;
a ^= (c >>> 12);
b -= c;
b -= a;
b ^= (a << 18);
c -= a;
c -= b;
c ^= (b >>> 22);
h[0] = a;
h[1] = b;
h[2] = c;
} |
python | def all():
"""clean the dis and uninstall cloudmesh"""
dir()
cmd3()
banner("CLEAN PREVIOUS CLOUDMESH INSTALLS")
r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True))
while r > 0:
local('echo "y\n" | pip uninstall cloudmesh')
r = int(local("pip freeze |fgrep cloudmesh | wc -l", capture=True)) |
python | def _add_edge_dmap_fun(graph, edges_weights=None):
"""
Adds edge to the dispatcher map.
:param graph:
A directed graph.
:type graph: networkx.classes.digraph.DiGraph
:param edges_weights:
Edge weights.
:type edges_weights: dict, optional
:return:
A function that adds an edge to the `graph`.
:rtype: callable
"""
add = graph.add_edge # Namespace shortcut for speed.
if edges_weights is not None:
def add_edge(i, o, w):
if w in edges_weights:
add(i, o, weight=edges_weights[w]) # Weighted edge.
else:
add(i, o) # Normal edge.
else:
# noinspection PyUnusedLocal
def add_edge(i, o, w):
add(i, o) # Normal edge.
return add_edge |
java | public void unreferenceSSTables()
{
Set<SSTableReader> notCompacting;
View currentView, newView;
do
{
currentView = view.get();
notCompacting = currentView.nonCompactingSStables();
newView = currentView.replace(notCompacting, Collections.<SSTableReader>emptySet());
}
while (!view.compareAndSet(currentView, newView));
if (notCompacting.isEmpty())
{
// notifySSTablesChanged -> LeveledManifest.promote doesn't like a no-op "promotion"
return;
}
notifySSTablesChanged(notCompacting, Collections.<SSTableReader>emptySet(), OperationType.UNKNOWN);
removeOldSSTablesSize(notCompacting);
releaseReferences(notCompacting, true);
} |
java | Symbol findImmediateMemberType(Env<AttrContext> env,
Type site,
Name name,
TypeSymbol c) {
Scope.Entry e = c.members().lookup(name);
while (e.scope != null) {
if (e.sym.kind == TYP) {
return isAccessible(env, site, e.sym)
? e.sym
: new AccessError(env, site, e.sym);
}
e = e.next();
}
return typeNotFound;
} |
java | public static boolean checkCharacter(int c, boolean foundQuestionMark) throws IOException {
if(foundQuestionMark) {
switch(c) {
case '.':
case '-':
case '*':
case '_':
case '+': // converted space
case '%': // encoded value
// Other characters used outside the URL data
//case ':':
//case '/':
//case '@':
//case ';':
//case '?':
// Parameter separators
case '=':
case '&':
// Anchor separator
case '#':
return true;
default:
if(
(c<'a' || c>'z')
&& (c<'A' || c>'Z')
&& (c<'0' || c>'9')
) throw new IOException(ApplicationResources.accessor.getMessage("UrlValidator.invalidCharacter", Integer.toHexString(c)));
return true;
}
} else {
return c=='?';
}
} |
java | private final int getBlockIndexForPosition(final BlockLocation[] blocks, final long offset,
final long halfSplitSize, final int startIndex) {
// go over all indexes after the startIndex
for (int i = startIndex; i < blocks.length; i++) {
long blockStart = blocks[i].getOffset();
long blockEnd = blockStart + blocks[i].getLength();
if (offset >= blockStart && offset < blockEnd) {
// got the block where the split starts
// check if the next block contains more than this one does
if (i < blocks.length - 1 && blockEnd - offset < halfSplitSize) {
return i + 1;
} else {
return i;
}
}
}
throw new IllegalArgumentException("The given offset is not contained in the any block.");
} |
python | def set_ethercat(interface, master_id):
'''
Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't
already use EtherCAT adapter mode, otherwise will return true.
:param interface: interface label
:param master_id: EtherCAT Master ID
:return: True if the settings were applied, otherwise an exception will be thrown.
CLI Example:
.. code-block:: bash
salt '*' ip.set_ethercat interface-label master-id
'''
if __grains__['lsb_distrib_id'] == 'nilrt':
initial_mode = _get_adapter_mode_info(interface)
_save_config(interface, 'Mode', NIRTCFG_ETHERCAT)
_save_config(interface, 'MasterID', master_id)
if initial_mode != 'ethercat':
__salt__['system.set_reboot_required_witnessed']()
return True
raise salt.exceptions.CommandExecutionError('EtherCAT is not supported') |
python | async def vcx_agent_provision(config: str) -> None:
"""
Provision an agent in the agency, populate configuration and wallet for this agent.
Example:
import json
enterprise_config = {
'agency_url': 'http://localhost:8080',
'agency_did': 'VsKV7grR1BUE29mG2Fm2kX',
'agency_verkey': "Hezce2UWMZ3wUhVkh2LfKSs8nDzWwzs2Win7EzNN3YaR",
'wallet_name': 'LIBVCX_SDK_WALLET',
'agent_seed': '00000000000000000000000001234561',
'enterprise_seed': '000000000000000000000000Trustee1',
'wallet_key': '1234'
}
vcx_config = await vcx_agent_provision(json.dumps(enterprise_config))
:param config: JSON configuration
:return: Configuration for vcx_init call.
"""
logger = logging.getLogger(__name__)
if not hasattr(vcx_agent_provision, "cb"):
logger.debug("vcx_agent_provision: Creating callback")
vcx_agent_provision.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, c_char_p))
c_config = c_char_p(config.encode('utf-8'))
result = await do_call('vcx_agent_provision_async',
c_config,
vcx_agent_provision.cb)
logger.debug("vcx_agent_provision completed")
return result.decode() |
python | def Hooper2K(Di, Re, name=None, K1=None, Kinfty=None):
r'''Returns loss coefficient for any various fittings, depending
on the name input. Alternatively, the Hooper constants K1, Kinfty
may be provided and used instead. Source of data is [1]_.
Reviews of this model are favorable less favorable than the Darby method
but superior to the constant-K method.
.. math::
K = \frac{K_1}{Re} + K_\infty\left(1 + \frac{1\text{ inch}}{D_{in}}\right)
Note this model uses actual inside pipe diameter in inches.
Parameters
----------
Di : float
Actual inside diameter of the pipe, [in]
Re : float
Reynolds number, [-]
name : str, optional
String from Hooper dict representing a fitting
K1 : float, optional
K1 parameter of Hooper model, optional [-]
Kinfty : float, optional
Kinfty parameter of Hooper model, optional [-]
Returns
-------
K : float
Loss coefficient [-]
Notes
-----
Also described in Ludwig's Applied Process Design.
Relatively uncommon to see it used.
No actual example found.
Examples
--------
>>> Hooper2K(Di=2., Re=10000., name='Valve, Globe, Standard')
6.15
>>> Hooper2K(Di=2., Re=10000., K1=900, Kinfty=4)
6.09
References
----------
.. [1] Hooper, W. B., "The 2-K Method Predicts Head Losses in Pipe
Fittings," Chem. Eng., p. 97, Aug. 24 (1981).
.. [2] Hooper, William B. "Calculate Head Loss Caused by Change in Pipe
Size." Chemical Engineering 95, no. 16 (November 7, 1988): 89.
.. [3] Kayode Coker. Ludwig's Applied Process Design for Chemical and
Petrochemical Plants. 4E. Amsterdam ; Boston: Gulf Professional
Publishing, 2007.
'''
if name:
if name in Hooper:
d = Hooper[name]
K1, Kinfty = d['K1'], d['Kinfty']
else:
raise Exception('Name of fitting not in list')
elif K1 and Kinfty:
pass
else:
raise Exception('Name of fitting or constants are required')
return K1/Re + Kinfty*(1. + 1./Di) |
python | def click_action(self):
"""|ActionSetting| instance providing access to click behaviors.
Click behaviors are hyperlink-like behaviors including jumping to
a hyperlink (web page) or to another slide in the presentation. The
click action is that defined on the overall shape, not a run of text
within the shape. An |ActionSetting| object is always returned, even
when no click behavior is defined on the shape.
"""
cNvPr = self._element._nvXxPr.cNvPr
return ActionSetting(cNvPr, self) |
java | public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ,
float centerX, float centerY, float centerZ,
float upX, float upY, float upZ, Matrix4f dest) {
if ((properties & PROPERTY_IDENTITY) != 0)
return dest.setLookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ);
else if ((properties & PROPERTY_PERSPECTIVE) != 0)
return lookAtPerspectiveLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest);
return lookAtLHGeneric(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest);
} |
java | public CommandLine parse(Options options, String[] arguments, Properties properties, boolean stopAtNonOption)
throws ParseException
{
this.options = options;
this.stopAtNonOption = stopAtNonOption;
skipParsing = false;
currentOption = null;
expectedOpts = new ArrayList(options.getRequiredOptions());
// clear the data from the groups
for (OptionGroup group : options.getOptionGroups())
{
group.setSelected(null);
}
cmd = new CommandLine();
if (arguments != null)
{
for (String argument : arguments)
{
handleToken(argument);
}
}
// check the arguments of the last option
checkRequiredArgs();
// add the default options
handleProperties(properties);
checkRequiredOptions();
return cmd;
} |
java | @Override
public void close(final URI uri, final ClassLoader classLoader) {
if (uri == null || classLoader == null) {
throw new NullPointerException();
}
synchronized (cacheManagers) {
final ConcurrentMap<URI, Eh107CacheManager> map = cacheManagers.get(classLoader);
if (map != null) {
final Eh107CacheManager cacheManager = map.remove(uri);
if (cacheManager != null) {
cacheManager.closeInternal();
}
}
}
} |
python | def getColumnsByName(elem, name):
"""
Return a list of Column elements named name under elem. The name
comparison is done with CompareColumnNames().
"""
name = StripColumnName(name)
return elem.getElements(lambda e: (e.tagName == ligolw.Column.tagName) and (e.Name == name)) |
java | protected final BufferedImage create_LED_Image(final int SIZE, final int STATE, final LedColor LED_COLOR) {
return LED_FACTORY.create_LED_Image(SIZE, STATE, LED_COLOR, model.getCustomLedColor());
} |
python | def create(self, unique_name, friendly_name=values.unset, actions=values.unset,
actions_url=values.unset):
"""
Create a new TaskInstance
:param unicode unique_name: An application-defined string that uniquely identifies the resource
:param unicode friendly_name: descriptive string that you create to describe the new resource
:param dict actions: The JSON string that specifies the actions that instruct the Assistant on how to perform the task
:param unicode actions_url: The URL from which the Assistant can fetch actions
:returns: Newly created TaskInstance
:rtype: twilio.rest.autopilot.v1.assistant.task.TaskInstance
"""
data = values.of({
'UniqueName': unique_name,
'FriendlyName': friendly_name,
'Actions': serialize.object(actions),
'ActionsUrl': actions_url,
})
payload = self._version.create(
'POST',
self._uri,
data=data,
)
return TaskInstance(self._version, payload, assistant_sid=self._solution['assistant_sid'], ) |
python | def _transform_data(self, X):
"""Binarize the data for each column separately."""
if self._binarizers == []:
raise NotFittedError()
if self.binarize is not None:
X = binarize(X, threshold=self.binarize)
if len(self._binarizers) != X.shape[1]:
raise ValueError(
"Expected input with %d features, got %d instead" %
(len(self._binarizers), X.shape[1]))
X_parts = []
for i in range(X.shape[1]):
X_i = self._binarizers[i].transform(X[:, i])
# sklearn returns ndarray with shape (samples, 1) on binary input.
if self._binarizers[i].classes_.shape[0] == 2:
X_parts.append(1 - X_i)
X_parts.append(X_i)
return np.concatenate(X_parts, axis=1) |
python | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(SidekiqCollector, self).get_default_config()
config.update({
'path': 'sidekiq',
'host': 'localhost',
'ports': '6379',
'password': None,
'databases': 16,
'sentinel_ports': None,
'sentinel_name': None,
'cluster_prefix': None
})
return config |
java | public com.google.api.ads.adwords.axis.v201809.cm.ConversionOptimizerEligibility getConversionOptimizerEligibility() {
return conversionOptimizerEligibility;
} |
java | public String getParameterName(Parameter parameter) {
Name annotation = parameter.getAnnotation(Name.class);
if (null == annotation) {
return parameter.getName();
}
return annotation.value();
} |
java | private boolean topicImplicity(final String topic, final String[] splitTopic) {
try {
return topicMatcher.matches(stripedTopic, this.splitTopic, nonWildCard, endsWithWildCard, rootWildCard, topic, splitTopic);
} catch (InvalidTopicException e) {
return false;
}
} |
python | def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
conf,
nesting_key=None):
'''
Get pillar data from Vault for the configuration ``conf``.
'''
comps = conf.split()
paths = [comp for comp in comps if comp.startswith('path=')]
if not paths:
log.error('"%s" is not a valid Vault ext_pillar config', conf)
return {}
vault_pillar = {}
try:
path = paths[0].replace('path=', '')
path = path.format(**{'minion': minion_id})
url = 'v1/{0}'.format(path)
response = __utils__['vault.make_request']('GET', url)
if response.status_code == 200:
vault_pillar = response.json().get('data', {})
else:
log.info('Vault secret not found for: %s', path)
except KeyError:
log.error('No such path in Vault: %s', path)
if nesting_key:
vault_pillar = {nesting_key: vault_pillar}
return vault_pillar |
python | def serialize(self, config):
"""
:param config:
:type config: yowsup.config.base.config.Config
:return:
:rtype: bytes
"""
for transform in self._transforms:
config = transform.transform(config)
return config |
java | public SerializationObject getSerializationObject() {
SerializationObject object;
synchronized (ivListOfObjects) {
if (ivListOfObjects.isEmpty()) {
object = createNewObject();
} else {
object = ivListOfObjects.remove(ivListOfObjects.size() - 1);
}
}
return object;
} |
java | public int read() throws IOException {
int c;
if (mFirst != 0) {
c = mFirst;
mFirst = 0;
}
else {
c = super.read();
}
if (c == '\n') {
mLine++;
}
else if (c == ENTER_CODE) {
mUnicodeReader.setEscapesEnabled(true);
}
else if (c == ENTER_TEXT) {
mUnicodeReader.setEscapesEnabled(false);
}
return c;
} |
java | @NotNull
public static String getStoreSku(@NotNull final String appStoreName, @NotNull String sku) {
return SkuManager.getInstance().getStoreSku(appStoreName, sku);
} |
python | def _get_argument(self, argument_node):
"""
Returns a FritzActionArgument instance for the given argument_node.
"""
argument = FritzActionArgument()
argument.name = argument_node.find(self.nodename('name')).text
argument.direction = argument_node.find(self.nodename('direction')).text
rsv = argument_node.find(self.nodename('relatedStateVariable')).text
# TODO: track malformed xml-nodes (i.e. misspelled)
argument.data_type = self.state_variables.get(rsv, None)
return argument |
java | public static void readable(final String path, final String message) throws IllegalArgumentException {
notNullOrEmpty(path, message);
readable(new File(path), message);
} |
java | public ResourcePendingMaintenanceActions withPendingMaintenanceActionDetails(PendingMaintenanceAction... pendingMaintenanceActionDetails) {
if (this.pendingMaintenanceActionDetails == null) {
setPendingMaintenanceActionDetails(new com.amazonaws.internal.SdkInternalList<PendingMaintenanceAction>(pendingMaintenanceActionDetails.length));
}
for (PendingMaintenanceAction ele : pendingMaintenanceActionDetails) {
this.pendingMaintenanceActionDetails.add(ele);
}
return this;
} |
java | public static void main(String[] args) throws FileNotFoundException, IOException {
InputStream codeStream = FeatureCodeBuilder.class.getClassLoader().getResourceAsStream("featureCodes_en.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(codeStream, Charset.forName("UTF-8")));
// generate dummy feature code for top-level territories
Set<Code> featureCodes = new TreeSet<Code>();
featureCodes.add(new Code("TERRI", "A", "independent territory", "a territory that acts as an independent political entity",
"manually added to identify territories that can contain other administrative divisions"));
String line;
while ((line = in.readLine()) != null) {
String[] tokens = line.split("\t");
if (!tokens[0].equals("null")) {
String[] codes = tokens[0].split("\\.");
featureCodes.add(new Code(codes[1], codes[0], tokens[1], tokens.length == 3 ? tokens[2] : ""));
}
}
in.close();
for (Code code : featureCodes) {
System.out.println(code);
}
System.out.println("// manually added for locations not assigned to a feature code");
System.out.println("NULL(FeatureClass.NULL, \"not available\", \"\", false);");
} |
java | private int[] map(int u, int v, int[] us, int[] mapping) {
for (int i = 0; i < us.length; i++)
us[i] = mapping[us[i]];
return us;
} |
java | protected void addDescription(PackageDoc pkg, Content dlTree, SearchIndexItem si) {
Content link = getPackageLink(pkg, new StringContent(utils.getPackageName(pkg)));
si.setLabel(utils.getPackageName(pkg));
si.setCategory(getResource("doclet.Packages").toString());
Content dt = HtmlTree.DT(link);
dt.addContent(" - ");
dt.addContent(getResource("doclet.package"));
dt.addContent(" " + pkg.name());
dlTree.addContent(dt);
Content dd = new HtmlTree(HtmlTag.DD);
addSummaryComment(pkg, dd);
dlTree.addContent(dd);
} |
java | public static <T> T objectFromClause(Class<T> type, String clause, Object... args)
{
return SqlClosure.sqlExecute(c -> OrmElf.objectFromClause(c, type, clause, args));
} |
java | @BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
public final OperationFuture<Instruction, CreateInstructionMetadata> createInstructionAsync(
CreateInstructionRequest request) {
return createInstructionOperationCallable().futureCall(request);
} |
python | def _ModifiedDecoder(wire_type, decode_value, modify_value):
"""Like SimpleDecoder but additionally invokes modify_value on every value
before storing it. Usually modify_value is ZigZagDecode.
"""
# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but
# not enough to make a significant difference.
def InnerDecode(buffer, pos):
(result, new_pos) = decode_value(buffer, pos)
return (modify_value(result), new_pos)
return _SimpleDecoder(wire_type, InnerDecode) |
python | def _get_batch_name(sample):
"""Retrieve batch name for use in SV calling outputs.
Handles multiple batches split via SV calling.
"""
batch = dd.get_batch(sample) or dd.get_sample_name(sample)
if isinstance(batch, (list, tuple)) and len(batch) > 1:
batch = dd.get_sample_name(sample)
return batch |
java | public boolean hasNext()
{
if (tc.isEntryEnabled()) SibTr.entry(this, tc, "hasNext");
if (tc.isEntryEnabled()) SibTr.exit(this, tc, "hasNext", ""+transmissionsRemaining);
return transmissionsRemaining;
} |
python | def thread_safe_client(client, lock=None):
"""Create a thread-safe proxy which locks every method call
for the given client.
Args:
client: the client object to be guarded.
lock: the lock object that will be used to lock client's methods.
If None, a new lock will be used.
Returns:
A thread-safe proxy for the given client.
"""
if lock is None:
lock = threading.Lock()
return _ThreadSafeProxy(client, lock) |
java | public static int getDefaultFlags ( CIFSContext tc ) {
return NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_VERSION
| ( tc.getConfig().isUseUnicode() ? NTLMSSP_NEGOTIATE_UNICODE : NTLMSSP_NEGOTIATE_OEM );
} |
python | def cube2matrix(data_cube):
r"""Cube to Matrix
This method transforms a 3D cube to a 2D matrix
Parameters
----------
data_cube : np.ndarray
Input data cube, 3D array
Returns
-------
np.ndarray 2D matrix
Examples
--------
>>> from modopt.base.transform import cube2matrix
>>> a = np.arange(16).reshape((4, 2, 2))
>>> cube2matrix(a)
array([[ 0, 4, 8, 12],
[ 1, 5, 9, 13],
[ 2, 6, 10, 14],
[ 3, 7, 11, 15]])
"""
return data_cube.reshape([data_cube.shape[0]] +
[np.prod(data_cube.shape[1:])]).T |
java | public static TypeAnnotationPosition
resourceVariable(final List<TypePathEntry> location,
final JCLambda onLambda,
final int pos) {
return new TypeAnnotationPosition(TargetType.RESOURCE_VARIABLE, pos,
Integer.MIN_VALUE, onLambda,
Integer.MIN_VALUE, Integer.MIN_VALUE,
location);
} |
python | def get_session_data( username, password_verifier, salt, client_public, private, preset):
"""Print out server session data."""
session = SRPServerSession(
SRPContext(username, prime=preset[0], generator=preset[1]),
hex_from_b64(password_verifier), private=private)
session.process(client_public, salt, base64=True)
click.secho('Server session key: %s' % session.key_b64)
click.secho('Server session key proof: %s' % session.key_proof_b64)
click.secho('Server session key hash: %s' % session.key_proof_hash_b64) |
java | @Override
public void correctDataTypes(DAO[] daoList, ModelDef model) {
for(DAO dao : daoList){
correctDataTypes(dao, model);
}
} |
python | def _set_dac_value(self, channel, value):
'''Write DAC
'''
# DAC value cannot be -128
if value == -128:
value = -127
if value < 0:
sign = 1
else:
sign = 0
value = (sign << 7) | (0x7F & abs(value))
self._intf.write(self._base_addr + self.DS_4424_ADD, array('B', pack('BB', channel, value))) |
java | @Override
public Object processResponse(Object rawResponse) throws ServiceException {
PipelineHelpers.throwIfNotSuccess((ClientResponse) rawResponse);
return rawResponse;
} |
python | def run_script(pycode):
"""Run the Python in `pycode`, and return a dict of the resulting globals."""
# Fix up the whitespace in pycode.
if pycode[0] == "\n":
pycode = pycode[1:]
pycode.rstrip()
pycode = textwrap.dedent(pycode)
# execute it.
globs = {}
six.exec_(pycode, globs, globs) # pylint: disable=W0122
return globs |
python | def get(self, copy=False):
"""Return the value of the attribute"""
array = getattr(self.owner, self.name)
if copy:
return array.copy()
else:
return array |
java | public static void leaveSafeBlock()
{
if (!inSafe) {
return;
}
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glPopMatrix();
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glPopMatrix();
GL11.glPopClientAttrib();
GL11.glPopAttrib();
if (lastUsed != null) {
lastUsed.bind();
} else {
TextureImpl.bindNone();
}
inSafe = false;
} |
java | private void runFileFormatValidation() throws IOException {
Preconditions.checkArgument(this.props.containsKey(VALIDATION_FILE_FORMAT_KEY));
this.configStoreUri =
StringUtils.isNotBlank(this.props.getProperty(ConfigurationKeys.CONFIG_MANAGEMENT_STORE_URI)) ? Optional.of(
this.props.getProperty(ConfigurationKeys.CONFIG_MANAGEMENT_STORE_URI)) : Optional.<String>absent();
if (!Boolean.valueOf(this.props.getProperty(ConfigurationKeys.CONFIG_MANAGEMENT_STORE_ENABLED,
ConfigurationKeys.DEFAULT_CONFIG_MANAGEMENT_STORE_ENABLED))) {
this.configStoreUri = Optional.<String>absent();
}
List<Partition> partitions = new ArrayList<>();
if (this.configStoreUri.isPresent()) {
Preconditions.checkArgument(this.props.containsKey(GOBBLIN_CONFIG_TAGS_WHITELIST),
"Missing required property " + GOBBLIN_CONFIG_TAGS_WHITELIST);
String tag = this.props.getProperty(GOBBLIN_CONFIG_TAGS_WHITELIST);
ConfigClient configClient = ConfigClient.createConfigClient(VersionStabilityPolicy.WEAK_LOCAL_STABILITY);
Path tagUri = PathUtils.mergePaths(new Path(this.configStoreUri.get()), new Path(tag));
try (AutoReturnableObject<IMetaStoreClient> client = pool.getClient()) {
Collection<URI> importedBy = configClient.getImportedBy(new URI(tagUri.toString()), true);
for (URI uri : importedBy) {
String dbName = new Path(uri).getParent().getName();
Table table = new Table(client.get().getTable(dbName, new Path(uri).getName()));
for (org.apache.hadoop.hive.metastore.api.Partition partition : client.get()
.listPartitions(dbName, table.getTableName(), maxParts)) {
partitions.add(new Partition(table, partition));
}
}
} catch (Exception e) {
this.throwables.add(e);
}
}
for (Partition partition : partitions) {
if (!shouldValidate(partition)) {
continue;
}
String fileFormat = this.props.getProperty(VALIDATION_FILE_FORMAT_KEY);
Optional<HiveSerDeWrapper.BuiltInHiveSerDe> hiveSerDe =
Enums.getIfPresent(HiveSerDeWrapper.BuiltInHiveSerDe.class, fileFormat.toUpperCase());
if (!hiveSerDe.isPresent()) {
throwables.add(new Throwable("Partition SerDe is either not supported or absent"));
continue;
}
String serdeLib = partition.getTPartition().getSd().getSerdeInfo().getSerializationLib();
if (!hiveSerDe.get().toString().equalsIgnoreCase(serdeLib)) {
throwables.add(new Throwable("Partition " + partition.getCompleteName() + " SerDe " + serdeLib
+ " doesn't match with the required SerDe " + hiveSerDe.get().toString()));
}
}
if (!this.throwables.isEmpty()) {
for (Throwable e : this.throwables) {
log.error("Failed to validate due to " + e);
}
throw new RuntimeException("Validation Job Failed");
}
} |
java | protected ModificationHistory getModificationHistory(Type type) {
ModificationHistory history = new ModificationHistory();
ClassDoc classDoc = this.wrDoc.getConfiguration().root.classNamed(type.qualifiedTypeName());
if (classDoc != null) {
LinkedList<ModificationRecord> list = this.getModificationRecords(classDoc);
history.addModificationRecords(list);
}
return history;
} |
python | def toggle_concatenate(self):
"""Enable and disable concatenation options."""
if not (self.chunk['epoch'].isChecked() and
self.lock_to_staging.get_value()):
for i,j in zip([self.idx_chan, self.idx_cycle, self.idx_stage,
self.idx_evt_type],
[self.cat['chan'], self.cat['cycle'],
self.cat['stage'], self.cat['evt_type']]):
if len(i.selectedItems()) > 1:
j.setEnabled(True)
else:
j.setEnabled(False)
j.setChecked(False)
if not self.chunk['event'].isChecked():
self.cat['evt_type'].setEnabled(False)
if not self.cat['discontinuous'].get_value():
self.cat['chan'].setEnabled(False)
self.cat['chan'].setChecked(False)
self.update_nseg() |
python | def dInd_calc(TNR, TPR):
"""
Calculate dInd (Distance index).
:param TNR: specificity or true negative rate
:type TNR : float
:param TPR: sensitivity, recall, hit rate, or true positive rate
:type TPR : float
:return: dInd as float
"""
try:
result = math.sqrt(((1 - TNR)**2) + ((1 - TPR)**2))
return result
except Exception:
return "None" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.