language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | protected void saveInternal(XMLStreamWriter stream) throws XMLStreamException {
if (namespace != null) {
stream.writeStartElement(prefix, namespace, name);
} else {
stream.writeStartElement(name);
}
for (Map.Entry<XAttributeName, String> a : attributes.entrySet()) {
XAttributeName an = a.getKey();
if (an.namespace != null) {
stream.writeAttribute(an.prefix, an.namespace, an.name, a.getValue());
} else {
stream.writeAttribute(an.name, a.getValue());
}
}
if (content != null) {
stream.writeCharacters(content);
} else {
for (XNElement e : children) {
e.saveInternal(stream);
}
}
stream.writeEndElement();
} |
java | public VariableRef[] getOutOfScopeVariableRefs() {
Scope parent;
if ((parent = getParent()) == null) {
return new VariableRef[0];
}
Collection<VariableRef> allRefs = new ArrayList<VariableRef>();
fillVariableRefs(allRefs, this);
Collection<VariableRef> refs =
new ArrayList<VariableRef>(allRefs.size());
Iterator<VariableRef> it = allRefs.iterator();
while (it.hasNext()) {
VariableRef ref = it.next();
Variable var = ref.getVariable();
if (var != null &&
parent.getDeclaredVariable(var.getName()) == var) {
refs.add(ref);
}
}
VariableRef[] refsArray = new VariableRef[refs.size()];
return refs.toArray(refsArray);
} |
python | def pop(self, identifier, default=None):
"""Pop a node of the AttrTree using its path string.
Args:
identifier: Path string of the node to return
default: Value to return if no node is found
Returns:
The node that was removed from the AttrTree
"""
if identifier in self.children:
item = self[identifier]
self.__delitem__(identifier)
return item
else:
return default |
java | @Nonnull
public PLTableRow addAndReturnRow (@Nonnull final Iterable <? extends PLTableCell> aCells)
{
return addAndReturnRow (aCells, m_aRows.getDefaultHeight ());
} |
java | public final void mapEntry() throws RecognitionException {
try {
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:574:5: ( expression COLON expression )
// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:574:7: expression COLON expression
{
pushFollow(FOLLOW_expression_in_mapEntry3175);
expression();
state._fsp--;
if (state.failed) return;
match(input,COLON,FOLLOW_COLON_in_mapEntry3177); if (state.failed) return;
pushFollow(FOLLOW_expression_in_mapEntry3179);
expression();
state._fsp--;
if (state.failed) return;
}
}
catch (RecognitionException re) {
throw re;
}
finally {
// do for sure before leaving
}
} |
python | def decode_pubkey_hex(pubkey_hex):
"""
Decode a public key for ecdsa verification
"""
if not isinstance(pubkey_hex, (str, unicode)):
raise ValueError("public key is not a string")
pubk = keylib.key_formatting.decompress(str(pubkey_hex))
assert len(pubk) == 130
pubk_raw = pubk[2:]
pubk_i = (int(pubk_raw[:64], 16), int(pubk_raw[64:], 16))
return pubk_i |
java | void optimizeTransitions()
{
HashMap<DFAState<T>,RangeSet> hml = new HashMap<>();
for (Transition<DFAState<T>> t : transitions.values())
{
RangeSet rs = hml.get(t.getTo());
if (rs == null)
{
rs = new RangeSet();
hml.put(t.getTo(), rs);
}
rs.add(t.getCondition());
}
transitions.clear();
for (DFAState<T> dfa : hml.keySet())
{
RangeSet rs = RangeSet.merge(hml.get(dfa));
for (CharRange r : rs)
{
addTransition(r, dfa);
}
}
} |
python | def apply_and_save(self):
"""Apply replaced words and patches, and save setup.py file."""
patches = self.patches
content = None
with open(self.IN_PATH) as f_in:
# As setup.py.in file size is 2.4 KByte.
# it's fine to read entire content.
content = f_in.read()
# Replace words.
for key in self.replaced_word_dict:
content = content.replace(key, self.replaced_word_dict[key])
# Apply patches.
out_patches = []
for patch in patches:
pattern = re.compile(patch['src'], re.MULTILINE)
(content, subs_num) = re.subn(pattern, patch['dest'],
content)
if subs_num > 0:
patch['applied'] = True
out_patches.append(patch)
for patch in out_patches:
if patch.get('required') and not patch.get('applied'):
Log.warn('Patch not applied {0}'.format(patch['src']))
with open(self.OUT_PATH, 'w') as f_out:
f_out.write(content)
self.pathces = out_patches
# Release content data to make it released by GC quickly.
content = None |
python | def add_default_args(parser, version=None, include=None):
'''
Add default arguments to a parser. These are:
- config: argument for specifying a configuration file.
- user: argument for specifying a user.
- dry-run: option for running without side effects.
- verbose: option for running verbosely.
- quiet: option for running quietly.
- version: option for spitting out version information.
Args:
version (str): version to return on <cli> --version
include (Sequence): default arguments to add to cli. Default: (config, user, dry-run, verbose, quiet)
'''
include = include or ('config', 'user', 'dry-run', 'verbose', 'quiet')
if 'config' in include:
parser.add_argument('-c', '--config', dest='config_file', metavar='PATH', default=None,
type=str, help='bots config file (json or yaml)')
if 'user' in include:
parser.add_argument('-u', '--user', dest='screen_name', type=str, help="Twitter screen name")
if 'dry-run' in include:
parser.add_argument('-n', '--dry-run', action='store_true', help="Don't actually do anything")
if 'verbose' in include:
parser.add_argument('-v', '--verbose', action='store_true', help="Run talkatively")
if 'quiet' in include:
parser.add_argument('-q', '--quiet', action='store_true', help="Run quietly")
if version:
parser.add_argument('-V', '--version', action='version', version="%(prog)s " + version) |
java | public Node clearAttributes() {
Iterator<Attribute> it = attributes().iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
return this;
} |
java | public void setNoteText(java.util.Collection<StringFilter> noteText) {
if (noteText == null) {
this.noteText = null;
return;
}
this.noteText = new java.util.ArrayList<StringFilter>(noteText);
} |
python | def parse_pictures(self, picture_page):
"""Parses the DOM and returns character pictures attributes.
:type picture_page: :class:`bs4.BeautifulSoup`
:param picture_page: MAL character pictures page's DOM
:rtype: dict
:return: character pictures attributes.
"""
character_info = self.parse_sidebar(picture_page)
second_col = picture_page.find(u'div', {'id': 'content'}).find(u'table').find(u'tr').find_all(u'td', recursive=False)[1]
try:
picture_table = second_col.find(u'table', recursive=False)
character_info[u'pictures'] = []
if picture_table:
character_info[u'pictures'] = map(lambda img: img.get(u'src').decode('utf-8'), picture_table.find_all(u'img'))
except:
if not self.session.suppress_parse_exceptions:
raise
return character_info |
java | private void addSmallIcon(RemoteViews notificationView) {
notificationView.setInt(R.id.simple_sound_cloud_notification_icon,
"setBackgroundResource", mNotificationConfig.getNotificationIconBackground());
notificationView.setImageViewResource(R.id.simple_sound_cloud_notification_icon,
mNotificationConfig.getNotificationIcon());
} |
python | def _read_temp(data):
'''
Return what would be written to disk
'''
tout = StringIO()
tout.write(data)
tout.seek(0)
output = tout.readlines()
tout.close()
return output |
python | def ParseFileEntryMetadata(self, parser_mediator, file_entry):
"""Parses the file entry metadata e.g. file system data.
Args:
parser_mediator (ParserMediator): parser mediator.
file_entry (dfvfs.FileEntry): file entry.
"""
if self._filestat_parser:
self._ParseFileEntryWithParser(
parser_mediator, self._filestat_parser, file_entry) |
java | private List<String> parseEnumData(File annotationCacheCopy,
String valueDelimiter, long characterOffset)
throws IOException {
List<String> enumData = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(annotationCacheCopy));
reader.skip(characterOffset);
String line = "";
while ((line = reader.readLine()) != null) {
String[] lineTokens = StringUtils.splitByWholeSeparator(line,
valueDelimiter);
if (lineTokens != null && lineTokens.length >= 1) {
enumData.add(lineTokens[0]);
}
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {}
}
}
return enumData;
} |
python | def feature_importance(self, importance_type='split', iteration=None):
"""Get feature importances.
Parameters
----------
importance_type : string, optional (default="split")
How the importance is calculated.
If "split", result contains numbers of times the feature is used in a model.
If "gain", result contains total gains of splits which use the feature.
iteration : int or None, optional (default=None)
Limit number of iterations in the feature importance calculation.
If None, if the best iteration exists, it is used; otherwise, all trees are used.
If <= 0, all trees are used (no limits).
Returns
-------
result : numpy array
Array with feature importances.
"""
if iteration is None:
iteration = self.best_iteration
if importance_type == "split":
importance_type_int = 0
elif importance_type == "gain":
importance_type_int = 1
else:
importance_type_int = -1
result = np.zeros(self.num_feature(), dtype=np.float64)
_safe_call(_LIB.LGBM_BoosterFeatureImportance(
self.handle,
ctypes.c_int(iteration),
ctypes.c_int(importance_type_int),
result.ctypes.data_as(ctypes.POINTER(ctypes.c_double))))
if importance_type_int == 0:
return result.astype(int)
else:
return result |
java | public boolean destroyDependentInstance(T instance) {
synchronized (dependentInstances) {
for (Iterator<ContextualInstance<?>> iterator = dependentInstances.iterator(); iterator.hasNext();) {
ContextualInstance<?> contextualInstance = iterator.next();
if (contextualInstance.getInstance() == instance) {
iterator.remove();
destroy(contextualInstance);
return true;
}
}
}
return false;
} |
python | def _teardown_log_prefix(self):
"""Tear down custom warning notification."""
self._logger_console_fmtter.prefix = ''
self._logger_console_fmtter.plugin_id = ''
self._logger_file_fmtter.prefix = ' '
self._logger_file_fmtter.plugin_id = '' |
python | def list_connected_devices(self, **kwargs):
"""List connected devices.
Example usage, listing all registered devices in the catalog:
.. code-block:: python
filters = {
'created_at': {'$gte': datetime.datetime(2017,01,01),
'$lte': datetime.datetime(2017,12,31)
}
}
devices = api.list_connected_devices(order='asc', filters=filters)
for idx, device in enumerate(devices):
print(device)
## Other example filters
# Directly connected devices (not via gateways):
filters = {
'host_gateway': {'$eq': ''},
'device_type': {'$eq': ''}
}
# Devices connected via gateways:
filters = {
'host_gateway': {'$neq': ''}
}
# Gateway devices:
filters = {
'device_type': {'$eq': 'MBED_GW'}
}
:param int limit: The number of devices to retrieve.
:param str order: The ordering direction, ascending (asc) or
descending (desc)
:param str after: Get devices after/starting at given `device_id`
:param filters: Dictionary of filters to apply.
:returns: a list of connected :py:class:`Device` objects.
:rtype: PaginatedResponse
"""
# TODO(pick one of these)
filter_or_filters = 'filter' if 'filter' in kwargs else 'filters'
kwargs.setdefault(filter_or_filters, {}).setdefault('state', {'$eq': 'registered'})
kwargs = self._verify_sort_options(kwargs)
kwargs = self._verify_filters(kwargs, Device, True)
api = self._get_api(device_directory.DefaultApi)
return PaginatedResponse(api.device_list, lwrap_type=Device, **kwargs) |
java | private void logOutOfMemoryError()
{
logger.error("Dump some crucial information below:\n" +
"Total milliseconds waiting for chunks: {},\n" +
"Total memory used: {}, Max heap size: {}, total download time: {} millisec,\n" +
"total parsing time: {} milliseconds, total chunks: {},\n" +
"currentMemoryUsage in Byte: {}, currentMemoryLimit in Bytes: {} \n" +
"nextChunkToDownload: {}, nextChunkToConsume: {}\n" +
"Several suggestions to try to resolve the OOM issue:\n" +
"1. increase the JVM heap size if you have more space; or \n" +
"2. use CLIENT_MEMORY_LIMIT to reduce the memory usage by the JDBC driver " +
"(https://docs.snowflake.net/manuals/sql-reference/parameters.html#client-memory-limit)" +
"3. please make sure 2 * CLIENT_PREFETCH_THREADS * CLIENT_RESULT_CHUNK_SIZE < CLIENT_MEMORY_LIMIT. " +
"If not, please reduce CLIENT_PREFETCH_THREADS and CLIENT_RESULT_CHUNK_SIZE too.",
numberMillisWaitingForChunks,
Runtime.getRuntime().totalMemory(), Runtime.getRuntime().maxMemory(),
totalMillisDownloadingChunks.get(),
totalMillisParsingChunks.get(), chunks.size(), currentMemoryUsage, memoryLimit,
nextChunkToDownload, nextChunkToConsume);
} |
java | public LineStringExpression<LineString> interiorRingN(int idx) {
return GeometryExpressions.lineStringOperation(SpatialOps.INTERIOR_RINGN, mixin, ConstantImpl.create(idx));
} |
java | public void setCaptionDescriptions(java.util.Collection<CaptionDescriptionPreset> captionDescriptions) {
if (captionDescriptions == null) {
this.captionDescriptions = null;
return;
}
this.captionDescriptions = new java.util.ArrayList<CaptionDescriptionPreset>(captionDescriptions);
} |
java | public ExpressRouteCircuitsRoutesTableListResultInner beginListRoutesTable(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) {
return beginListRoutesTableWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).toBlocking().single().body();
} |
java | private void doConnect() {
try {
LOG.info("Connecting to zookeeper server - " + RpcClientConf.ZK_SERVER_LIST);
zkClient = new SimpleZooKeeperClient(RpcClientConf.ZK_SERVER_LIST,
RpcClientConf.ZK_DIGEST_AUTH, new ServiceWatcher());
updateServiceLocalCache();
} catch (Exception e) {
LOG.error("Zookeeper client initialization failed, " + e.getMessage(), e);
}
} |
python | def patch_celery():
""" Monkey patch Celery to use cloudpickle instead of pickle. """
registry = serialization.registry
serialization.pickle = cloudpickle
registry.unregister('pickle')
registry.register('pickle', cloudpickle_dumps, cloudpickle_loads,
content_type='application/x-python-serialize',
content_encoding='binary')
import celery.worker as worker
import celery.concurrency.asynpool as asynpool
worker.state.pickle = cloudpickle
asynpool._pickle = cloudpickle
import billiard.common
billiard.common.pickle = cloudpickle
billiard.common.pickle_dumps = cloudpickle_dumps
billiard.common.pickle_loads = cloudpickle_loads |
java | public static void tint(View view, Tint tint) {
final ColorStateList color = tint.getColor(view.getContext());
if (view instanceof ImageView) {
tint(((ImageView) view).getDrawable(), color);
} else if (view instanceof TextView) {
TextView text = (TextView) view;
Drawable[] comp = text.getCompoundDrawables();
for (int i = 0; i < comp.length; i++) {
if (comp[i] != null) {
comp[i] = tint(comp[i], color);
}
}
text.setCompoundDrawablesWithIntrinsicBounds(comp[0], comp[1], comp[2], comp[3]);
} else {
throw new IllegalArgumentException("Unsupported view type");
}
} |
python | def _sequence(self, i):
"""Handle character group."""
result = ['[']
end_range = 0
escape_hyphen = -1
removed = False
last_posix = False
c = next(i)
if c in ('!', '^'):
# Handle negate char
result.append('^')
c = next(i)
if c == '[':
last_posix = self._handle_posix(i, result, 0)
if not last_posix:
result.append(re.escape(c))
c = next(i)
elif c in ('-', ']'):
result.append(re.escape(c))
c = next(i)
while c != ']':
if c == '-':
if last_posix:
result.append('\\' + c)
last_posix = False
elif i.index - 1 > escape_hyphen:
# Found a range delimiter.
# Mark the next two characters as needing to be escaped if hyphens.
# The next character would be the end char range (s-e),
# and the one after that would be the potential start char range
# of a new range (s-es-e), so neither can be legitimate range delimiters.
result.append(c)
escape_hyphen = i.index + 1
end_range = i.index
elif end_range and i.index - 1 >= end_range:
if self._sequence_range_check(result, '\\' + c):
removed = True
end_range = 0
else:
result.append('\\' + c)
c = next(i)
continue
last_posix = False
if c == '[':
last_posix = self._handle_posix(i, result, end_range)
if last_posix:
c = next(i)
continue
if c == '\\':
# Handle escapes
subindex = i.index
try:
value = self._references(i, True)
except PathNameException:
raise StopIteration
except StopIteration:
i.rewind(i.index - subindex)
value = r'\\'
elif c == '/':
if self.pathname:
raise StopIteration
value = c
elif c in SET_OPERATORS:
# Escape &, |, and ~ to avoid &&, ||, and ~~
value = '\\' + c
else:
# Anything else
value = c
if end_range and i.index - 1 >= end_range:
if self._sequence_range_check(result, value):
removed = True
end_range = 0
else:
result.append(value)
c = next(i)
result.append(']')
# Bad range removed.
if removed:
value = "".join(result)
if value == '[]':
# We specified some ranges, but they are all
# out of reach. Create an impossible sequence to match.
result = ['[^%s]' % ('\x00-\xff' if self.is_bytes else uniprops.UNICODE_RANGE)]
elif value == '[^]':
# We specified some range, but hey are all
# out of reach. Since this is exclusive
# that means we can match *anything*.
result = ['[%s]' % ('\x00-\xff' if self.is_bytes else uniprops.UNICODE_RANGE)]
else:
result = [value]
if self.pathname or self.after_start:
return self._restrict_sequence() + ''.join(result)
return ''.join(result) |
java | public String currentWord() {
return wordIndex >= 0 && wordIndex < words.size() ? words.get(wordIndex) : null;
} |
python | def _read_socket(self, size):
"""
Reads data from socket.
:param size: Size in bytes to be read.
:return: Data from socket
"""
value = b''
while len(value) < size:
data = self.connection.recv(size - len(value))
if not data:
break
value += data
# If we got less data than we requested, the server disconnected.
if len(value) < size:
raise socket.error()
return value |
python | def check(self):
"""
Basic checks that don't depend on any context.
Adapted from Bicoin Code: main.cpp
"""
self._check_tx_inout_count()
self._check_txs_out()
self._check_txs_in()
# Size limits
self._check_size_limit() |
java | protected final BeanJsonMapperInfo getMapperInfo( JClassType beanType ) throws UnableToCompleteException {
BeanJsonMapperInfo mapperInfo = typeOracle.getBeanJsonMapperInfo( beanType );
if ( null != mapperInfo ) {
return mapperInfo;
}
boolean samePackage = true;
String packageName = beanType.getPackage().getName();
// We can't create classes in the java package so we prefix it.
if ( packageName.startsWith( "java." ) ) {
packageName = "gwtjackson." + packageName;
samePackage = false;
}
// Retrieve the informations on the beans and its properties.
BeanInfo beanInfo = BeanProcessor.processBean( logger, typeOracle, configuration, beanType );
PropertiesContainer properties = PropertyProcessor
.findAllProperties( configuration, logger, typeOracle, beanInfo, samePackage );
beanInfo = BeanProcessor.processProperties( configuration, logger, typeOracle, beanInfo, properties );
// We concatenate the name of all the enclosing classes.
StringBuilder builder = new StringBuilder( beanType.getSimpleSourceName() );
JClassType enclosingType = beanType.getEnclosingType();
while ( null != enclosingType ) {
builder.insert( 0, enclosingType.getSimpleSourceName() + "_" );
enclosingType = enclosingType.getEnclosingType();
}
// If the type is specific to the mapper, we concatenate the name and hash of the mapper to it.
boolean isSpecificToMapper = configuration.isSpecificToMapper( beanType );
if ( isSpecificToMapper ) {
JClassType rootMapperClass = configuration.getRootMapperClass();
builder.insert( 0, '_' ).insert( 0, configuration.getRootMapperHash() ).insert( 0, '_' ).insert( 0, rootMapperClass
.getSimpleSourceName() );
}
String simpleSerializerClassName = builder.toString() + "BeanJsonSerializerImpl";
String simpleDeserializerClassName = builder.toString() + "BeanJsonDeserializerImpl";
mapperInfo = new BeanJsonMapperInfo( beanType, packageName, samePackage, simpleSerializerClassName,
simpleDeserializerClassName, beanInfo, properties
.getProperties() );
typeOracle.addBeanJsonMapperInfo( beanType, mapperInfo );
return mapperInfo;
} |
java | protected void readHeader(ByteBuffer buffer) {
super.readHeader(buffer);
if (this.responseStatus == ResponseStatus.NO_ERROR) {
this.decodeStatus = BinaryDecodeStatus.DONE;
}
} |
java | private JSONObject getTableResultHelper(String requestId, String resultType) {
AipRequest request = new AipRequest();
preOperation(request);
request.addBody("request_id", requestId);
request.addBody("result_type", resultType);
request.setUri(OcrConsts.TABLE_RESULT_GET);
postOperation(request);
return requestServer(request);
} |
java | public List<Label> getLabels(Object projectIdOrPath) throws GitLabApiException {
return (getLabels(projectIdOrPath, getDefaultPerPage()).all());
} |
java | @Deprecated
public C verify(int allowedStatements, Query query) throws WrongNumberOfQueriesError {
return verify(SqlQueries.exactQueries(allowedStatements).type(adapter(query)));
} |
java | @Override
public Set<QueryableEntry<K, V>> filter(QueryContext queryContext) {
if (!(predicate instanceof IndexAwarePredicate)) {
return null;
}
Set<QueryableEntry<K, V>> set = ((IndexAwarePredicate<K, V>) predicate).filter(queryContext);
if (set == null || set.isEmpty()) {
return set;
}
List<QueryableEntry<K, V>> resultList = new ArrayList<QueryableEntry<K, V>>();
Map.Entry<Integer, Map.Entry> nearestAnchorEntry = getNearestAnchorEntry();
for (QueryableEntry<K, V> queryableEntry : set) {
if (SortingUtil.compareAnchor(this, queryableEntry, nearestAnchorEntry)) {
resultList.add(queryableEntry);
}
}
List<QueryableEntry<K, V>> sortedSubList =
(List) SortingUtil.getSortedSubList((List) resultList, this, nearestAnchorEntry);
return new LinkedHashSet<QueryableEntry<K, V>>(sortedSubList);
} |
python | def electron_shell_str(shell, shellidx=None):
'''Return a string representing the data for an electron shell
If shellidx (index of the shell) is not None, it will also be printed
'''
am = shell['angular_momentum']
amchar = lut.amint_to_char(am)
amchar = amchar.upper()
shellidx_str = ''
if shellidx is not None:
shellidx_str = 'Index {} '.format(shellidx)
exponents = shell['exponents']
coefficients = shell['coefficients']
ncol = len(coefficients) + 1
point_places = [8 * i + 15 * (i - 1) for i in range(1, ncol + 1)]
s = "Shell: {}Region: {}: AM: {}\n".format(shellidx_str, shell['region'], amchar)
s += "Function: {}\n".format(shell['function_type'])
s += write_matrix([exponents, *coefficients], point_places)
return s |
python | def read_struct_field(self, struct_name, field_name, x, y, p=0):
"""Read the value out of a struct maintained by SARK.
This method is particularly useful for reading fields from the ``sv``
struct which, for example, holds information about system status. See
``sark.h`` for details.
Parameters
----------
struct_name : string
Name of the struct to read from, e.g., `"sv"`
field_name : string
Name of the field to read, e.g., `"eth_addr"`
Returns
-------
value
The value returned is unpacked given the struct specification.
Currently arrays are returned as tuples, e.g.::
# Returns a 20-tuple.
cn.read_struct_field("sv", "status_map")
# Fails
cn.read_struct_field("sv", "status_map[1]")
"""
# Look up the struct and field
field, address, pack_chars = \
self._get_struct_field_and_address(struct_name, field_name)
length = struct.calcsize(pack_chars)
# Perform the read
data = self.read(address, length, x, y, p)
# Unpack the data
unpacked = struct.unpack(pack_chars, data)
if field.length == 1:
return unpacked[0]
else:
return unpacked |
java | private void heartbeat() {
long index = context.nextIndex();
long timestamp = System.currentTimeMillis();
replicator.replicate(new HeartbeatOperation(index, timestamp))
.thenRun(() -> context.setTimestamp(timestamp));
} |
python | def insert_recording(hw):
"""Insert recording `hw` into database."""
mysql = utils.get_mysql_cfg()
connection = pymysql.connect(host=mysql['host'],
user=mysql['user'],
passwd=mysql['passwd'],
db=mysql['db'],
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
cursor = connection.cursor()
sql = ("INSERT INTO `wm_raw_draw_data` ("
"`user_id`, "
"`data`, "
"`md5data`, "
"`creation_date`, "
"`device_type`, "
"`accepted_formula_id`, "
"`secret`, "
"`ip`, "
"`segmentation`, "
"`internal_id`, "
"`description` "
") VALUES (%s, %s, MD5(data), "
"%s, %s, %s, %s, %s, %s, %s, %s);")
data = (hw.user_id,
hw.raw_data_json,
getattr(hw, 'creation_date', None),
getattr(hw, 'device_type', ''),
getattr(hw, 'formula_id', None),
getattr(hw, 'secret', ''),
getattr(hw, 'ip', None),
str(getattr(hw, 'segmentation', '')),
getattr(hw, 'internal_id', ''),
getattr(hw, 'description', ''))
cursor.execute(sql, data)
connection.commit()
for symbol_id, strokes in zip(hw.symbol_stream, hw.segmentation):
insert_symbol_mapping(cursor.lastrowid,
symbol_id,
hw.user_id,
strokes)
logging.info("Insert raw data.")
except pymysql.err.IntegrityError as e:
print("Error: {} (can probably be ignored)".format(e)) |
java | public static IUnitizingAnnotationUnit findNextUnit(
final Iterator<IUnitizingAnnotationUnit> units, int raterIdx,
final Object category) {
while (units.hasNext()) {
IUnitizingAnnotationUnit result = units.next();
if (category != null && !category.equals(result.getCategory())) {
continue;
}
if (raterIdx < 0 || result.getRaterIdx() == raterIdx) {
return result;
}
}
return null;
} |
java | public static <T extends Annotation> T getAnnotation(Object context, Class<T> annotation) {
Class<?> contextClass = context.getClass();
if(contextClass.isAnnotationPresent(annotation)) {
return contextClass.getAnnotation(annotation);
}
else {
return null;
}
} |
java | @Given("^I obtain elasticsearch cluster name in '([^:]+?)(:.+?)?' and save it in variable '(.+?)'?$")
public void saveElasticCluster(String host, String port, String envVar) throws Exception {
commonspec.setRestProtocol("http://");
commonspec.setRestHost(host);
commonspec.setRestPort(port);
Future<Response> response;
response = commonspec.generateRequest("GET", false, null, null, "/", "", "json", "");
commonspec.setResponse("GET", response.get());
String json;
String parsedElement;
json = commonspec.getResponse().getResponse();
parsedElement = "$..cluster_name";
String json2 = "[" + json + "]";
String value = commonspec.getJSONPathString(json2, parsedElement, "0");
if (value == null) {
throw new Exception("No cluster name is found");
} else {
ThreadProperty.set(envVar, value);
}
} |
java | public double getRank(final double value) {
if (isEmpty()) { return Double.NaN; }
final DoublesSketchAccessor samples = DoublesSketchAccessor.wrap(this);
long total = 0;
int weight = 1;
samples.setLevel(DoublesSketchAccessor.BB_LVL_IDX);
for (int i = 0; i < samples.numItems(); i++) {
if (samples.get(i) < value) {
total += weight;
}
}
long bitPattern = getBitPattern();
for (int lvl = 0; bitPattern != 0L; lvl++, bitPattern >>>= 1) {
weight *= 2;
if ((bitPattern & 1L) > 0) { // level is not empty
samples.setLevel(lvl);
for (int i = 0; i < samples.numItems(); i++) {
if (samples.get(i) < value) {
total += weight;
} else {
break; // levels are sorted, no point comparing further
}
}
}
}
return (double) total / getN();
} |
java | public void marshall(DeleteLabelsRequest deleteLabelsRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteLabelsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteLabelsRequest.getResourceId(), RESOURCEID_BINDING);
protocolMarshaller.marshall(deleteLabelsRequest.getAuthenticationToken(), AUTHENTICATIONTOKEN_BINDING);
protocolMarshaller.marshall(deleteLabelsRequest.getLabels(), LABELS_BINDING);
protocolMarshaller.marshall(deleteLabelsRequest.getDeleteAll(), DELETEALL_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def _isbool(string):
"""
>>> _isbool(True)
True
>>> _isbool("False")
True
>>> _isbool(1)
False
"""
return isinstance(string, _bool_type) or\
(isinstance(string, (_binary_type, _text_type))
and
string in ("True", "False")) |
java | public static final Long getTimeBoxValue(TimeZone zone, Date date) {
if (date == null) return null;
// use a Calendar in the specified timezone to figure out the
// time which is edited in a format independent of TimeZone.
Calendar cal = GregorianCalendar.getInstance(zone);
cal.setTime(date);
// hh:mm (seconds and milliseconds are generally zero but we
// include them as well)
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
int millis = cal.get(Calendar.MILLISECOND);
return (((((hours * 60L) + minutes) * 60L) + seconds) * 1000L) + millis;
} |
java | @Override
public int reverseProxyTo(URL url, StaplerRequest req) throws IOException {
return getWrapped().reverseProxyTo(url, req);
} |
python | def get_team_members_with_extended_properties(self, project_id, team_id, top=None, skip=None):
"""GetTeamMembersWithExtendedProperties.
[Preview API] Get a list of members for a specific team.
:param str project_id: The name or ID (GUID) of the team project the team belongs to.
:param str team_id: The name or ID (GUID) of the team .
:param int top:
:param int skip:
:rtype: [TeamMember]
"""
route_values = {}
if project_id is not None:
route_values['projectId'] = self._serialize.url('project_id', project_id, 'str')
if team_id is not None:
route_values['teamId'] = self._serialize.url('team_id', team_id, 'str')
query_parameters = {}
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
response = self._send(http_method='GET',
location_id='294c494c-2600-4d7e-b76c-3dd50c3c95be',
version='5.1-preview.2',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TeamMember]', self._unwrap_collection(response)) |
java | public void publish(boolean block, boolean skip) {
//Sort components so we always get the same timline order...
// Arrays.sort(components);
//If blocking behavior has been requested, wait until any previous call
//to the image encoding thread has finished. The rest of the
//code in this function is written from an "encode if possible" perspective.
if (!skip) imageEncoder.waitUntilFinished();
if(!imageEncoder.isWorking()) {
timelinesToRefresh.clear();
if (bounds != null) {
min = bounds.min+origin;
max = bounds.max+origin;
}
else {
min = origin;
max = Long.MIN_VALUE;
}
for(int tl = 0; tl < components.length; tl++) {
String comp = components[tl];
SymbolicTimeline stl = null;
//synchronized(ans) {
synchronized(an) {
//stl = new SymbolicTimeline(ans, comp);
if (markingsToExclude != null) stl = new SymbolicTimeline(an, comp, markingsToExclude);
else stl = new SymbolicTimeline(an, comp);
}
if (bounds == null) {
if (stl.getPulses()[stl.getPulses().length-1] > max) max = stl.getPulses()[stl.getPulses().length-1];
}
timelinesToRefresh.add(stl);
}
long delta = 0;
double portionBefore = 0.9;
if (slidingWindow && bounds != null) {
delta = bounds.max-bounds.min;
if (((double)timeNow)/temporalResolution > origin+((double)delta)*portionBefore) {
min = (long)( ((double)timeNow)/(double)temporalResolution - ((double)delta)*portionBefore);
max = (long)( ((double)timeNow)/(double)temporalResolution + ((double)delta)*(1-portionBefore));
}
}
imageEncoder.encodeTimelines(timelinesToRefresh);
logger.finest("Image being rendered...");
}
else {
logger.finest("Skipped rendering image.");
}
//If blocking behavior has been requested, do not return until
//the image encoding thread has finished.
if (block) imageEncoder.waitUntilFinished();
} |
java | private static synchronized IMqttClient getClient(MqttSettings settings) throws MqttException {
if (CLIENT == null) {
CLIENT = new MqttClient(settings.getServerUrl(), PUBLISHER_ID);
MqttConnectOptions options = new MqttConnectOptions();
options.setAutomaticReconnect(true);
options.setCleanSession(true);
options.setConnectionTimeout(10);
CLIENT.connect(options);
}
return CLIENT;
} |
python | def authenticate_with_password(self, username, password,
security_question_id=None,
security_question_answer=None):
"""Performs Username/Password Authentication
:param string username: your SoftLayer username
:param string password: your SoftLayer password
:param int security_question_id: The security question id to answer
:param string security_question_answer: The answer to the security
question
"""
self.auth = None
res = self.call('User_Customer', 'getPortalLoginToken',
username,
password,
security_question_id,
security_question_answer)
self.auth = slauth.TokenAuthentication(res['userId'], res['hash'])
return res['userId'], res['hash'] |
python | def is_compression_coordinate(ds, variable):
'''
Returns True if the variable is a coordinate variable that defines a
compression scheme.
:param netCDF4.Dataset nc: An open netCDF dataset
:param str variable: Variable name
'''
# Must be a coordinate variable
if not is_coordinate_variable(ds, variable):
return False
# must have a string attribute compress
compress = getattr(ds.variables[variable], 'compress', None)
if not isinstance(compress, basestring):
return False
if not compress:
return False
# This should never happen or be allowed
if variable in compress:
return False
# Must point to dimensions
for dim in compress.split():
if dim not in ds.dimensions:
return False
return True |
java | public FlowStatus getFlowStatus(String flowName, String flowGroup, long flowExecutionId) {
FlowStatus flowStatus = null;
Iterator<JobStatus> jobStatusIterator =
jobStatusRetriever.getJobStatusesForFlowExecution(flowName, flowGroup, flowExecutionId);
if (jobStatusIterator.hasNext()) {
flowStatus = new FlowStatus(flowName, flowGroup, flowExecutionId, jobStatusIterator);
}
return flowStatus;
} |
java | @Override
public AttachmentResourceWritable addAttachment(File file, AttachmentType type) throws RepositoryException {
return addAttachment(file, type, file.getName());
} |
java | public void getAllFileID(Callback<List<String>> callback) throws NullPointerException {
gw2API.getAllFileIDs().enqueue(callback);
} |
python | def numpy_to_data_array(ary, *, var_name="data", coords=None, dims=None):
"""Convert a numpy array to an xarray.DataArray.
The first two dimensions will be (chain, draw), and any remaining
dimensions will be "shape".
If the numpy array is 1d, this dimension is interpreted as draw
If the numpy array is 2d, it is interpreted as (chain, draw)
If the numpy array is 3 or more dimensions, the last dimensions are kept as shapes.
Parameters
----------
ary : np.ndarray
A numpy array. If it has 2 or more dimensions, the first dimension should be
independent chains from a simulation. Use `np.expand_dims(ary, 0)` to add a
single dimension to the front if there is only 1 chain.
var_name : str
If there are no dims passed, this string is used to name dimensions
coords : dict[str, iterable]
A dictionary containing the values that are used as index. The key
is the name of the dimension, the values are the index values.
dims : List(str)
A list of coordinate names for the variable
Returns
-------
xr.DataArray
Will have the same data as passed, but with coordinates and dimensions
"""
# manage and transform copies
default_dims = ["chain", "draw"]
ary = np.atleast_2d(ary)
n_chains, n_samples, *shape = ary.shape
if n_chains > n_samples:
warnings.warn(
"More chains ({n_chains}) than draws ({n_samples}). "
"Passed array should have shape (chains, draws, *shape)".format(
n_chains=n_chains, n_samples=n_samples
),
SyntaxWarning,
)
dims, coords = generate_dims_coords(
shape, var_name, dims=dims, coords=coords, default_dims=default_dims
)
# reversed order for default dims: 'chain', 'draw'
if "draw" not in dims:
dims = ["draw"] + dims
if "chain" not in dims:
dims = ["chain"] + dims
if "chain" not in coords:
coords["chain"] = np.arange(n_chains)
if "draw" not in coords:
coords["draw"] = np.arange(n_samples)
# filter coords based on the dims
coords = {key: xr.IndexVariable((key,), data=coords[key]) for key in dims}
return xr.DataArray(ary, coords=coords, dims=dims) |
python | def _fillAndTraceback(self, table):
"""
Perform Local Alignment according to Smith-Waterman Algorithm.
Fills the table and then traces back from the highest score.
NB left = deletion and up = insertion wrt seq1
"""
# Fill
max_score = 0
max_row = 0
max_col = 0
for row in range(1, len(self.seq2Seq) + 1):
for col in range(1, len(self.seq1Seq) + 1):
# Calculate match score
letter1 = self.seq1Seq[col - 1]
letter2 = self.seq2Seq[row - 1]
if letter1 == letter2:
diagonal_score = (table[row - 1][col - 1]['score'] +
self.match)
else:
diagonal_score = (table[row - 1][col - 1]['score'] +
self.mismatch)
ins_run = table[row - 1][col]['ins']
del_run = table[row][col - 1]['del']
# Calculate gap scores ensuring extension is not > 0
if table[row - 1][col]['ins'] <= 0:
ins_score = table[row - 1][col]['score'] + self.gapOpen
else:
if self.gapExtend + ins_run * self.gapExtendDecay <= 0.0:
ins_score = (table[row - 1][col]['score'] +
self.gapExtend +
ins_run * self.gapExtendDecay)
else:
ins_score = table[row - 1][col]['score']
if table[row - 1][col]['del'] <= 0:
del_score = table[row][col - 1]['score'] + self.gapOpen
else:
if self.gapExtend + del_run * self.gapExtendDecay <= 0.0:
del_score = (table[row][col - 1]['score'] +
self.gapExtend +
del_run * self.gapExtendDecay)
else:
del_score = table[row][col - 1]['score']
# Choose best score
if diagonal_score <= 0 and ins_score <= 0 and del_score <= 0:
table[row][col] = {'score': 0, 'pointer': None, 'ins': 0,
'del': 0}
else:
if diagonal_score >= ins_score:
if diagonal_score >= del_score: # diag lef/up
diagonal = {'score': diagonal_score,
'pointer': 'diagonal', 'ins': 0,
'del': 0}
table[row][col] = diagonal
else: # lef diag/up
deletion = {'score': del_score, 'pointer': 'del',
'ins': 0, 'del': del_run + 1}
table[row][col] = deletion
else: # up diag
if ins_score >= del_score: # up diag/lef
insertion = {'score': ins_score, 'pointer': 'ins',
'ins': ins_run + 1, 'del': 0}
table[row][col] = insertion
else: # lef up diag
deletion = {'score': del_score, 'pointer': 'del',
'ins': 0, 'del': del_run + 1}
table[row][col] = deletion
# Set max score - is this the best way of getting max score
# considering how the for loop iterates through the matrix?
if table[row][col]['score'] >= max_score:
max_row = row
max_col = col
max_score = table[row][col]['score']
# Traceback
indexes = {'max_row': max_row, 'max_col': max_col}
align1 = ''
align2 = ''
align = ''
current_row = max_row
current_col = max_col
while True:
arrow = table[current_row][current_col]['pointer']
if arrow is None:
min_row = current_row + 1
min_col = current_col + 1
break
elif arrow == 'diagonal':
align1 += self.seq1Seq[current_col - 1]
align2 += self.seq2Seq[current_row - 1]
if self.seq1Seq[current_col - 1] == self.seq2Seq[
current_row - 1]:
align += '|'
else:
align += ' '
current_row -= 1
current_col -= 1
elif arrow == 'del':
align1 += self.seq1Seq[current_col - 1]
align2 += '-'
align += ' '
current_col -= 1
elif arrow == 'ins':
align1 += '-'
align2 += self.seq2Seq[current_row - 1]
align += ' '
current_row -= 1
else:
raise ValueError('Invalid pointer: %s' % arrow)
indexes['min_row'] = min_row
indexes['min_col'] = min_col
align1 = align1[::-1]
align2 = align2[::-1]
align = align[::-1]
if len(align1) != len(align2):
raise ValueError(
'Lengths of locally aligned sequences differ (%d != %d).' % (
len(align1), len(align2)))
return ([align1, align, align2], indexes) |
java | private void init() {
// MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) getContext().getResources().getDimension(R.dimen.bottom_navigation_padded_height)));
// marginParams.setMargins(0, (int) getContext().getResources().getDimension(R.dimen.bottom_navigation_top_margin_correction), 0, 0);
setLayoutParams(new ViewGroup.LayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)));
LayoutInflater inflater = LayoutInflater.from(getContext());
View parentView = inflater.inflate(R.layout.bottom_navigation_bar_container, this, true);
mBackgroundOverlay = parentView.findViewById(R.id.bottom_navigation_bar_overLay);
mContainer = parentView.findViewById(R.id.bottom_navigation_bar_container);
mTabContainer = parentView.findViewById(R.id.bottom_navigation_bar_item_container);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.setOutlineProvider(ViewOutlineProvider.BOUNDS);
} else {
//to do
}
ViewCompat.setElevation(this, mElevation);
setClipToPadding(false);
} |
python | def set_value(self, dry_wet: LeakSensorState):
"""Set the value of the state to dry or wet."""
value = 0
if dry_wet == self._dry_wet_type:
value = 1
self._update_subscribers(value) |
java | @Override
public int getJobInstanceCount(String jobName) throws NoSuchJobException, JobSecurityException {
int jobInstanceCount = 0;
if (authService == null || authService.isAdmin() || authService.isMonitor()) {
// Do an unfiltered query if no app security, or if the user is admin or monitor
jobInstanceCount = getPersistenceManagerService().getJobInstanceCount(jobName);
} else if (authService.isSubmitter()) {
jobInstanceCount = getPersistenceManagerService().getJobInstanceCount(jobName, batchSecurityHelper.getRunAsUser());
} else {
throw new JobSecurityException("Current user " + authService.getRunAsUser() + " is not authorized to perform batch operations");
}
// Debate on mailing list if we should be reqiured to distinguish between 0 count and NoSuchJobException.
if (jobInstanceCount == 0) {
validateJobName(jobName);
}
return jobInstanceCount;
} |
java | protected static List<EndpointHelpDto> describeEndpoints(List<Class<? extends AbstractResource>> resourceClasses) {
List<EndpointHelpDto> result = new LinkedList<>();
if (resourceClasses != null && !resourceClasses.isEmpty()) {
for (Class<? extends AbstractResource> resourceClass : resourceClasses) {
EndpointHelpDto dto = EndpointHelpDto.fromResourceClass(resourceClass);
if (dto != null) {
result.add(dto);
}
}
}
return result;
} |
java | public static <T> Comparator<T> comparator(CheckedComparator<T> comparator, Consumer<Throwable> handler) {
return (t1, t2) -> {
try {
return comparator.compare(t1, t2);
}
catch (Throwable e) {
handler.accept(e);
throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
}
};
} |
java | public PreferencesFx saveSettings(boolean save) {
preferencesFxModel.setSaveSettings(save);
// if settings shouldn't be saved, clear them if there are any present
if (!save) {
preferencesFxModel.getStorageHandler().clearPreferences();
}
return this;
} |
python | def stem_plural_word(self, plural):
"""Stem a plural word to its common stem form.
Asian J. (2007) "Effective Techniques for Indonesian Text Retrieval" page 76-77.
@link http://researchbank.rmit.edu.au/eserv/rmit:6312/Asian.pdf
"""
matches = re.match(r'^(.*)-(.*)$', plural)
#translated from PHP conditional check:
#if (!isset($words[1]) || !isset($words[2]))
if not matches:
return plural
words = [matches.group(1), matches.group(2)]
#malaikat-malaikat-nya -> malaikat malaikat-nya
suffix = words[1]
suffixes = ['ku', 'mu', 'nya', 'lah', 'kah', 'tah', 'pun']
matches = re.match(r'^(.*)-(.*)$', words[0])
if suffix in suffixes and matches:
words[0] = matches.group(1)
words[1] = matches.group(2) + '-' + suffix
#berbalas-balasan -> balas
rootWord1 = self.stem_singular_word(words[0])
rootWord2 = self.stem_singular_word(words[1])
#meniru-nirukan -> tiru
if not self.dictionary.contains(words[1]) and rootWord2 == words[1]:
rootWord2 = self.stem_singular_word('me' + words[1])
if rootWord1 == rootWord2:
return rootWord1
else:
return plural |
python | def get_menu_items_for_rendering(self):
"""
Return a list of 'menu items' to be included in the context for
rendering the current level of the menu.
The responsibility for sourcing, priming, and modifying menu items is
split between three methods: ``get_raw_menu_items()``,
``prime_menu_items()`` and ``modify_menu_items()``, respectively.
"""
items = self.get_raw_menu_items()
# Allow hooks to modify the raw list
for hook in hooks.get_hooks('menus_modify_raw_menu_items'):
items = hook(items, **self.common_hook_kwargs)
# Prime and modify the menu items accordingly
items = self.modify_menu_items(self.prime_menu_items(items))
if isinstance(items, GeneratorType):
items = list(items)
# Allow hooks to modify the primed/modified list
hook_methods = hooks.get_hooks('menus_modify_primed_menu_items')
for hook in hook_methods:
items = hook(items, **self.common_hook_kwargs)
return items |
python | def removeComments(element):
"""
Removes comments from the element and its children.
"""
global _num_bytes_saved_in_comments
num = 0
if isinstance(element, xml.dom.minidom.Comment):
_num_bytes_saved_in_comments += len(element.data)
element.parentNode.removeChild(element)
num += 1
else:
for subelement in element.childNodes[:]:
num += removeComments(subelement)
return num |
java | public void removeRunner(String name, String identifier) throws GreenPepperServerException
{
log.debug("Removing runner: " + name);
execute(XmlRpcMethodName.removeRunner, CollectionUtil.toVector(name), identifier);
} |
java | public synchronized void setActive(boolean active) {
if (this.isActive == active) {
log.info("DagManager already {}, skipping further actions.", (!active) ? "inactive" : "active");
return;
}
this.isActive = active;
try {
if (this.isActive) {
log.info("Activating DagManager.");
log.info("Scheduling {} DagManager threads", numThreads);
//Initializing state store for persisting Dags.
Class dagStateStoreClass = Class.forName(ConfigUtils.getString(config, DAG_STATESTORE_CLASS_KEY, FSDagStateStore.class.getName()));
this.dagStateStore = (DagStateStore) GobblinConstructorUtils.invokeLongestConstructor(dagStateStoreClass, config, topologySpecMap);
//On startup, the service creates DagManagerThreads that are scheduled at a fixed rate.
for (int i = 0; i < numThreads; i++) {
this.scheduledExecutorPool.scheduleAtFixedRate(new DagManagerThread(jobStatusRetriever, dagStateStore, queue, instrumentationEnabled), 0, this.pollingInterval,
TimeUnit.SECONDS);
}
if ((this.jobStatusMonitor != null) && (!this.jobStatusMonitor.isRunning())) {
log.info("Starting job status monitor");
jobStatusMonitor.startAsync().awaitRunning();
}
for (Dag<JobExecutionPlan> dag : dagStateStore.getDags()) {
offer(dag);
}
} else { //Mark the DagManager inactive.
log.info("Inactivating the DagManager. Shutting down all DagManager threads");
this.scheduledExecutorPool.shutdown();
try {
this.scheduledExecutorPool.awaitTermination(TERMINATION_TIMEOUT, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.error("Exception {} encountered when shutting down DagManager threads.", e);
}
log.info("Shutting down JobStatusMonitor");
this.jobStatusMonitor.shutDown();
}
} catch (IOException | ReflectiveOperationException e) {
log.error("Exception encountered when activating the new DagManager", e);
throw new RuntimeException(e);
}
} |
java | public AssemblyDefinitionInner get(String resourceGroupName, String integrationAccountName, String assemblyArtifactName) {
return getWithServiceResponseAsync(resourceGroupName, integrationAccountName, assemblyArtifactName).toBlocking().single().body();
} |
java | public static Matcher<AnnotationTree> hasArgumentWithValue(
String argumentName, Matcher<ExpressionTree> valueMatcher) {
return new AnnotationHasArgumentWithValue(argumentName, valueMatcher);
} |
java | public void setSizeSegment(com.google.api.ads.admanager.axis.v201808.CreativePlaceholder[] sizeSegment) {
this.sizeSegment = sizeSegment;
} |
python | def simple_eq(one: Instance, two: Instance, attrs: List[str]) -> bool:
"""
Test if two objects are equal, based on a comparison of the specified
attributes ``attrs``.
"""
return all(getattr(one, a) == getattr(two, a) for a in attrs) |
java | private void loadPreInstalledPlugins() {
for (File file : listJarFiles(fs.getInstalledPluginsDir())) {
PluginInfo info = PluginInfo.create(file);
registerPluginInfo(info);
}
} |
python | def _cache_loc(self, path, saltenv='base', cachedir=None):
'''
Return the local location to cache the file, cache dirs will be made
'''
cachedir = self.get_cachedir(cachedir)
dest = salt.utils.path.join(cachedir,
'files',
saltenv,
path)
destdir = os.path.dirname(dest)
with salt.utils.files.set_umask(0o077):
# remove destdir if it is a regular file to avoid an OSError when
# running os.makedirs below
if os.path.isfile(destdir):
os.remove(destdir)
# ensure destdir exists
try:
os.makedirs(destdir)
except OSError as exc:
if exc.errno != errno.EEXIST: # ignore if it was there already
raise
yield dest |
python | def _postcheck(self, network, feedin):
"""
Raises an error if the curtailment of a generator exceeds the
feed-in of that generator at any time step.
Parameters
-----------
network : :class:`~.grid.network.Network`
feedin : :pandas:`pandas.DataFrame<dataframe>`
DataFrame with feed-in time series in kW. Columns of the dataframe
are :class:`~.grid.components.GeneratorFluctuating`, index is
time index.
"""
curtailment = network.timeseries.curtailment
gen_repr = [repr(_) for _ in curtailment.columns]
feedin_repr = feedin.loc[:, gen_repr]
curtailment_repr = curtailment
curtailment_repr.columns = gen_repr
if not ((feedin_repr - curtailment_repr) > -1e-1).all().all():
message = 'Curtailment exceeds feed-in.'
logging.error(message)
raise TypeError(message) |
python | def _load_config():
"""Helper to load prefs from ~/.vispy/vispy.json"""
fname = _get_config_fname()
if fname is None or not op.isfile(fname):
return dict()
with open(fname, 'r') as fid:
config = json.load(fid)
return config |
java | @Override
public synchronized SQLiteDatabase getReadableDatabase() {
if (mDatabase != null && mDatabase.isOpen()) {
return mDatabase; // The database is already open for business
}
if (mIsInitializing) {
throw new IllegalStateException("getReadableDatabase called recursively");
}
try {
return getWritableDatabase();
} catch (SQLiteException e) {
if (mName == null) throw e; // Can't open a temp database read-only!
Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
}
SQLiteDatabase db = null;
try {
mIsInitializing = true;
String path = mContext.getDatabasePath(mName).getPath();
db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
if (db.getVersion() != mNewVersion) {
throw new SQLiteException("Can't upgrade read-only database from version " +
db.getVersion() + " to " + mNewVersion + ": " + path);
}
onOpen(db);
Log.w(TAG, "Opened " + mName + " in read-only mode");
mDatabase = db;
return mDatabase;
} finally {
mIsInitializing = false;
if (db != null && db != mDatabase) db.close();
}
} |
java | public static com.liferay.commerce.model.CommerceOrderItem addCommerceOrderItem(
com.liferay.commerce.model.CommerceOrderItem commerceOrderItem) {
return getService().addCommerceOrderItem(commerceOrderItem);
} |
python | def summarize(self, test_arr, vectorizable_token, sentence_list, limit=5):
'''
Summarize input document.
Args:
test_arr: `np.ndarray` of observed data points..
vectorizable_token: is-a `VectorizableToken`.
sentence_list: `list` of all sentences.
limit: The number of selected abstract sentence.
Returns:
`np.ndarray` of scores.
'''
if isinstance(vectorizable_token, VectorizableToken) is False:
raise TypeError()
_ = self.inference(test_arr)
score_arr = self.__encoder_decoder_controller.get_reconstruction_error()
score_arr = score_arr.reshape((
score_arr.shape[0],
-1
)).mean(axis=1)
score_list = score_arr.tolist()
abstract_list = []
for i in range(limit):
if self.__normal_prior_flag is True:
key = score_arr.argmin()
else:
key = score_arr.argmax()
score = score_list.pop(key)
score_arr = np.array(score_list)
seq_arr = test_arr[key]
token_arr = vectorizable_token.tokenize(seq_arr.tolist())
s = " ".join(token_arr.tolist())
_s = "".join(token_arr.tolist())
for sentence in sentence_list:
if s in sentence or _s in sentence:
abstract_list.append(sentence)
abstract_list = list(set(abstract_list))
if len(abstract_list) >= limit:
break
return abstract_list |
python | def clear_expired_cookies(self):
"""Discard all expired cookies.
You probably don't need to call this method: expired cookies are never
sent back to the server (provided you're using DefaultCookiePolicy),
this method is called by CookieJar itself every so often, and the
.save() method won't save expired cookies anyway (unless you ask
otherwise by passing a true ignore_expires argument).
"""
self._cookies_lock.acquire()
try:
now = time.time()
for cookie in self:
if cookie.is_expired(now):
self.clear(cookie.domain, cookie.path, cookie.name)
finally:
self._cookies_lock.release() |
java | @Override
@Deprecated
public DescribeExportConfigurationsResult describeExportConfigurations(DescribeExportConfigurationsRequest request) {
request = beforeClientExecution(request);
return executeDescribeExportConfigurations(request);
} |
java | public static JPAEntry convertEDBObjectEntryToJPAEntry(EDBObjectEntry entry, JPAObject owner) {
for (EDBConverterStep step : steps) {
if (step.doesStepFit(entry.getType())) {
LOGGER.debug("EDBConverterStep {} fit for type {}", step.getClass().getName(), entry.getType());
return step.convertToJPAEntry(entry, owner);
}
}
LOGGER.error("No EDBConverterStep fit for EDBObjectEntry {}", entry);
return null;
} |
java | public Reader requestPost(String data) throws IOException {
connection.setRequestMethod("POST");
connection.setDoOutput(true);
Writer writer = new Writer(connection.getOutputStream());
writer.write(data);
writer.close();
return new Reader(connection.getInputStream());
} |
java | protected static void addHeaders(Selenified clazz, ITestContext context, Map<String, Object> headers) {
context.setAttribute(clazz.getClass().getName() + "Headers", headers);
} |
java | public List<String> getTableColumn(final By tableBy, final int columnNumber) {
List<String> result = new ArrayList<String>();
List<List<String>> table = this.getTableAsList(tableBy);
for (List<String> line : table) {
result.add(line.get(columnNumber));
}
return result;
} |
java | public void marshall(DeleteClientCertificateRequest deleteClientCertificateRequest, ProtocolMarshaller protocolMarshaller) {
if (deleteClientCertificateRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(deleteClientCertificateRequest.getClientCertificateId(), CLIENTCERTIFICATEID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public CompletableFuture<String> getScope(final String scopeName) {
Preconditions.checkNotNull(scopeName);
return streamStore.getScopeConfiguration(scopeName);
} |
java | public String getValue (String name, String defval)
{
return _props.getProperty(name, defval);
} |
java | @Override
public FieldTextBuilder NOT() {
// NOT * => 0
// NOT 0 => *
if(isEmpty()) {
return setFieldText(MATCHNOTHING);
}
if(MATCHNOTHING.equals(this)) {
return clear();
}
not ^= true;
return this;
} |
python | def emit(self, record):
"""
Overloaded emit() function from the logger module.
The supplied log record is added to the log buffer and the
sigNewLog signal triggered.
.. note:: this method is always only called from the
``logger`` module.
"""
self.log.append(record)
# Do not trigger the signal again if no one has fetched any
# data since it was last set.
if not self.waitForFetch:
self.waitForFetch = True
self.sigNewLog.emit() |
java | public static <T> MutableFloatCollection collectFloat(
Iterable<T> iterable,
FloatFunction<? super T> floatFunction)
{
if (iterable instanceof MutableCollection)
{
return ((MutableCollection<T>) iterable).collectFloat(floatFunction);
}
if (iterable instanceof ArrayList)
{
return ArrayListIterate.collectFloat((ArrayList<T>) iterable, floatFunction);
}
if (iterable instanceof List)
{
return ListIterate.collectFloat((List<T>) iterable, floatFunction);
}
if (iterable != null)
{
return IterableIterate.collectFloat(iterable, floatFunction);
}
throw new IllegalArgumentException("Cannot perform a collectFloat on null");
} |
python | def createEditor(self, parent, column, operator, value):
"""
Creates a new editor for the given parent and operator.
:param parent | <QWidget>
operator | <str>
value | <variant>
"""
editor = super(NumericPlugin, self).createEditor(parent,
column,
operator,
value)
if isinstance(editor, QLineEdit):
validator = QRegExpValidator(QRegExp('^-?\d+\.?\d*'), editor)
editor.setValidator(validator)
if value is None:
value = 0
editor.setText(nativestring(value))
return editor |
java | public void informDiscard(final EventDispatcher pDispatcher, final Path pFile) {
// Remove the checksum resource to save memory
resources.remove(pFile);
if (pDispatcher.hasListeners()) {
final Collection<DispatchKey> keys = createKeys(pFile);
keys.forEach(k -> pDispatcher.discard(k));
}
} |
python | def read_rtt(jlink):
"""Reads the JLink RTT buffer #0 at 10Hz and prints to stdout.
This method is a polling loop against the connected JLink unit. If
the JLink is disconnected, it will exit. Additionally, if any exceptions
are raised, they will be caught and re-raised after interrupting the
main thread.
sys.stdout.write and sys.stdout.flush are used since target terminals
are expected to transmit newlines, which may or may not line up with the
arbitrarily-chosen 1024-byte buffer that this loop uses to read.
Args:
jlink (pylink.JLink): The JLink to read.
Raises:
Exception on error.
"""
try:
while jlink.connected():
terminal_bytes = jlink.rtt_read(0, 1024)
if terminal_bytes:
sys.stdout.write("".join(map(chr, terminal_bytes)))
sys.stdout.flush()
time.sleep(0.1)
except Exception:
print("IO read thread exception, exiting...")
thread.interrupt_main()
raise |
python | def build_kernel(self):
"""Build the KNN kernel.
Build a k nearest neighbors kernel, optionally with alpha decay.
If `precomputed` is not `None`, the appropriate steps in the kernel
building process are skipped.
Must return a symmetric matrix
Returns
-------
K : kernel matrix, shape=[n_samples, n_samples]
symmetric matrix with ones down the diagonal
with no non-negative entries.
Raises
------
ValueError: if `precomputed` is not an acceptable value
"""
if self.precomputed == "affinity":
# already done
# TODO: should we check that precomputed matrices look okay?
# e.g. check the diagonal
K = self.data_nu
elif self.precomputed == "adjacency":
# need to set diagonal to one to make it an affinity matrix
K = self.data_nu
if sparse.issparse(K) and \
not (isinstance(K, sparse.dok_matrix) or
isinstance(K, sparse.lil_matrix)):
K = K.tolil()
K = set_diagonal(K, 1)
else:
tasklogger.log_start("affinities")
if sparse.issparse(self.data_nu):
self.data_nu = self.data_nu.toarray()
if self.precomputed == "distance":
pdx = self.data_nu
elif self.precomputed is None:
pdx = pdist(self.data_nu, metric=self.distance)
if np.any(pdx == 0):
pdx = squareform(pdx)
duplicate_ids = np.array(
[i for i in np.argwhere(pdx == 0)
if i[1] > i[0]])
duplicate_names = ", ".join(["{} and {}".format(i[0], i[1])
for i in duplicate_ids])
warnings.warn(
"Detected zero distance between samples {}. "
"Consider removing duplicates to avoid errors in "
"downstream processing.".format(duplicate_names),
RuntimeWarning)
else:
pdx = squareform(pdx)
else:
raise ValueError(
"precomputed='{}' not recognized. "
"Choose from ['affinity', 'adjacency', 'distance', "
"None]".format(self.precomputed))
if self.bandwidth is None:
knn_dist = np.partition(
pdx, self.knn + 1, axis=1)[:, :self.knn + 1]
bandwidth = np.max(knn_dist, axis=1)
elif callable(self.bandwidth):
bandwidth = self.bandwidth(pdx)
else:
bandwidth = self.bandwidth
bandwidth = bandwidth * self.bandwidth_scale
pdx = (pdx.T / bandwidth).T
K = np.exp(-1 * np.power(pdx, self.decay))
# handle nan
K = np.where(np.isnan(K), 1, K)
tasklogger.log_complete("affinities")
# truncate
if sparse.issparse(K):
if not (isinstance(K, sparse.csr_matrix) or
isinstance(K, sparse.csc_matrix) or
isinstance(K, sparse.bsr_matrix)):
K = K.tocsr()
K.data[K.data < self.thresh] = 0
K = K.tocoo()
K.eliminate_zeros()
K = K.tocsr()
else:
K[K < self.thresh] = 0
return K |
python | def plot_lr(self, show_moms=False, skip_start:int=0, skip_end:int=0, return_fig:bool=None)->Optional[plt.Figure]:
"Plot learning rate, `show_moms` to include momentum."
lrs = self._split_list(self.lrs, skip_start, skip_end)
iterations = self._split_list(range_of(self.lrs), skip_start, skip_end)
if show_moms:
moms = self._split_list(self.moms, skip_start, skip_end)
fig, axs = plt.subplots(1,2, figsize=(12,4))
axs[0].plot(iterations, lrs)
axs[0].set_xlabel('Iterations')
axs[0].set_ylabel('Learning Rate')
axs[1].plot(iterations, moms)
axs[1].set_xlabel('Iterations')
axs[1].set_ylabel('Momentum')
else:
fig, ax = plt.subplots()
ax.plot(iterations, lrs)
ax.set_xlabel('Iterations')
ax.set_ylabel('Learning Rate')
if ifnone(return_fig, defaults.return_fig): return fig
if not IN_NOTEBOOK: plot_sixel(fig) |
java | public void generateProxy(Element element) {
try {
getClassBuilder(element)
.buildProxyClass()
.build()
.writeTo(filer);
} catch (Exception ex) {
messager.printMessage(Diagnostic.Kind.WARNING, "Error while generating Proxy " + ex.getMessage());
}
} |
java | public Postcard withParcelableArray(@Nullable String key, @Nullable Parcelable[] value) {
mBundle.putParcelableArray(key, value);
return this;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.