language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public void marshall(ListWebACLsRequest listWebACLsRequest, ProtocolMarshaller protocolMarshaller) {
if (listWebACLsRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(listWebACLsRequest.getNextMarker(), NEXTMARKER_BINDING);
protocolMarshaller.marshall(listWebACLsRequest.getLimit(), LIMIT_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | @Override
public RecordWriter<K, V> getRecordWriter(TaskAttemptContext context)
throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
return getDelegate(conf).getRecordWriter(context);
} |
java | SnapshotDescriptor copyTo(Buffer buffer) {
this.buffer = buffer
.writeLong(index)
.writeLong(timestamp)
.writeInt(version)
.writeBoolean(locked)
.skip(BYTES - buffer.position())
.flush();
return this;
} |
java | static boolean shouldExpireAfterRead(Request request) {
return Boolean.TRUE.toString().equalsIgnoreCase(request.header(CACHE_EXPIRE_AFTER_READ_HEADER));
} |
python | def dottable_getitem(data, dottable_key, default=None):
"""Return item as ``dict.__getitem__` but using keys with dots.
It does not address indexes in iterables.
"""
def getitem(value, *keys):
if not keys:
return default
elif len(keys) == 1:
key = keys[0]
if isinstance(value, MutableMapping):
return value.get(key, default)
elif isinstance(value, Sequence) and \
not isinstance(value, six.string_types):
return [getitem(v, key) for v in value]
return default
return getitem(getitem(value, keys[0]), *keys[1:])
return getitem(data, *dottable_key.split('.')) |
python | def get_current_m2m_diff(self, instance, new_objects):
"""
:param instance: Versionable object
:param new_objects: objects which are about to be associated with
instance
:return: (being_removed id list, being_added id list)
:rtype : tuple
"""
new_ids = self.pks_from_objects(new_objects)
relation_manager = self.__get__(instance)
filter = Q(**{relation_manager.source_field.attname: instance.pk})
qs = self.through.objects.current.filter(filter)
try:
# Django 1.7
target_name = relation_manager.target_field.attname
except AttributeError:
# Django 1.6
target_name = relation_manager.through._meta.get_field_by_name(
relation_manager.target_field_name)[0].attname
current_ids = set(qs.values_list(target_name, flat=True))
being_removed = current_ids - new_ids
being_added = new_ids - current_ids
return list(being_removed), list(being_added) |
python | def native(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a native string."""
if isinstance(s, str):
return s
if str is unicode: # Python 3.x ->
return unicodestr(s, encoding, fallback)
return bytestring(s, encoding, fallback) |
python | def _apply_tracing(self, handler, attributes):
"""
Helper function to avoid rewriting for middleware and decorator.
Returns a new span from the request with logged attributes and
correct operation name from the func.
"""
operation_name = self._get_operation_name(handler)
headers = handler.request.headers
request = handler.request
# start new span from trace info
try:
span_ctx = self._tracer.extract(opentracing.Format.HTTP_HEADERS,
headers)
scope = self._tracer.start_active_span(operation_name,
child_of=span_ctx)
except (opentracing.InvalidCarrierException,
opentracing.SpanContextCorruptedException):
scope = self._tracer.start_active_span(operation_name)
# add span to current spans
setattr(request, SCOPE_ATTR, scope)
# log any traced attributes
scope.span.set_tag(tags.COMPONENT, 'tornado')
scope.span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER)
scope.span.set_tag(tags.HTTP_METHOD, request.method)
scope.span.set_tag(tags.HTTP_URL, request.uri)
for attr in attributes:
if hasattr(request, attr):
payload = str(getattr(request, attr))
if payload:
scope.span.set_tag(attr, payload)
# invoke the start span callback, if any
self._call_start_span_cb(scope.span, request)
return scope |
python | def t_IDENTIFIER(self, t):
r'[a-zA-Z_][a-zA-Z0-9_]*'
t.type = self.reserved_words.get(t.value, 'IDENTIFIER')
return t |
java | public static Object decodeObjectContent(Object content, MediaType contentMediaType) {
try {
if (content == null) return null;
if (contentMediaType == null) {
throw new NullPointerException("contentMediaType cannot be null!");
}
String strContent;
String type = contentMediaType.getClassType();
if (type == null) return content;
if (type.equals("ByteArray")) {
if (content instanceof byte[]) return content;
if (content instanceof String) return hexToBytes(content.toString());
throw new EncodingException("Cannot read ByteArray!");
}
if (content instanceof byte[]) {
strContent = new String((byte[]) content, UTF_8);
} else {
strContent = content.toString();
}
Class<?> destinationType = Class.forName(type);
if (destinationType == String.class) return content;
if (destinationType == Boolean.class) return Boolean.parseBoolean(strContent);
if (destinationType == Short.class) return Short.parseShort(strContent);
if (destinationType == Byte.class) return Byte.parseByte(strContent);
if (destinationType == Integer.class) return Integer.parseInt(strContent);
if (destinationType == Long.class) return Long.parseLong(strContent);
if (destinationType == Float.class) return Float.parseFloat(strContent);
if (destinationType == Double.class) return Double.parseDouble(strContent);
return content;
} |
java | public void align(Structure s1, Structure s2) throws StructureException {
align(s1, s2, params);
} |
python | def weighted(weights):
"""
Return a random integer 0 <= N <= len(weights) - 1, where the weights
determine the probability of each possible integer.
Based on this StackOverflow post by Ned Batchelder:
http://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choice
"""
# Convert weights to floats
weights = [float(w) for w in weights]
# Pick a value at random
choice = random.uniform(0, sum(weights))
# Find the value
position = 0
for i, weight in enumerate(weights):
if position + weight >= choice:
return i
position += weight |
java | public final void creator() throws RecognitionException {
try {
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:649:5: ( ( nonWildcardTypeArguments )? createdName ( arrayCreatorRest | classCreatorRest ) )
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:649:7: ( nonWildcardTypeArguments )? createdName ( arrayCreatorRest | classCreatorRest )
{
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:649:7: ( nonWildcardTypeArguments )?
int alt74=2;
int LA74_0 = input.LA(1);
if ( (LA74_0==LESS) ) {
alt74=1;
}
switch (alt74) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:649:7: nonWildcardTypeArguments
{
pushFollow(FOLLOW_nonWildcardTypeArguments_in_creator3871);
nonWildcardTypeArguments();
state._fsp--;
if (state.failed) return;
}
break;
}
pushFollow(FOLLOW_createdName_in_creator3874);
createdName();
state._fsp--;
if (state.failed) return;
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:650:9: ( arrayCreatorRest | classCreatorRest )
int alt75=2;
int LA75_0 = input.LA(1);
if ( (LA75_0==LEFT_SQUARE) ) {
alt75=1;
}
else if ( (LA75_0==LEFT_PAREN) ) {
alt75=2;
}
else {
if (state.backtracking>0) {state.failed=true; return;}
NoViableAltException nvae =
new NoViableAltException("", 75, 0, input);
throw nvae;
}
switch (alt75) {
case 1 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:650:10: arrayCreatorRest
{
pushFollow(FOLLOW_arrayCreatorRest_in_creator3885);
arrayCreatorRest();
state._fsp--;
if (state.failed) return;
}
break;
case 2 :
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:650:29: classCreatorRest
{
pushFollow(FOLLOW_classCreatorRest_in_creator3889);
classCreatorRest();
state._fsp--;
if (state.failed) return;
}
break;
}
}
}
catch (RecognitionException re) {
throw re;
}
finally {
// do for sure before leaving
}
} |
python | def encode(cls, value):
"""
encode a floating point number to bytes in redis
:param value: float
:return: bytes
"""
try:
if float(value) + 0 == value:
return repr(value)
except (TypeError, ValueError):
pass
raise InvalidValue('not a float') |
java | private boolean isPublicAccessible(Member member) {
if (((AccessibleObject) member).isAccessible()) {
return true;
}
if (!Modifier.isPublic(member.getModifiers())) {
return false;
}
if (Modifier.isPublic(member.getDeclaringClass().getModifiers())) {
return true;
}
return false;
} |
python | def shallow_repr(self, max_depth=8, explicit_length=False, details=LITE_REPR):
"""
Returns a string representation of this AST, but with a maximum depth to
prevent floods of text being printed.
:param max_depth: The maximum depth to print.
:param explicit_length: Print lengths of BVV arguments.
:param details: An integer value specifying how detailed the output should be:
LITE_REPR - print short repr for both operations and BVs,
MID_REPR - print full repr for operations and short for BVs,
FULL_REPR - print full repr of both operations and BVs.
:return: A string representing the AST
"""
ast_queue = [(0, iter([self]))]
arg_queue = []
op_queue = []
while ast_queue:
try:
depth, args_iter = ast_queue[-1]
arg = next(args_iter)
if not isinstance(arg, Base):
arg_queue.append(arg)
continue
if max_depth is not None:
if depth >= max_depth:
arg_queue.append('<...>')
continue
if arg.op in operations.reversed_ops:
op_queue.append((depth + 1, operations.reversed_ops[arg.op], len(arg.args), arg.length))
ast_queue.append((depth + 1, reversed(arg.args)))
else:
op_queue.append((depth + 1, arg.op, len(arg.args), arg.length))
ast_queue.append((depth + 1, iter(arg.args)))
except StopIteration:
ast_queue.pop()
if op_queue:
depth, op, num_args, length = op_queue.pop()
args_repr = arg_queue[-num_args:]
del arg_queue[-num_args:]
length = length if explicit_length else None
inner_repr = self._op_repr(op, args_repr, depth > 1, length, details)
arg_queue.append(inner_repr)
assert len(op_queue) == 0, "op_queue is not empty"
assert len(ast_queue) == 0, "arg_queue is not empty"
assert len(arg_queue) == 1, ("repr_queue has unexpected length", len(arg_queue))
return "<{} {}>".format(self._type_name(), arg_queue.pop()) |
java | @Override
protected void _fit(Dataframe trainingData) {
ModelParameters modelParameters = knowledgeBase.getModelParameters();
Map<Object, Double> minColumnValues = modelParameters.getMinColumnValues();
Map<Object, Double> maxColumnValues = modelParameters.getMaxColumnValues();
boolean scaleResponse = knowledgeBase.getTrainingParameters().getScaleResponse();
Set<TypeInference.DataType> supportedXDataTypes = getSupportedXDataTypes();
Stream<Object> transformedColumns = trainingData.getXDataTypes().entrySet().stream()
.filter(e -> supportedXDataTypes.contains(e.getValue()))
.map(e -> e.getKey());
streamExecutor.forEach(StreamMethods.stream(transformedColumns, isParallelized()), column -> {
FlatDataCollection columnValues = trainingData.getXColumn(column).toFlatDataCollection();
minColumnValues.put(column, Descriptives.min(columnValues));
maxColumnValues.put(column, Descriptives.max(columnValues));
});
if(scaleResponse && trainingData.getYDataType() == TypeInference.DataType.NUMERICAL) {
FlatDataCollection columnValues = trainingData.getYColumn().toFlatDataCollection();
minColumnValues.put(Dataframe.COLUMN_NAME_Y, Descriptives.min(columnValues));
maxColumnValues.put(Dataframe.COLUMN_NAME_Y, Descriptives.max(columnValues));
}
} |
java | public com.google.privacy.dlp.v2.KmsWrappedCryptoKey getKmsWrapped() {
if (sourceCase_ == 3) {
return (com.google.privacy.dlp.v2.KmsWrappedCryptoKey) source_;
}
return com.google.privacy.dlp.v2.KmsWrappedCryptoKey.getDefaultInstance();
} |
python | def remote_upload(apikey, picture_url, resize=None,
rotation='00', noexif=False):
"""
prepares post for remote upload
:param str apikey: Apikey needed for Autentication on picflash.
:param str picture_url: URL to picture allowd Protocols are: ftp,
http, https
:param str resize: Aresolution in the folowing format: \
'80x80'(optional)
:param str|degree rotation: The picture will be rotated by this Value. \
Allowed values are 00, 90, 180, 270.(optional)
:param boolean noexif: set to True when exif data should be purged.\
(optional)
"""
check_rotation(rotation)
check_resize(resize)
url = check_if_redirect(picture_url)
if url:
picture_url = resolve_redirect(url)
post_data = compose_post(apikey, resize, rotation, noexif)
post_data['url[]'] = ('', picture_url)
return do_upload(post_data) |
java | @SuppressWarnings("unchecked")
private void decreaseKey(ReflectedHandle<K, V> n, K newKey) {
if (n.inner == null && free != n) {
throw new IllegalArgumentException("Invalid handle!");
}
int c;
if (comparator == null) {
c = ((Comparable<? super K>) newKey).compareTo(n.key);
} else {
c = comparator.compare(newKey, n.key);
}
if (c > 0) {
throw new IllegalArgumentException("Keys can only be decreased!");
}
n.key = newKey;
if (c == 0 || free == n) {
return;
}
// actual decrease
AddressableHeap.Handle<K, HandleMap<K, V>> nInner = n.inner;
if (n.minNotMax) {
// we are in the min heap, easy case
n.inner.decreaseKey(newKey);
} else {
// we are in the max heap, remove
nInner.delete();
ReflectedHandle<K, V> nOuter = nInner.getValue().outer;
nOuter.inner = null;
nOuter.minNotMax = false;
// remove min
AddressableHeap.Handle<K, HandleMap<K, V>> minInner = nInner.getValue().otherInner;
ReflectedHandle<K, V> minOuter = minInner.getValue().outer;
minInner.delete();
minOuter.inner = null;
minOuter.minNotMax = false;
// update key
nOuter.key = newKey;
// reinsert both
insertPair(nOuter, minOuter);
}
} |
java | public DateTime toDateTimeAtMidnight(DateTimeZone zone) {
Chronology chrono = getChronology().withZone(zone);
return new DateTime(getYear(), getMonthOfYear(), getDayOfMonth(), 0, 0, 0, 0, chrono);
} |
python | def publish(**kwargs):
"""
Runs the version task before pushing to git and uploading to pypi.
"""
current_version = get_current_version()
click.echo('Current version: {0}'.format(current_version))
retry = kwargs.get("retry")
debug('publish: retry=', retry)
if retry:
# The "new" version will actually be the current version, and the
# "current" version will be the previous version.
new_version = current_version
current_version = get_previous_version(current_version)
else:
level_bump = evaluate_version_bump(current_version, kwargs['force_level'])
new_version = get_new_version(current_version, level_bump)
owner, name = get_repository_owner_and_name()
ci_checks.check('master')
checkout('master')
if version(**kwargs):
push_new_version(
gh_token=os.environ.get('GH_TOKEN'),
owner=owner,
name=name
)
if config.getboolean('semantic_release', 'upload_to_pypi'):
upload_to_pypi(
username=os.environ.get('PYPI_USERNAME'),
password=os.environ.get('PYPI_PASSWORD'),
# We are retrying, so we don't want errors for files that are already on PyPI.
skip_existing=retry,
)
if check_token():
click.echo('Updating changelog')
try:
log = generate_changelog(current_version, new_version)
post_changelog(
owner,
name,
new_version,
markdown_changelog(new_version, log, header=False)
)
except GitError:
click.echo(click.style('Posting changelog failed.', 'red'), err=True)
else:
click.echo(
click.style('Missing token: cannot post changelog', 'red'), err=True)
click.echo(click.style('New release published', 'green'))
else:
click.echo('Version failed, no release will be published.', err=True) |
java | public static <T> AddQuery<T> start(T query, long correlationId, String type) {
return start(query, correlationId, type, null);
} |
java | private String generateValue() {
String result = "";
for (CmsCheckBox checkbox : m_checkboxes) {
if (checkbox.isChecked()) {
result += checkbox.getInternalValue() + ",";
}
}
if (result.contains(",")) {
result = result.substring(0, result.lastIndexOf(","));
}
return result;
} |
java | void registerAndConnect(SocketChannel sock, InetSocketAddress addr)
throws IOException {
selectionKey = sock.register(selector, SelectionKey.OP_CONNECT);
boolean immediateConnect = sock.connect(addr);
if(LOGGER.isTraceEnabled()){
LOGGER.trace("Connect to host=" + addr.getHostName() + ", hostString=" + addr.getHostString() + ", port=" + addr.getPort() + ", all=" + addr.getAddress() + ", local=" + sock.socket().getLocalSocketAddress());
}
if (immediateConnect) {
onConnectSucceeded();
}
} |
java | private void parseData(byte[] data)
{
int bytesRead = 0;
if (grouped)
{
group = data[bytesRead];
bytesRead ++;
}
if (encrypted)
{
encrType = data[bytesRead];
bytesRead ++;
}
if (lengthIndicator)
{
dataLength = Helpers.convertDWordToInt(data, bytesRead);
bytesRead += 4;
}
frameData = new byte[data.length - bytesRead];
System.arraycopy(data, bytesRead, frameData, 0, frameData.length);
} |
python | def set_away(self, away=True):
"""
:param away: a boolean of true (away) or false ('home')
:return nothing
This function handles both ecobee and nest thermostats
which use a different field for away/home status.
"""
if self.profile() is not None:
if away:
desired_state = {"profile": "away"}
else:
desired_state = {"profile": "home"}
else:
desired_state = {"users_away": away}
response = self.api_interface.set_device_state(self, {
"desired_state": desired_state
})
self._update_state_from_response(response) |
python | def drop_zombies(feed: "Feed") -> "Feed":
"""
In the given "Feed", drop stops with no stop times,
trips with no stop times, shapes with no trips,
routes with no trips, and services with no trips, in that order.
Return the resulting "Feed".
"""
feed = feed.copy()
# Drop stops of location type 0 that lack stop times
ids = feed.stop_times["stop_id"].unique()
f = feed.stops
cond = f["stop_id"].isin(ids)
if "location_type" in f.columns:
cond |= f["location_type"] != 0
feed.stops = f[cond].copy()
# Drop trips with no stop times
ids = feed.stop_times["trip_id"].unique()
f = feed.trips
feed.trips = f[f["trip_id"].isin(ids)]
# Drop shapes with no trips
ids = feed.trips["shape_id"].unique()
f = feed.shapes
if f is not None:
feed.shapes = f[f["shape_id"].isin(ids)]
# Drop routes with no trips
ids = feed.trips["route_id"].unique()
f = feed.routes
feed.routes = f[f["route_id"].isin(ids)]
# Drop services with no trips
ids = feed.trips["service_id"].unique()
if feed.calendar is not None:
f = feed.calendar
feed.calendar = f[f["service_id"].isin(ids)]
if feed.calendar_dates is not None:
f = feed.calendar_dates
feed.calendar_dates = f[f["service_id"].isin(ids)]
return feed |
java | final public void print(Object v)
{
if (v == null)
write(_nullChars, 0, _nullChars.length);
else {
String s = v.toString();
write(s, 0, s.length());
}
} |
java | public int getExpandedTypeID(String namespace, String localName, int type)
{
ExpandedNameTable ent = m_expandedNameTable;
return ent.getExpandedTypeID(namespace, localName, type);
} |
java | public void deleteBuildVariable(Integer projectId, String key)
throws IOException {
String tailUrl = GitlabProject.URL + "/" +
projectId +
GitlabBuildVariable.URL + "/" +
key;
retrieve().method(DELETE).to(tailUrl, Void.class);
} |
python | def isinstance(self, types):
"""
Checks if the instance if one of the types provided or if any of the inner_field child is one of the types
provided, returns True if field or any inner_field is one of ths provided, False otherwise
:param types: Iterable of types to check inclusion of instance
:return: Boolean
"""
if isinstance(self, types):
return True
inner_field = getattr(self, 'inner_field', None)
while inner_field:
if isinstance(inner_field, types):
return True
inner_field = getattr(inner_field, 'inner_field', None)
return False |
java | void markAsProcessed(final CtClass ctClass) {
final ClassFile classFile = ctClass.getClassFile();
for (final Object attributeObject : classFile.getAttributes()) {
if (attributeObject instanceof AnnotationsAttribute) {
final AnnotationsAttribute annotationAttribute = (AnnotationsAttribute) attributeObject;
final javassist.bytecode.annotation.Annotation annotation = annotationAttribute.getAnnotation(PROCESSED_ANNOTATION_CLASS);
if (annotation != null) {
return;
}
}
}
final javassist.bytecode.annotation.Annotation annotation =
new javassist.bytecode.annotation.Annotation(PROCESSED_ANNOTATION_CLASS, classFile.getConstPool());
final AnnotationsAttribute annotationAttribute =
new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
annotationAttribute.addAnnotation(annotation);
classFile.addAttribute(annotationAttribute);
} |
python | def config(key):
"""
Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration
base and configuration mapping.
"""
def decorator(cls):
parent = cls.getConfigurableParent()
if parent is None:
parentbase = None
else:
parentbase = getattr(parent, 'configbase', None)
if parentbase is None:
cls.configkey = key
else:
cls.configkey = parentbase + '.' + key
return cls
return decorator |
java | public ImplementationGuidePackageComponent addPackage() { //3
ImplementationGuidePackageComponent t = new ImplementationGuidePackageComponent();
if (this.package_ == null)
this.package_ = new ArrayList<ImplementationGuidePackageComponent>();
this.package_.add(t);
return t;
} |
java | public static org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement p2(
final Curve curve,
final FieldElement X,
final FieldElement Y,
final FieldElement Z) {
return new org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement(curve,
Representation.P2, X, Y, Z, null);
} |
python | def image(self, x, y, image, width=None, height=None):
"""
Inserts an image into the drawing, position by its top-left corner.
:param int x:
The x position to insert the image.
:param int y:
The y position to insert the image.
:param str image:
The file path or a PhotoImage or PIL.Image object.
:param str width:
The width to scale the image too, setting to `None` will use the
actual width of the Image. Default to `None`.
:param str height:
The width to scale the image too, setting to `None` will use the
actual height of the Image. Default to `None`.
:return:
The id of the image.
"""
# load the image and add to the dict (otherwise tk destroys the reference to them!)
_image = utils.GUIZeroImage(image, width, height)
id = self.tk.create_image(x, y, image=_image.tk_image, anchor="nw")
self._images[id] = _image
return id |
python | def add_vts(self, task_name, targets, cache_key, valid, phase):
""" Add a single VersionedTargetSet entry to the report.
:param InvalidationCacheManager cache_manager:
:param CacheKey cache_key:
:param bool valid:
:param string phase:
"""
if task_name not in self._task_reports:
self.add_task(task_name)
self._task_reports[task_name].add(targets, cache_key, valid, phase) |
java | void updateDataFields(int why) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "updateDataFields");
super.updateDataFields(why);
if (bodyMap != null && bodyMap.isChanged()) {
getPayload().setField(JmsMapBodyAccess.BODY_DATA_ENTRY_NAME, bodyMap.getKeyList());
getPayload().setField(JmsMapBodyAccess.BODY_DATA_ENTRY_VALUE, bodyMap.getValueList());
bodyMap.setUnChanged(); // d317373.1
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "updateDataFields");
} |
java | protected static String decodePercent(String str) {
String decoded = null;
try {
decoded = URLDecoder.decode(str, "UTF8");
} catch (UnsupportedEncodingException ignored) {
NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored);
}
return decoded;
} |
java | private void passivateSession(BackedSession sess) {
synchronized (sess) { // Keep PropertyWriter thread from sneaking in..
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[PASSIVATE_SESSION], "check for Passivation Listener for session");
}
// note that sessionCacheDiscard was called by LRUHashMap.put when he had to eject the oldest
getStoreCallback().sessionWillPassivate(sess);
if (_smc.getEnableTimeBasedWrite() || _smc.getPersistSessionAfterPassivation()) {
// Since removing from the cache... Need to write the session to the database
// Don't bother checking if this session is in the service method
// as it is the oldest entry in the cache.
// Need to also write the session if passivate updated any attributes.
if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
if (_smc.getEnableTimeBasedWrite()) {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[PASSIVATE_SESSION],
"Removing oldest entry from cache with TimeBasedWrits. Write it! " + sess.getId() + " " + getAppName());
} else {
LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[PASSIVATE_SESSION],
"Persisting the session after it was passivated. " + sess.getId() + " " + getAppName());
}
}
sess.removingSessionFromCache = true;
sess.sync();
sess.removingSessionFromCache = false;
}
}
} |
java | public static PreparedStatement createTrackTable(Connection connection, String trackTableName,boolean isH2) throws SQLException {
try (Statement stmt = connection.createStatement()) {
StringBuilder sb = new StringBuilder("CREATE TABLE ");
sb.append(trackTableName).append(" (");
if (isH2) {
sb.append("the_geom MULTILINESTRING CHECK ST_SRID(THE_GEOM) = 4326,");
} else {
sb.append("the_geom GEOMETRY(MULTILINESTRING, 4326),");
}
sb.append(" id INT,");
sb.append(GPXTags.NAME.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.CMT.toLowerCase()).append(" TEXT,");
sb.append("description").append(" TEXT,");
sb.append(GPXTags.SRC.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.HREF.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.HREFTITLE.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.NUMBER.toLowerCase()).append(" INT,");
sb.append(GPXTags.TYPE.toLowerCase()).append(" TEXT,");
sb.append(GPXTags.EXTENSIONS.toLowerCase()).append(" TEXT);");
stmt.execute(sb.toString());
}
//We return the preparedstatement of the route table
StringBuilder insert = new StringBuilder("INSERT INTO ").append(trackTableName).append(" VALUES ( ?");
for (int i = 1; i < GpxMetadata.RTEFIELDCOUNT; i++) {
insert.append(",?");
}
insert.append(");");
return connection.prepareStatement(insert.toString());
} |
java | public void incrementWaitingRequests(String browserName) {
logger.entering(browserName);
validateBrowserName(browserName);
BrowserStatistics lStatistics = createStatisticsIfNotPresent(browserName);
lStatistics.incrementWaitingRequests();
logger.exiting();
} |
python | def set_def_canned_acl(self, acl_str, key_name='', headers=None):
"""sets or changes a bucket's default object acl to a predefined
(canned) value"""
return self.set_canned_acl_helper(acl_str, key_name, headers,
query_args=DEF_OBJ_ACL) |
java | public EList<Double> getValues()
{
if (values == null)
{
values = new EDataTypeEList<Double>(Double.class, this, TypesPackage.JVM_DOUBLE_ANNOTATION_VALUE__VALUES);
}
return values;
} |
java | public Observable<EnqueueTrainingResponse> trainVersionAsync(UUID appId, String versionId) {
return trainVersionWithServiceResponseAsync(appId, versionId).map(new Func1<ServiceResponse<EnqueueTrainingResponse>, EnqueueTrainingResponse>() {
@Override
public EnqueueTrainingResponse call(ServiceResponse<EnqueueTrainingResponse> response) {
return response.body();
}
});
} |
python | def check_value_error_for_parity(value_error: ValueError, call_type: ParityCallType) -> bool:
"""
For parity failing calls and functions do not return None if the transaction
will fail but instead throw a ValueError exception.
This function checks the thrown exception to see if it's the correct one and
if yes returns True, if not returns False
"""
try:
error_data = json.loads(str(value_error).replace("'", '"'))
except json.JSONDecodeError:
return False
if call_type == ParityCallType.ESTIMATE_GAS:
code_checks_out = error_data['code'] == -32016
message_checks_out = 'The execution failed due to an exception' in error_data['message']
elif call_type == ParityCallType.CALL:
code_checks_out = error_data['code'] == -32015
message_checks_out = 'VM execution error' in error_data['message']
else:
raise ValueError('Called check_value_error_for_parity() with illegal call type')
if code_checks_out and message_checks_out:
return True
return False |
java | @Ok("json:full")
@At("/api/purchase")
public NutMap purchase(String userId, String commodityCode, int orderCount, boolean dofail) {
try {
businessService.purchase(userId, commodityCode, orderCount, dofail);
return new NutMap("ok", true);
}
catch (Throwable e) {
log.debug("purchase fail", e);
return new NutMap("ok", false);
}
} |
python | def update(self, key, content, **metadata):
"""
:param key: Document unique identifier.
:param str content: Content to store and index for search.
:param metadata: Arbitrary key/value pairs to store for document.
Update the given document. Existing metadata will be preserved and,
optionally, updated with the provided metadata.
"""
self.remove(key, preserve_data=True)
self.add(key, content, **metadata) |
python | def iterator(self, *argv):
""" Iterator returning any list of elements via attribute lookup in `self`
This iterator retains the order of the arguments """
for arg in argv:
if hasattr(self, arg):
for item in getattr(self, arg):
yield item |
java | public static boolean is_yanadi(String str)
{
String s1 = VarnaUtil.getAdiVarna(str);
if (is_yan(s1)) return true;
return false;
} |
java | @Override
public java.util.concurrent.Future<ReceiveMessageResult> receiveMessageAsync(String queueUrl,
com.amazonaws.handlers.AsyncHandler<ReceiveMessageRequest, ReceiveMessageResult> asyncHandler) {
return receiveMessageAsync(new ReceiveMessageRequest().withQueueUrl(queueUrl), asyncHandler);
} |
python | def firmware_download_input_protocol_type_ftp_protocol_ftp_host(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "input")
protocol_type = ET.SubElement(input, "protocol-type")
ftp_protocol = ET.SubElement(protocol_type, "ftp-protocol")
ftp = ET.SubElement(ftp_protocol, "ftp")
host = ET.SubElement(ftp, "host")
host.text = kwargs.pop('host')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
python | def top_charts_for_genre(self, genre_id):
"""Get a listing of top charts for a top chart genre.
Parameters:
genre_id (str): A top chart genre ID as found with :meth:`top_charts_genres`.
"""
response = self._call(mc_calls.BrowseTopChartForGenre, genre_id)
top_chart_for_genre = response.body
return top_chart_for_genre |
java | @Override
@FFDCIgnore(Exception.class)
public String getGroupSecurityName(final String inputUniqueGroupId) throws EntryNotFoundException, RegistryException {
try {
// bridge the APIs
String returnValue = securityBridge.getGroupSecurityName(inputUniqueGroupId);
return returnValue;
} catch (Exception excp) {
if (excp instanceof EntryNotFoundException)
throw (EntryNotFoundException) excp;
else if (excp instanceof RegistryException)
throw (RegistryException) excp;
else
throw new RegistryException(excp.getMessage(), excp);
}
} |
python | def show_minimum_needs_configuration(self):
"""Show the minimum needs dialog."""
# import here only so that it is AFTER i18n set up
from safe.gui.tools.minimum_needs.needs_manager_dialog import (
NeedsManagerDialog)
dialog = NeedsManagerDialog(
parent=self.iface.mainWindow(),
dock=self.dock_widget)
dialog.exec_() |
python | def __shapeIndex(self, i=None):
"""Returns the offset in a .shp file for a shape based on information
in the .shx index file."""
shx = self.shx
if not shx:
return None
if not self._offsets:
# File length (16-bit word * 2 = bytes) - header length
shx.seek(24)
shxRecordLength = (unpack(">i", shx.read(4))[0] * 2) - 100
numRecords = shxRecordLength // 8
# Jump to the first record.
shx.seek(100)
for r in range(numRecords):
# Offsets are 16-bit words just like the file length
self._offsets.append(unpack(">i", shx.read(4))[0] * 2)
shx.seek(shx.tell() + 4)
if not i == None:
return self._offsets[i] |
python | def get_clients_groups(self) -> typing.Iterator['Group']:
"""
Gets all clients groups
Returns: generator of Groups
"""
for group in self.groups:
if group.group_is_client_group:
yield group |
java | public IfcCommunicationsApplianceTypeEnum createIfcCommunicationsApplianceTypeEnumFromString(EDataType eDataType,
String initialValue) {
IfcCommunicationsApplianceTypeEnum result = IfcCommunicationsApplianceTypeEnum.get(initialValue);
if (result == null)
throw new IllegalArgumentException(
"The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
} |
java | public String getErrorString() {
StringBuffer ret = new StringBuffer();
String linesep = System.getProperty("line.separator");
List<Exception> exc = getExceptions();
if (exc != null && exc.size() != 0) {
// ret.append(HBCIUtils.getLocMsg("STAT_EXCEPTIONS")).append(":").append(linesep);
for (Iterator<Exception> j = exc.iterator(); j.hasNext(); ) {
ret.append(HBCIUtils.exception2StringShort(j.next()));
ret.append(linesep);
}
}
HBCIDialogStatus status = getDialogStatus();
if (status != null) {
String errMsg = status.getErrorString();
if (errMsg.length() != 0) {
ret.append(errMsg + linesep);
}
}
return ret.toString().trim();
} |
java | public final EObject ruleXVariableDeclaration() throws RecognitionException {
EObject current = null;
Token lv_writeable_1_0=null;
Token otherlv_2=null;
Token lv_extension_3_0=null;
Token lv_extension_4_0=null;
Token lv_writeable_5_0=null;
Token otherlv_6=null;
Token otherlv_8=null;
Token otherlv_10=null;
AntlrDatatypeRuleToken lv_name_7_0 = null;
EObject lv_type_9_0 = null;
EObject lv_right_11_0 = null;
enterRule();
try {
// InternalSARL.g:7968:2: ( ( ( ( ( () ( ( ( ( ( 'var' ) ) | 'val' ) ( ( 'extension' ) )? ) | ( ( ( 'extension' ) ) ( ( ( 'var' ) ) | 'val' ) ) ) ) )=> ( () ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) ) ) ) ( (lv_name_7_0= ruleValidID ) ) (otherlv_8= ':' ( (lv_type_9_0= ruleJvmTypeReference ) ) )? (otherlv_10= '=' ( (lv_right_11_0= ruleXExpression ) ) )? ) )
// InternalSARL.g:7969:2: ( ( ( ( () ( ( ( ( ( 'var' ) ) | 'val' ) ( ( 'extension' ) )? ) | ( ( ( 'extension' ) ) ( ( ( 'var' ) ) | 'val' ) ) ) ) )=> ( () ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) ) ) ) ( (lv_name_7_0= ruleValidID ) ) (otherlv_8= ':' ( (lv_type_9_0= ruleJvmTypeReference ) ) )? (otherlv_10= '=' ( (lv_right_11_0= ruleXExpression ) ) )? )
{
// InternalSARL.g:7969:2: ( ( ( ( () ( ( ( ( ( 'var' ) ) | 'val' ) ( ( 'extension' ) )? ) | ( ( ( 'extension' ) ) ( ( ( 'var' ) ) | 'val' ) ) ) ) )=> ( () ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) ) ) ) ( (lv_name_7_0= ruleValidID ) ) (otherlv_8= ':' ( (lv_type_9_0= ruleJvmTypeReference ) ) )? (otherlv_10= '=' ( (lv_right_11_0= ruleXExpression ) ) )? )
// InternalSARL.g:7970:3: ( ( ( () ( ( ( ( ( 'var' ) ) | 'val' ) ( ( 'extension' ) )? ) | ( ( ( 'extension' ) ) ( ( ( 'var' ) ) | 'val' ) ) ) ) )=> ( () ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) ) ) ) ( (lv_name_7_0= ruleValidID ) ) (otherlv_8= ':' ( (lv_type_9_0= ruleJvmTypeReference ) ) )? (otherlv_10= '=' ( (lv_right_11_0= ruleXExpression ) ) )?
{
// InternalSARL.g:7970:3: ( ( ( () ( ( ( ( ( 'var' ) ) | 'val' ) ( ( 'extension' ) )? ) | ( ( ( 'extension' ) ) ( ( ( 'var' ) ) | 'val' ) ) ) ) )=> ( () ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) ) ) )
// InternalSARL.g:7971:4: ( ( () ( ( ( ( ( 'var' ) ) | 'val' ) ( ( 'extension' ) )? ) | ( ( ( 'extension' ) ) ( ( ( 'var' ) ) | 'val' ) ) ) ) )=> ( () ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) ) )
{
// InternalSARL.g:8011:4: ( () ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) ) )
// InternalSARL.g:8012:5: () ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) )
{
// InternalSARL.g:8012:5: ()
// InternalSARL.g:8013:6:
{
if ( state.backtracking==0 ) {
current = forceCreateModelElement(
grammarAccess.getXVariableDeclarationAccess().getXtendVariableDeclarationAction_0_0_0(),
current);
}
}
// InternalSARL.g:8019:5: ( ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? ) | ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) ) )
int alt222=2;
int LA222_0 = input.LA(1);
if ( ((LA222_0>=65 && LA222_0<=66)) ) {
alt222=1;
}
else if ( (LA222_0==45) ) {
alt222=2;
}
else {
if (state.backtracking>0) {state.failed=true; return current;}
NoViableAltException nvae =
new NoViableAltException("", 222, 0, input);
throw nvae;
}
switch (alt222) {
case 1 :
// InternalSARL.g:8020:6: ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? )
{
// InternalSARL.g:8020:6: ( ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )? )
// InternalSARL.g:8021:7: ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' ) ( (lv_extension_3_0= 'extension' ) )?
{
// InternalSARL.g:8021:7: ( ( (lv_writeable_1_0= 'var' ) ) | otherlv_2= 'val' )
int alt219=2;
int LA219_0 = input.LA(1);
if ( (LA219_0==65) ) {
alt219=1;
}
else if ( (LA219_0==66) ) {
alt219=2;
}
else {
if (state.backtracking>0) {state.failed=true; return current;}
NoViableAltException nvae =
new NoViableAltException("", 219, 0, input);
throw nvae;
}
switch (alt219) {
case 1 :
// InternalSARL.g:8022:8: ( (lv_writeable_1_0= 'var' ) )
{
// InternalSARL.g:8022:8: ( (lv_writeable_1_0= 'var' ) )
// InternalSARL.g:8023:9: (lv_writeable_1_0= 'var' )
{
// InternalSARL.g:8023:9: (lv_writeable_1_0= 'var' )
// InternalSARL.g:8024:10: lv_writeable_1_0= 'var'
{
lv_writeable_1_0=(Token)match(input,65,FOLLOW_75); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(lv_writeable_1_0, grammarAccess.getXVariableDeclarationAccess().getWriteableVarKeyword_0_0_1_0_0_0_0());
}
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElement(grammarAccess.getXVariableDeclarationRule());
}
setWithLastConsumed(current, "writeable", true, "var");
}
}
}
}
break;
case 2 :
// InternalSARL.g:8037:8: otherlv_2= 'val'
{
otherlv_2=(Token)match(input,66,FOLLOW_75); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_2, grammarAccess.getXVariableDeclarationAccess().getValKeyword_0_0_1_0_0_1());
}
}
break;
}
// InternalSARL.g:8042:7: ( (lv_extension_3_0= 'extension' ) )?
int alt220=2;
int LA220_0 = input.LA(1);
if ( (LA220_0==45) ) {
alt220=1;
}
switch (alt220) {
case 1 :
// InternalSARL.g:8043:8: (lv_extension_3_0= 'extension' )
{
// InternalSARL.g:8043:8: (lv_extension_3_0= 'extension' )
// InternalSARL.g:8044:9: lv_extension_3_0= 'extension'
{
lv_extension_3_0=(Token)match(input,45,FOLLOW_3); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(lv_extension_3_0, grammarAccess.getXVariableDeclarationAccess().getExtensionExtensionKeyword_0_0_1_0_1_0());
}
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElement(grammarAccess.getXVariableDeclarationRule());
}
setWithLastConsumed(current, "extension", true, "extension");
}
}
}
break;
}
}
}
break;
case 2 :
// InternalSARL.g:8058:6: ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) )
{
// InternalSARL.g:8058:6: ( ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' ) )
// InternalSARL.g:8059:7: ( (lv_extension_4_0= 'extension' ) ) ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' )
{
// InternalSARL.g:8059:7: ( (lv_extension_4_0= 'extension' ) )
// InternalSARL.g:8060:8: (lv_extension_4_0= 'extension' )
{
// InternalSARL.g:8060:8: (lv_extension_4_0= 'extension' )
// InternalSARL.g:8061:9: lv_extension_4_0= 'extension'
{
lv_extension_4_0=(Token)match(input,45,FOLLOW_76); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(lv_extension_4_0, grammarAccess.getXVariableDeclarationAccess().getExtensionExtensionKeyword_0_0_1_1_0_0());
}
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElement(grammarAccess.getXVariableDeclarationRule());
}
setWithLastConsumed(current, "extension", true, "extension");
}
}
}
// InternalSARL.g:8073:7: ( ( (lv_writeable_5_0= 'var' ) ) | otherlv_6= 'val' )
int alt221=2;
int LA221_0 = input.LA(1);
if ( (LA221_0==65) ) {
alt221=1;
}
else if ( (LA221_0==66) ) {
alt221=2;
}
else {
if (state.backtracking>0) {state.failed=true; return current;}
NoViableAltException nvae =
new NoViableAltException("", 221, 0, input);
throw nvae;
}
switch (alt221) {
case 1 :
// InternalSARL.g:8074:8: ( (lv_writeable_5_0= 'var' ) )
{
// InternalSARL.g:8074:8: ( (lv_writeable_5_0= 'var' ) )
// InternalSARL.g:8075:9: (lv_writeable_5_0= 'var' )
{
// InternalSARL.g:8075:9: (lv_writeable_5_0= 'var' )
// InternalSARL.g:8076:10: lv_writeable_5_0= 'var'
{
lv_writeable_5_0=(Token)match(input,65,FOLLOW_3); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(lv_writeable_5_0, grammarAccess.getXVariableDeclarationAccess().getWriteableVarKeyword_0_0_1_1_1_0_0());
}
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElement(grammarAccess.getXVariableDeclarationRule());
}
setWithLastConsumed(current, "writeable", true, "var");
}
}
}
}
break;
case 2 :
// InternalSARL.g:8089:8: otherlv_6= 'val'
{
otherlv_6=(Token)match(input,66,FOLLOW_3); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_6, grammarAccess.getXVariableDeclarationAccess().getValKeyword_0_0_1_1_1_1());
}
}
break;
}
}
}
break;
}
}
}
// InternalSARL.g:8098:3: ( (lv_name_7_0= ruleValidID ) )
// InternalSARL.g:8099:4: (lv_name_7_0= ruleValidID )
{
// InternalSARL.g:8099:4: (lv_name_7_0= ruleValidID )
// InternalSARL.g:8100:5: lv_name_7_0= ruleValidID
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXVariableDeclarationAccess().getNameValidIDParserRuleCall_1_0());
}
pushFollow(FOLLOW_77);
lv_name_7_0=ruleValidID();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXVariableDeclarationRule());
}
set(
current,
"name",
lv_name_7_0,
"org.eclipse.xtend.core.Xtend.ValidID");
afterParserOrEnumRuleCall();
}
}
}
// InternalSARL.g:8117:3: (otherlv_8= ':' ( (lv_type_9_0= ruleJvmTypeReference ) ) )?
int alt223=2;
int LA223_0 = input.LA(1);
if ( (LA223_0==46) ) {
alt223=1;
}
switch (alt223) {
case 1 :
// InternalSARL.g:8118:4: otherlv_8= ':' ( (lv_type_9_0= ruleJvmTypeReference ) )
{
otherlv_8=(Token)match(input,46,FOLLOW_41); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_8, grammarAccess.getXVariableDeclarationAccess().getColonKeyword_2_0());
}
// InternalSARL.g:8122:4: ( (lv_type_9_0= ruleJvmTypeReference ) )
// InternalSARL.g:8123:5: (lv_type_9_0= ruleJvmTypeReference )
{
// InternalSARL.g:8123:5: (lv_type_9_0= ruleJvmTypeReference )
// InternalSARL.g:8124:6: lv_type_9_0= ruleJvmTypeReference
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXVariableDeclarationAccess().getTypeJvmTypeReferenceParserRuleCall_2_1_0());
}
pushFollow(FOLLOW_78);
lv_type_9_0=ruleJvmTypeReference();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXVariableDeclarationRule());
}
set(
current,
"type",
lv_type_9_0,
"org.eclipse.xtext.xbase.Xtype.JvmTypeReference");
afterParserOrEnumRuleCall();
}
}
}
}
break;
}
// InternalSARL.g:8142:3: (otherlv_10= '=' ( (lv_right_11_0= ruleXExpression ) ) )?
int alt224=2;
int LA224_0 = input.LA(1);
if ( (LA224_0==47) ) {
alt224=1;
}
switch (alt224) {
case 1 :
// InternalSARL.g:8143:4: otherlv_10= '=' ( (lv_right_11_0= ruleXExpression ) )
{
otherlv_10=(Token)match(input,47,FOLLOW_45); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_10, grammarAccess.getXVariableDeclarationAccess().getEqualsSignKeyword_3_0());
}
// InternalSARL.g:8147:4: ( (lv_right_11_0= ruleXExpression ) )
// InternalSARL.g:8148:5: (lv_right_11_0= ruleXExpression )
{
// InternalSARL.g:8148:5: (lv_right_11_0= ruleXExpression )
// InternalSARL.g:8149:6: lv_right_11_0= ruleXExpression
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXVariableDeclarationAccess().getRightXExpressionParserRuleCall_3_1_0());
}
pushFollow(FOLLOW_2);
lv_right_11_0=ruleXExpression();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXVariableDeclarationRule());
}
set(
current,
"right",
lv_right_11_0,
"org.eclipse.xtext.xbase.Xbase.XExpression");
afterParserOrEnumRuleCall();
}
}
}
}
break;
}
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} |
java | public void setUserAttributes(java.util.Collection<AttributeType> userAttributes) {
if (userAttributes == null) {
this.userAttributes = null;
return;
}
this.userAttributes = new java.util.ArrayList<AttributeType>(userAttributes);
} |
java | public com.squareup.okhttp.Call getUniversePlanetsPlanetIdAsync(Integer planetId, String datasource,
String ifNoneMatch, final ApiCallback<PlanetResponse> callback) throws ApiException {
com.squareup.okhttp.Call call = getUniversePlanetsPlanetIdValidateBeforeCall(planetId, datasource, ifNoneMatch,
callback);
Type localVarReturnType = new TypeToken<PlanetResponse>() {
}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} |
java | @Override
public LogProperties logProperties()
{
if (tc.isEntryEnabled())
Tr.entry(tc, "logProperties", this);
final LogProperties lprops = _recoveryLog.logProperties();
if (tc.isEntryEnabled())
Tr.exit(tc, "logProperties", lprops);
return lprops;
} |
java | protected final void run(Block block) {
if (stopping) {
return;
}
final Authentication auth = Jenkins.getAuthentication();
task = GeneralNonBlockingStepExecutionUtils.getExecutorService().submit(() -> {
threadName = Thread.currentThread().getName();
try {
try (ACLContext acl = ACL.as(auth)) {
block.run();
}
} catch (Throwable e) {
if (!stopping) {
getContext().onFailure(e);
}
} finally {
threadName = null;
task = null;
}
});
} |
java | @Override
public void addStatus(Status status) {
StatusManager sm = context.getStatusManager();
sm.add(status);
} |
java | public static int findIndexOf(Object self, int startIndex, Closure condition) {
return findIndexOf(InvokerHelper.asIterator(self), condition);
} |
java | @Override
public Double getUserItemPreference(U u, I i) {
if (userItemPreferences.containsKey(u) && userItemPreferences.get(u).containsKey(i)) {
return userItemPreferences.get(u).get(i);
}
return Double.NaN;
} |
python | def bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4",
scatter_size=10, fill_alpha=0.4, line_alpha=0.4,
court_line_color='gray', court_line_width=1,
hover_tool=False, tooltips=None, **kwargs):
# TODO: Settings for hover tooltip
"""
Returns a figure with both FGA and basketball court lines drawn onto it.
This function expects data to be a ColumnDataSource with the x and y values
named "LOC_X" and "LOC_Y". Otherwise specify x and y.
Parameters
----------
data : DataFrame
The DataFrame that contains the shot chart data.
x, y : str, optional
The x and y coordinates of the shots taken.
fill_color : str, optional
The fill color of the shots. Can be a a Hex value.
scatter_size : int, optional
The size of the dots for the scatter plot.
fill_alpha : float, optional
Alpha value for the shots. Must be a floating point value between 0
(transparent) to 1 (opaque).
line_alpha : float, optiona
Alpha value for the outer lines of the plotted shots. Must be a
floating point value between 0 (transparent) to 1 (opaque).
court_line_color : str, optional
The color of the court lines. Can be a a Hex value.
court_line_width : float, optional
The linewidth the of the court lines in pixels.
hover_tool : boolean, optional
If ``True``, creates hover tooltip for the plot.
tooltips : List of tuples, optional
Provides the information for the the hover tooltip.
Returns
-------
fig : Figure
The Figure object with the shot chart plotted on it.
"""
source = ColumnDataSource(data)
fig = figure(width=700, height=658, x_range=[-250, 250],
y_range=[422.5, -47.5], min_border=0, x_axis_type=None,
y_axis_type=None, outline_line_color="black", **kwargs)
fig.scatter(x, y, source=source, size=scatter_size, color=fill_color,
alpha=fill_alpha, line_alpha=line_alpha)
bokeh_draw_court(fig, line_color=court_line_color,
line_width=court_line_width)
if hover_tool:
hover = HoverTool(renderers=[fig.renderers[0]], tooltips=tooltips)
fig.add_tools(hover)
return fig |
python | def write_bsedebug(basis):
'''Converts a basis set to BSE Debug format
'''
s = ''
for el, eldata in basis['elements'].items():
s += element_data_str(el, eldata)
return s |
python | def load(obj, env=None, silent=True, key=None):
"""Loads envvars with prefixes:
`DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_`
"""
global_env = obj.get("ENVVAR_PREFIX_FOR_DYNACONF")
if global_env is False or global_env.upper() != "DYNACONF":
load_from_env(IDENTIFIER + "_global", key, "DYNACONF", obj, silent)
# Load the global env if exists and overwrite everything
load_from_env(IDENTIFIER + "_global", key, global_env, obj, silent) |
python | def info(self):
"""Delivers some info to you about the class."""
print("Sorry, but I don't have much to share.")
print("This is me:")
print(self)
print("And these are the experiments assigned to me:")
print(self.experiments) |
python | def pipe_value(self, message):
'Send a new value into the ws pipe'
jmsg = json.dumps(message)
self.send(jmsg) |
java | public Observable<ServiceResponse<List<String>>> listDomainsWithServiceResponseAsync() {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
}
String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
return service.listDomains(this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<List<String>>>>() {
@Override
public Observable<ServiceResponse<List<String>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<List<String>> clientResponse = listDomainsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} |
python | def subset(self, used_indices, params=None):
"""Get subset of current Dataset.
Parameters
----------
used_indices : list of int
Indices used to create the subset.
params : dict or None, optional (default=None)
These parameters will be passed to Dataset constructor.
Returns
-------
subset : Dataset
Subset of the current Dataset.
"""
if params is None:
params = self.params
ret = Dataset(None, reference=self, feature_name=self.feature_name,
categorical_feature=self.categorical_feature, params=params,
free_raw_data=self.free_raw_data)
ret._predictor = self._predictor
ret.pandas_categorical = self.pandas_categorical
ret.used_indices = used_indices
return ret |
java | public static void log(final Level level, final Throwable exception, final String message) {
String nameOfException = exception.getClass().getName();
String messageOfException = exception.getMessage();
StringBuilder builder = new StringBuilder(BUFFER_SIZE);
builder.append(level);
builder.append(": ");
builder.append(message);
builder.append(" (");
builder.append(nameOfException);
if (messageOfException != null && !messageOfException.isEmpty()) {
builder.append(": ");
builder.append(messageOfException);
}
builder.append(")");
System.err.println(builder);
} |
java | public Vector2f lerp(Vector2fc other, float t, Vector2f dest) {
dest.x = x + (other.x() - x) * t;
dest.y = y + (other.y() - y) * t;
return dest;
} |
java | public static List<KeyedStateHandle> getManagedKeyedStateHandles(
OperatorState operatorState,
KeyGroupRange subtaskKeyGroupRange) {
final int parallelism = operatorState.getParallelism();
List<KeyedStateHandle> subtaskKeyedStateHandles = null;
for (int i = 0; i < parallelism; i++) {
if (operatorState.getState(i) != null) {
Collection<KeyedStateHandle> keyedStateHandles = operatorState.getState(i).getManagedKeyedState();
if (subtaskKeyedStateHandles == null) {
subtaskKeyedStateHandles = new ArrayList<>(parallelism * keyedStateHandles.size());
}
extractIntersectingState(
keyedStateHandles,
subtaskKeyGroupRange,
subtaskKeyedStateHandles);
}
}
return subtaskKeyedStateHandles;
} |
java | private Predicate<HelpPage> query(final Predicate<HelpPage> predicate) {
Predicate<HelpPage> query = predicate;
if (includeAll == null || !includeAll) {
if (includeAliases != null && !includeAliases) {
query = query.and(TypePredicate.of(AliasHelpPage.class).negate());
}
if (includeMeta != null && !includeMeta) {
query = query.and(TypePredicate.of(MetaHelpPage.class).negate());
}
if (includeCommands != null && !includeCommands) {
query = query.and(TypePredicate.of(CommandHelpPage.class).negate());
}
if (includeGroups != null && !includeGroups) {
query = query.and(TypePredicate.of(GroupHelpPage.class).negate());
}
}
return query;
} |
python | def get_sorted_source_files(
self,
source_filenames_or_globs: Union[str, List[str]],
recursive: bool = True) -> List[str]:
"""
Returns a sorted list of filenames to process, from a filename,
a glob string, or a list of filenames/globs.
Args:
source_filenames_or_globs: filename/glob, or list of them
recursive: use :func:`glob.glob` in recursive mode?
Returns:
sorted list of files to process
"""
if isinstance(source_filenames_or_globs, str):
source_filenames_or_globs = [source_filenames_or_globs]
final_filenames = [] # type: List[str]
for sfg in source_filenames_or_globs:
sfg_expanded = expanduser(sfg)
log.debug("Looking for: {!r}", sfg_expanded)
for filename in glob.glob(sfg_expanded, recursive=recursive):
log.debug("Trying: {!r}", filename)
if self.should_exclude(filename):
log.info("Skipping file {!r}", filename)
continue
final_filenames.append(filename)
final_filenames.sort()
return final_filenames |
python | def isordv(array, n):
"""
Determine whether an array of n items contains the integers
0 through n-1.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isordv_c.html
:param array: Array of integers.
:type array: Array of ints
:param n: Number of integers in array.
:type n: int
:return:
The function returns True if the array contains the
integers 0 through n-1, otherwise it returns False.
:rtype: bool
"""
array = stypes.toIntVector(array)
n = ctypes.c_int(n)
return bool(libspice.isordv_c(array, n)) |
java | public static <T> Collection<T> reject(
Iterable<T> iterable,
Predicate<? super T> predicate,
boolean allowReorderedResult)
{
return ParallelIterate.reject(iterable, predicate, null, allowReorderedResult);
} |
python | def sort_servers_closest(servers: Sequence[str]) -> Sequence[Tuple[str, float]]:
"""Sorts a list of servers by http round-trip time
Params:
servers: sequence of http server urls
Returns:
sequence of pairs of url,rtt in seconds, sorted by rtt, excluding failed servers
(possibly empty)
"""
if not {urlparse(url).scheme for url in servers}.issubset({'http', 'https'}):
raise TransportError('Invalid server urls')
get_rtt_jobs = set(
gevent.spawn(lambda url: (url, get_http_rtt(url)), server_url)
for server_url
in servers
)
# these tasks should never raise, returns None on errors
gevent.joinall(get_rtt_jobs, raise_error=False) # block and wait tasks
sorted_servers: List[Tuple[str, float]] = sorted(
(job.value for job in get_rtt_jobs if job.value[1] is not None),
key=itemgetter(1),
)
log.debug('Matrix homeserver RTT times', rtt_times=sorted_servers)
return sorted_servers |
java | @Override
public Object render(Map<String, Object> context, LNode... nodes) {
// The group-name is either the first token-expression, or if that is
// null (indicating there is no name), give it the name PREPEND followed
// by the number of expressions in the cycle-group.
String groupName = nodes[0] == null ?
PREPEND + (nodes.length - 1) :
super.asString(nodes[0].render(context));
// Prepend a groupName with a single- and double quote as to not
// let the groupName conflict with other variable assignments
groupName = PREPEND + groupName;
Object obj = context.remove(groupName);
List<Object> elements = new ArrayList<Object>();
for (int i = 1; i < nodes.length; i++) {
elements.add(nodes[i].render(context));
}
CycleGroup group;
if (obj == null) {
group = new CycleGroup(elements.size());
}
else {
group = (CycleGroup) obj;
}
context.put(groupName, group);
return group.next(elements);
} |
python | def parse_point_source_node(node, mfd_spacing=0.1):
"""
Returns an "areaSource" node into an instance of the :class:
openquake.hmtk.sources.area.mtkAreaSource
"""
assert "pointSource" in node.tag
pnt_taglist = get_taglist(node)
# Get metadata
point_id, name, trt = (node.attrib["id"],
node.attrib["name"],
node.attrib["tectonicRegion"])
assert point_id # Defensive validation!
# Process geometry
location, upper_depth, lower_depth = node_to_point_geometry(
node.nodes[pnt_taglist.index("pointGeometry")])
# Process scaling relation
msr = node_to_scalerel(node.nodes[pnt_taglist.index("magScaleRel")])
# Process aspect ratio
aspect = float_(node.nodes[pnt_taglist.index("ruptAspectRatio")].text)
# Process MFD
mfd = node_to_mfd(node, pnt_taglist)
# Process nodal planes
npds = node_to_nodal_planes(
node.nodes[pnt_taglist.index("nodalPlaneDist")])
# Process hypocentral depths
hdds = node_to_hdd(node.nodes[pnt_taglist.index("hypoDepthDist")])
return mtkPointSource(point_id, name, trt,
geometry=location,
upper_depth=upper_depth,
lower_depth=lower_depth,
mag_scale_rel=msr,
rupt_aspect_ratio=aspect,
mfd=mfd,
nodal_plane_dist=npds,
hypo_depth_dist=hdds) |
python | def flush(self):
"""Synchronously wait until this work item is processed.
This has the effect of waiting until all work items queued before this
method has been called have finished.
"""
done = threading.Event()
def _callback():
done.set()
self.defer(_callback)
done.wait() |
java | private static String firstCharToLowerCase(String word) {
if (word.length() == 1) {
return word.toLowerCase();
}
char c = word.charAt(0);
char newChar;
if (c >= 'A' && c <= 'Z') {
newChar = (char) (c + 32);
}
else {
newChar = c;
}
return newChar + word.substring(1);
} |
python | def update_by_function(self, extra_doc, index, doc_type, id, querystring_args=None,
update_func=None, attempts=2):
"""
Update an already indexed typed JSON document.
The update happens client-side, i.e. the current document is retrieved,
updated locally and finally pushed to the server. This may repeat up to
``attempts`` times in case of version conflicts.
:param update_func: A callable ``update_func(current_doc, extra_doc)``
that computes and returns the updated doc. Alternatively it may
update ``current_doc`` in place and return None. The default
``update_func`` is ``dict.update``.
:param attempts: How many times to retry in case of version conflict.
"""
if querystring_args is None:
querystring_args = {}
if update_func is None:
update_func = dict.update
for attempt in range(attempts - 1, -1, -1):
current_doc = self.get(index, doc_type, id, **querystring_args)
new_doc = update_func(current_doc, extra_doc)
if new_doc is None:
new_doc = current_doc
try:
return self.index(new_doc, index, doc_type, id,
version=current_doc._meta.version, querystring_args=querystring_args)
except VersionConflictEngineException:
if attempt <= 0:
raise
self.refresh(index) |
java | @Deprecated
public ServerBuilder port(int port, String protocol) {
return port(port, SessionProtocol.of(requireNonNull(protocol, "protocol")));
} |
python | def get_rows(runSetResults):
"""
Create list of rows with all data. Each row consists of several RunResults.
"""
rows = []
for task_results in zip(*[runset.results for runset in runSetResults]):
rows.append(Row(task_results))
return rows |
python | def loads(s, cls=None, **kwargs):
"""Load string"""
if not isinstance(s, string_types):
raise TypeError('the YAML object must be str, not {0!r}'.format(s.__class__.__name__))
cls = cls or YAMLDecoder
return cls(**kwargs).decode(s) |
python | def convertTimestamps(column):
"""Convert a dtype of a given column to a datetime.
This method tries to do this by brute force.
Args:
column (pandas.Series): A Series object with all rows.
Returns:
column: Converted to datetime if no errors occured, else the
original column will be returned.
"""
tempColumn = column
try:
# Try to convert the first row and a random row instead of the complete
# column, might be faster
# tempValue = np.datetime64(column[0])
tempValue = np.datetime64(column[randint(0, len(column.index) - 1)])
tempColumn = column.apply(to_datetime)
except Exception:
pass
return tempColumn |
java | @Benchmark
public ExampleInterface baseline() {
return new ExampleInterface() {
public boolean method(boolean arg) {
return false;
}
public byte method(byte arg) {
return 0;
}
public short method(short arg) {
return 0;
}
public int method(int arg) {
return 0;
}
public char method(char arg) {
return 0;
}
public long method(long arg) {
return 0;
}
public float method(float arg) {
return 0;
}
public double method(double arg) {
return 0;
}
public Object method(Object arg) {
return null;
}
public boolean[] method(boolean arg1, boolean arg2, boolean arg3) {
return null;
}
public byte[] method(byte arg1, byte arg2, byte arg3) {
return null;
}
public short[] method(short arg1, short arg2, short arg3) {
return null;
}
public int[] method(int arg1, int arg2, int arg3) {
return null;
}
public char[] method(char arg1, char arg2, char arg3) {
return null;
}
public long[] method(long arg1, long arg2, long arg3) {
return null;
}
public float[] method(float arg1, float arg2, float arg3) {
return null;
}
public double[] method(double arg1, double arg2, double arg3) {
return null;
}
public Object[] method(Object arg1, Object arg2, Object arg3) {
return null;
}
};
} |
java | public static base_response flush(nitro_service client, nssimpleacl resource) throws Exception {
nssimpleacl flushresource = new nssimpleacl();
flushresource.estsessions = resource.estsessions;
return flushresource.perform_operation(client,"flush");
} |
python | async def spawn(self, agent_cls, *args, addr=None, **kwargs):
"""Spawn a new agent in a slave environment.
:param str agent_cls:
`qualname`` of the agent class.
That is, the name should be in the form ``pkg.mod:cls``, e.g.
``creamas.core.agent:CreativeAgent``.
:param str addr:
Optional. Address for the slave enviroment's manager.
If :attr:`addr` is None, spawns the agent in the slave environment
with currently smallest number of agents.
:returns: :class:`aiomas.rpc.Proxy` and address for the created agent.
The ``*args`` and ``**kwargs`` are passed down to the agent's
:meth:`__init__`.
.. note::
Use :meth:`~creamas.mp.MultiEnvironment.spawn_n` to spawn large
number of agents with identical initialization parameters.
"""
if addr is None:
addr = await self._get_smallest_env()
r_manager = await self.env.connect(addr)
return await r_manager.spawn(agent_cls, *args, **kwargs) |
python | def render_payment_form(self):
"""Display the DirectPayment for entering payment information."""
self.context[self.form_context_name] = self.payment_form_cls()
return TemplateResponse(self.request, self.payment_template, self.context) |
java | public void info( String msg, Throwable t )
{
if( m_delegate.isInfoEnabled() )
{
m_delegate.inform( msg, t );
}
} |
python | def from_fqdn(cls, fqdn):
"""Retrieve domain id associated to a FQDN."""
result = cls.list({'fqdn': fqdn})
if len(result) > 0:
return result[0]['id'] |
java | @SuppressWarnings("unchecked")
private final void instantiateDeserializationUtils() {
if (this.serializers == null) {
this.serializers = new TypeSerializer[this.serializerFactories.length];
for (int i = 0; i < this.serializers.length; i++) {
this.serializers[i] = this.serializerFactories[i].getSerializer();
}
}
this.deserializedFields1 = new Object[this.serializers.length];
this.deserializedFields2 = new Object[this.serializers.length];
for (int i = 0; i < this.serializers.length; i++) {
this.deserializedFields1[i] = this.serializers[i].createInstance();
this.deserializedFields2[i] = this.serializers[i].createInstance();
}
} |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'types') and self.types is not None:
_dict['types'] = [x._to_dict() for x in self.types]
if hasattr(self, 'categories') and self.categories is not None:
_dict['categories'] = [x._to_dict() for x in self.categories]
return _dict |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.