language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public Observable<Void> beginScanForUpdatesAsync(String deviceName, String resourceGroupName) {
return beginScanForUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} |
python | def getpad(self):
"""Get pad value of DataBatch."""
if self.last_batch_handle == 'pad' and \
self.cursor + self.batch_size > self.num_data:
return self.cursor + self.batch_size - self.num_data
# check the first batch
elif self.last_batch_handle == 'roll_over' and \
-self.batch_size < self.cursor < 0:
return -self.cursor
else:
return 0 |
python | async def create(self, config: dict = None, access: str = None, replace: bool = False) -> Wallet:
"""
Create wallet on input name with given configuration and access credential value.
Raise ExtantWallet if wallet on input name exists already and replace parameter is False.
Raise BadAccess on replacement for bad access credentials value.
FAIR WARNING: specifying replace=True attempts to remove any matching wallet before proceeding; to
succeed, the existing wallet must use the same access credentials that the input configuration has.
:param config: configuration data for both indy-sdk and VON anchor wallet:
- 'name' or 'id': wallet name
- 'storage_type': storage type
- 'freshness_time': freshness time
- 'did': (optional) DID to use
- 'seed': (optional) seed to use
- 'auto_create': whether to create the wallet on first open (persists past close, can work with auto_remove)
- 'auto_remove': whether to remove the wallet on next close
- 'link_secret_label': (optional) link secret label to use to create link secret
:param access: indy wallet access credential ('key') value, if different than default
:param replace: whether to replace old wallet if it exists
:return: wallet created
"""
LOGGER.debug('WalletManager.create >>> config %s, access %s, replace %s', config, access, replace)
assert {'name', 'id'} & {k for k in config}
wallet_name = config.get('name', config.get('id'))
if replace:
von_wallet = self.get(config, access)
if not await von_wallet.remove():
LOGGER.debug('WalletManager.create <!< Failed to remove wallet %s for replacement', wallet_name)
raise ExtantWallet('Failed to remove wallet {} for replacement'.format(wallet_name))
indy_config = self._config2indy(config)
von_config = self._config2von(config, access)
rv = Wallet(indy_config, von_config)
await rv.create()
LOGGER.debug('WalletManager.create <<< %s', rv)
return rv |
java | private Stream<Numeric> runComputeMean(GraqlCompute.Statistics.Value query) {
Map<String, Double> meanPair = runComputeStatistics(query);
if (meanPair == null) return Stream.empty();
Double mean = meanPair.get(MeanMapReduce.SUM) / meanPair.get(MeanMapReduce.COUNT);
return Stream.of(new Numeric(mean));
} |
python | def run_ipython_notebook(notebook_str):
"""
References:
https://github.com/paulgb/runipy
>>> from utool.util_ipynb import * # NOQA
"""
from runipy.notebook_runner import NotebookRunner
import nbformat
import logging
log_format = '%(asctime)s %(levelname)s: %(message)s'
log_datefmt = '%m/%d/%Y %I:%M:%S %p'
logging.basicConfig(
level=logging.INFO, format=log_format, datefmt=log_datefmt
)
#fpath = 'tmp.ipynb'
#notebook_str = ut.readfrom(fpath)
#nb3 = IPython.nbformat.reads(notebook_str, 3)
#cell = nb4.cells[1]
#self = runner
#runner = NotebookRunner(nb3, mpl_inline=True)
print('Executing IPython notebook')
nb4 = nbformat.reads(notebook_str, 4)
runner = NotebookRunner(nb4)
runner.run_notebook(skip_exceptions=False)
run_nb = runner.nb
return run_nb |
java | @GetMapping(path = "/instances/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<ResponseEntity<Instance>> instance(@PathVariable String id) {
LOGGER.debug("Deliver registered instance with ID '{}'", id);
return registry.getInstance(InstanceId.of(id))
.filter(Instance::isRegistered)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
} |
java | private ControlFlushed createControlFlushed(SIBUuid8 target, SIBUuid12 stream)
throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "createControlFlushed", stream);
ControlFlushed flushedMsg;
// Create new message
try
{
flushedMsg = _cmf.createNewControlFlushed();
}
catch (MessageCreateFailedException e)
{
// FFDC
FFDCFilter.processException(
e,
"com.ibm.ws.sib.processor.impl.PubSubOutputHandler.createControlFlushed",
"1:1424:1.164.1.5",
this);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
{
SibTr.exception(tc, e);
SibTr.exit(tc, "createControlFlushed", e);
}
SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.impl.PubSubOutputHandler",
"1:1436:1.164.1.5",
e });
throw new SIResourceException(
nls.getFormattedMessage(
"INTERNAL_MESSAGING_ERROR_CWSIP0002",
new Object[] {
"com.ibm.ws.sib.processor.impl.PubSubOutputHandler",
"1:1444:1.164.1.5",
e },
null),
e);
}
// As we are using the Guaranteed Header - set all the attributes as
// well as the ones we want.
SIMPUtils.setGuaranteedDeliveryProperties(flushedMsg,
_messageProcessor.getMessagingEngineUuid(),
null,
stream,
null,
_destinationHandler.getUuid(),
ProtocolType.PUBSUBINPUT,
GDConfig.PROTOCOL_VERSION);
flushedMsg.setPriority(SIMPConstants.CTRL_MSG_PRIORITY);
flushedMsg.setReliability(Reliability.ASSURED_PERSISTENT);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createControlFlushed");
return flushedMsg;
} |
python | def do_forget(self, repo):
'''
Drop definition of a repo.
forget REPO
'''
self.abort_on_nonexisting_repo(repo, 'forget')
self.network.forget(repo) |
java | public static Transform createRotateTransform(float angle) {
return new Transform((float)FastTrig.cos(angle), -(float)FastTrig.sin(angle), 0, (float)FastTrig.sin(angle), (float)FastTrig.cos(angle), 0);
} |
java | @SuppressWarnings("unchecked")
private boolean hasPropertiesConfiguration(Dictionary properties) {
HashMap<Object, Object> mapProperties = new HashMap<Object, Object>(properties.size());
for (Object key : Collections.list(properties.keys())) {
mapProperties.put(key, properties.get(key));
}
mapProperties.remove(Constants.SERVICE_PID);
mapProperties.remove("service.factoryPid");
return !mapProperties.isEmpty();
} |
java | public static boolean isSecure(URI uri) {
Objects.requireNonNull(uri, "uri must not be null");
return uri.getScheme().equals("wss") || uri.getScheme().equals("https");
} |
python | def collapse_short_branches(self, threshold):
'''Collapse internal branches (not terminal branches) with length less than or equal to ``threshold``. A branch length of ``None`` is considered 0
Args:
``threshold`` (``float``): The threshold to use when collapsing branches
'''
if not isinstance(threshold,float) and not isinstance(threshold,int):
raise RuntimeError("threshold must be an integer or a float")
elif threshold < 0:
raise RuntimeError("threshold cannot be negative")
q = deque(); q.append(self.root)
while len(q) != 0:
next = q.popleft()
if next.edge_length is None or next.edge_length <= threshold:
if next.is_root():
next.edge_length = None
elif not next.is_leaf():
parent = next.parent; parent.remove_child(next)
for c in next.children:
parent.add_child(c)
q.extend(next.children) |
java | public CORSConfigBuilder withAllowedHeaders(String... headerNames) {
Mutils.notNull("headerNames", headerNames);
return withAllowedHeaders(asList(headerNames));
} |
python | def sleep(duration):
"""Return a `.Future` that resolves after the given number of seconds.
When used with ``yield`` in a coroutine, this is a non-blocking
analogue to `time.sleep` (which should not be used in coroutines
because it is blocking)::
yield gen.sleep(0.5)
Note that calling this function on its own does nothing; you must
wait on the `.Future` it returns (usually by yielding it).
.. versionadded:: 4.1
"""
f = Future()
IOLoop.current().call_later(duration, lambda: f.set_result(None))
return f |
java | public String getContentTypeWithVersion() {
if (!StringUtils.hasText(this.contentTypeTemplate)
|| !StringUtils.hasText(this.version)) {
return "";
}
return this.contentTypeTemplate.replaceAll(VERSION_PLACEHOLDER_REGEX,
this.version);
} |
java | public static GoogleJsonError parse(JsonFactory jsonFactory, HttpResponse response)
throws IOException {
JsonObjectParser jsonObjectParser = new JsonObjectParser.Builder(jsonFactory).setWrapperKeys(
Collections.singleton("error")).build();
return jsonObjectParser.parseAndClose(
response.getContent(), response.getContentCharset(), GoogleJsonError.class);
} |
java | public static BeanBox value(Object value) {
return new BeanBox().setTarget(value).setPureValue(true).setRequired(true);
} |
python | def format_message(self, msg, botreply=False):
"""Format a user's message for safe processing.
This runs substitutions on the message and strips out any remaining
symbols (depending on UTF-8 mode).
:param str msg: The user's message.
:param bool botreply: Whether this formatting is being done for the
bot's last reply (e.g. in a ``%Previous`` command).
:return str: The formatted message.
"""
# Make sure the string is Unicode for Python 2.
if sys.version_info[0] < 3 and isinstance(msg, str):
msg = msg.decode()
# Lowercase it.
msg = msg.lower()
# Run substitutions on it.
msg = self.substitute(msg, "sub")
# In UTF-8 mode, only strip metacharacters and HTML brackets
# (to protect from obvious XSS attacks).
if self.utf8:
msg = re.sub(RE.utf8_meta, '', msg)
msg = re.sub(self.master.unicode_punctuation, '', msg)
# For the bot's reply, also strip common punctuation.
if botreply:
msg = re.sub(RE.utf8_punct, '', msg)
else:
# For everything else, strip all non-alphanumerics.
msg = utils.strip_nasties(msg)
msg = msg.strip() # Strip leading and trailing white space
msg = RE.ws.sub(" ",msg) # Replace the multiple whitespaces by single whitespace
return msg |
java | public static Object selectMethod(MutableCallSite callSite, Class sender, String methodName, int callID, Boolean safeNavigation, Boolean thisCall, Boolean spreadCall, Object dummyReceiver, Object[] arguments) throws Throwable {
Selector selector = Selector.getSelector(callSite, sender, methodName, callID, safeNavigation, thisCall, spreadCall, arguments);
selector.setCallSiteTarget();
MethodHandle call = selector.handle.asSpreader(Object[].class, arguments.length);
call = call.asType(MethodType.methodType(Object.class,Object[].class));
return call.invokeExact(arguments);
} |
java | public Observable<JobInner> getAsync(String resourceGroupName, String workspaceName, String experimentName, String jobName) {
return getWithServiceResponseAsync(resourceGroupName, workspaceName, experimentName, jobName).map(new Func1<ServiceResponse<JobInner>, JobInner>() {
@Override
public JobInner call(ServiceResponse<JobInner> response) {
return response.body();
}
});
} |
java | public void marshall(Environment environment, ProtocolMarshaller protocolMarshaller) {
if (environment == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(environment.getId(), ID_BINDING);
protocolMarshaller.marshall(environment.getName(), NAME_BINDING);
protocolMarshaller.marshall(environment.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(environment.getType(), TYPE_BINDING);
protocolMarshaller.marshall(environment.getArn(), ARN_BINDING);
protocolMarshaller.marshall(environment.getOwnerArn(), OWNERARN_BINDING);
protocolMarshaller.marshall(environment.getLifecycle(), LIFECYCLE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def cublasZtpsv(handle, uplo, trans, diag, n, AP, x, incx):
"""
Solve complex triangular-packed system with one right-hand size.
"""
status = _libcublas.cublasZtpsv_v2(handle,
_CUBLAS_FILL_MODE[uplo],
_CUBLAS_OP[trans],
_CUBLAS_DIAG[diag],
n, int(AP), int(x), incx)
cublasCheckStatus(status) |
python | def delete_boot_script(self):
"""
::
DELETE /:login/machines/:id/metadata/user-script
Deletes any existing boot script on the machine.
"""
j, r = self.datacenter.request('DELETE', self.path +
'/metadata/user-script')
r.raise_for_status()
self.boot_script = None |
python | def from_bundle(cls, b, feature):
"""
Initialize a Spot feature from the bundle.
"""
feature_ps = b.get_feature(feature)
colat = feature_ps.get_value('colat', unit=u.rad)
longitude = feature_ps.get_value('long', unit=u.rad)
if len(b.hierarchy.get_stars())>=2:
star_ps = b.get_component(feature_ps.component)
orbit_ps = b.get_component(b.hierarchy.get_parent_of(feature_ps.component))
syncpar = star_ps.get_value('syncpar')
period = orbit_ps.get_value('period')
dlongdt = (syncpar - 1) / period * 2 * np.pi
else:
star_ps = b.get_component(feature_ps.component)
dlongdt = star_ps.get_value('freq', unit=u.rad/u.d)
longitude = np.pi/2
radius = feature_ps.get_value('radius', unit=u.rad)
relteff = feature_ps.get_value('relteff', unit=u.dimensionless_unscaled)
t0 = b.get_value('t0', context='system', unit=u.d)
return cls(colat, longitude, dlongdt, radius, relteff, t0) |
python | def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Renders `data` into serialized YAML.
"""
assert yaml, 'YAMLRenderer requires pyyaml to be installed'
if data is None:
return ''
return yaml.dump(
data,
stream=None,
encoding=self.charset,
Dumper=self.encoder,
allow_unicode=not self.ensure_ascii,
default_flow_style=self.default_flow_style
) |
java | public RTPFormats negotiateApplication(SessionDescription sdp, RTPFormats formats) {
this.application.clean();
MediaDescriptorField descriptor = sdp.getApplicationDescriptor();
descriptor.getFormats().intersection(formats, this.application);
return this.application;
} |
python | def _install_from_path(path):
'''
Internal function to install a package from the given path
'''
if not os.path.exists(path):
msg = 'File not found: {0}'.format(path)
raise SaltInvocationError(msg)
cmd = 'installer -pkg "{0}" -target /'.format(path)
return salt.utils.mac_utils.execute_return_success(cmd) |
java | public Vector3f getRow(int row, Vector3f dest) throws IndexOutOfBoundsException {
switch (row) {
case 0:
dest.x = m00;
dest.y = m10;
dest.z = m20;
break;
case 1:
dest.x = m01;
dest.y = m11;
dest.z = m21;
break;
case 2:
dest.x = m02;
dest.y = m12;
dest.z = m22;
break;
default:
throw new IndexOutOfBoundsException();
}
return dest;
} |
python | def create_volume(self, availability_zone, size=None, snapshot_id=None):
"""Create a new volume."""
params = {"AvailabilityZone": availability_zone}
if ((snapshot_id is None and size is None) or
(snapshot_id is not None and size is not None)):
raise ValueError("Please provide either size or snapshot_id")
if size is not None:
params["Size"] = str(size)
if snapshot_id is not None:
params["SnapshotId"] = snapshot_id
query = self.query_factory(
action="CreateVolume", creds=self.creds, endpoint=self.endpoint,
other_params=params)
d = query.submit()
return d.addCallback(self.parser.create_volume) |
python | def do_check(pool,request,models,include_children_for,modelgb):
"request is the output of translate_check. models a dict of {(model_name,pkey_tuple):model}.\
ICF is a {model_name:fields_list} for which we want to add nulls in request for missing children. see AMC for how it's used.\
The caller should have gone through the same ICF logic when looking up models so the arg has all the refs the DB knows.\
modelgb is misc.GetterBy<ModelInfo>, used by AMC for resolution."
add_missing_children(models,request,include_children_for,modelgb)
return {k:fkapply(models,pool,process_check,None,k,v) for k,v in request.items()} |
java | private int indexOf(int key) {
int startIndex = hashIndex(key);
int index = startIndex;
for (;;) {
if (values[index] == null) {
// It's available, so no chance that this value exists anywhere in the map.
return -1;
}
if (key == keys[index]) {
return index;
}
// Conflict, keep probing ...
if ((index = probeNext(index)) == startIndex) {
return -1;
}
}
} |
java | public final EObject ruleAntlrGrammar() throws RecognitionException {
EObject current = null;
Token otherlv_0=null;
Token lv_name_1_0=null;
Token otherlv_2=null;
EObject lv_options_3_0 = null;
EObject lv_rules_4_0 = null;
enterRule();
try {
// InternalSimpleAntlr.g:85:28: ( (otherlv_0= 'grammar' ( (lv_name_1_0= RULE_ID ) ) otherlv_2= ';' ( (lv_options_3_0= ruleOptions ) )? ( (lv_rules_4_0= ruleRule ) )* ) )
// InternalSimpleAntlr.g:86:1: (otherlv_0= 'grammar' ( (lv_name_1_0= RULE_ID ) ) otherlv_2= ';' ( (lv_options_3_0= ruleOptions ) )? ( (lv_rules_4_0= ruleRule ) )* )
{
// InternalSimpleAntlr.g:86:1: (otherlv_0= 'grammar' ( (lv_name_1_0= RULE_ID ) ) otherlv_2= ';' ( (lv_options_3_0= ruleOptions ) )? ( (lv_rules_4_0= ruleRule ) )* )
// InternalSimpleAntlr.g:86:3: otherlv_0= 'grammar' ( (lv_name_1_0= RULE_ID ) ) otherlv_2= ';' ( (lv_options_3_0= ruleOptions ) )? ( (lv_rules_4_0= ruleRule ) )*
{
otherlv_0=(Token)match(input,13,FOLLOW_3); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_0, grammarAccess.getAntlrGrammarAccess().getGrammarKeyword_0());
}
// InternalSimpleAntlr.g:90:1: ( (lv_name_1_0= RULE_ID ) )
// InternalSimpleAntlr.g:91:1: (lv_name_1_0= RULE_ID )
{
// InternalSimpleAntlr.g:91:1: (lv_name_1_0= RULE_ID )
// InternalSimpleAntlr.g:92:3: lv_name_1_0= RULE_ID
{
lv_name_1_0=(Token)match(input,RULE_ID,FOLLOW_4); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(lv_name_1_0, grammarAccess.getAntlrGrammarAccess().getNameIDTerminalRuleCall_1_0());
}
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElement(grammarAccess.getAntlrGrammarRule());
}
setWithLastConsumed(
current,
"name",
lv_name_1_0,
"org.eclipse.xtext.generator.parser.antlr.debug.SimpleAntlr.ID");
}
}
}
otherlv_2=(Token)match(input,14,FOLLOW_5); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_2, grammarAccess.getAntlrGrammarAccess().getSemicolonKeyword_2());
}
// InternalSimpleAntlr.g:112:1: ( (lv_options_3_0= ruleOptions ) )?
int alt1=2;
int LA1_0 = input.LA(1);
if ( (LA1_0==15) ) {
alt1=1;
}
switch (alt1) {
case 1 :
// InternalSimpleAntlr.g:113:1: (lv_options_3_0= ruleOptions )
{
// InternalSimpleAntlr.g:113:1: (lv_options_3_0= ruleOptions )
// InternalSimpleAntlr.g:114:3: lv_options_3_0= ruleOptions
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getAntlrGrammarAccess().getOptionsOptionsParserRuleCall_3_0());
}
pushFollow(FOLLOW_6);
lv_options_3_0=ruleOptions();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getAntlrGrammarRule());
}
set(
current,
"options",
lv_options_3_0,
"org.eclipse.xtext.generator.parser.antlr.debug.SimpleAntlr.Options");
afterParserOrEnumRuleCall();
}
}
}
break;
}
// InternalSimpleAntlr.g:130:3: ( (lv_rules_4_0= ruleRule ) )*
loop2:
do {
int alt2=2;
int LA2_0 = input.LA(1);
if ( (LA2_0==RULE_ID||LA2_0==19) ) {
alt2=1;
}
switch (alt2) {
case 1 :
// InternalSimpleAntlr.g:131:1: (lv_rules_4_0= ruleRule )
{
// InternalSimpleAntlr.g:131:1: (lv_rules_4_0= ruleRule )
// InternalSimpleAntlr.g:132:3: lv_rules_4_0= ruleRule
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getAntlrGrammarAccess().getRulesRuleParserRuleCall_4_0());
}
pushFollow(FOLLOW_6);
lv_rules_4_0=ruleRule();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getAntlrGrammarRule());
}
add(
current,
"rules",
lv_rules_4_0,
"org.eclipse.xtext.generator.parser.antlr.debug.SimpleAntlr.Rule");
afterParserOrEnumRuleCall();
}
}
}
break;
default :
break loop2;
}
} while (true);
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
} |
java | public final void pinsrw(MMRegister dst, Register src, Immediate imm8)
{
emitX86(INST_PINSRW, dst, src, imm8);
} |
python | def ciphertext_length(header, plaintext_length):
"""Calculates the complete ciphertext message length, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:param int plaintext_length: Length of plaintext in bytes
:rtype: int
"""
ciphertext_length = header_length(header)
ciphertext_length += body_length(header, plaintext_length)
ciphertext_length += footer_length(header)
return ciphertext_length |
java | public void invalidate() {
synchronized (mMeasuredChildren) {
Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "invalidate all [%d]", mMeasuredChildren.size());
mMeasuredChildren.clear();
}
} |
java | public Observable<Page<WorkspaceInner>> listByResourceGroupAsync(final String resourceGroupName) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName)
.map(new Func1<ServiceResponse<Page<WorkspaceInner>>, Page<WorkspaceInner>>() {
@Override
public Page<WorkspaceInner> call(ServiceResponse<Page<WorkspaceInner>> response) {
return response.body();
}
});
} |
java | public JSONObject getLogs(int offset, int length, LogType logType, RequestOptions requestOptions) throws AlgoliaException {
String type = null;
switch (logType) {
case LOG_BUILD:
type = "build";
break;
case LOG_QUERY:
type = "query";
break;
case LOG_ERROR:
type = "error";
break;
case LOG_ALL:
type = "all";
break;
}
return getRequest("/1/logs?offset=" + offset + "&length=" + length + "&type=" + type, false, requestOptions);
} |
python | def ldcoeffs(teff,logg=4.5,feh=0):
"""
Returns limb-darkening coefficients in Kepler band.
"""
teffs = np.atleast_1d(teff)
loggs = np.atleast_1d(logg)
Tmin,Tmax = (LDPOINTS[:,0].min(),LDPOINTS[:,0].max())
gmin,gmax = (LDPOINTS[:,1].min(),LDPOINTS[:,1].max())
teffs[(teffs < Tmin)] = Tmin + 1
teffs[(teffs > Tmax)] = Tmax - 1
loggs[(loggs < gmin)] = gmin + 0.01
loggs[(loggs > gmax)] = gmax - 0.01
u1,u2 = (U1FN(teffs,loggs),U2FN(teffs,loggs))
return u1,u2 |
python | def register_list_auth_roles_command(self, list_auth_roles_func):
"""
Add 'list_auth_roles' command to list project authorization roles that can be used with add_user.
:param list_auth_roles_func: function: run when user choses this option.
"""
description = "List authorization roles for use with add_user command."
list_auth_roles_parser = self.subparsers.add_parser('list-auth-roles', description=description)
list_auth_roles_parser.set_defaults(func=list_auth_roles_func) |
java | public final void bytes(Object source, Class sourceClass, byte[] data)
{
if (data == null)
bytes(source, sourceClass, data, 0, 0);
else
bytes(source, sourceClass, data, 0, data.length);
} |
python | def get_bulk_modify(self, value):
"""Return value in format for bulk modify"""
if self.multiselect:
value = value or []
return [self.cast_to_bulk_modify(child) for child in value]
return self.cast_to_bulk_modify(value) |
java | @Override
public synchronized void clear() {
if(isOpen()) {
_compactor.clear();
_addressArray.clear();
_segmentManager.clear();
this.init();
}
} |
python | def uncollapse(self):
"""Uncollapse a private message or modmail."""
url = self.reddit_session.config['uncollapse_message']
self.reddit_session.request_json(url, data={'id': self.name}) |
java | public EEnum getMappingOptionMapValue() {
if (mappingOptionMapValueEEnum == null) {
mappingOptionMapValueEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(91);
}
return mappingOptionMapValueEEnum;
} |
python | def _zforce(self,R,z,phi=0.,t=0.):
"""
NAME:
zforce
PURPOSE:
evaluate vertical force K_z (R,z)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
K_z (R,z)
HISTORY:
2012-12-27 - Written - Bovy (IAS)
"""
if self._new:
#if R > 6.: return self._kp(R,z)
if nu.fabs(z) < 10.**-6.:
return 0.
kalphamax1= R
ks1= kalphamax1*0.5*(self._glx+1.)
weights1= kalphamax1*self._glw
sqrtp= nu.sqrt(z**2.+(ks1+R)**2.)
sqrtm= nu.sqrt(z**2.+(ks1-R)**2.)
evalInt1= ks1**2.*special.k0(ks1*self._alpha)*(1./sqrtp+1./sqrtm)/nu.sqrt(R**2.+z**2.-ks1**2.+sqrtp*sqrtm)/(sqrtp+sqrtm)
if R < 10.:
kalphamax2= 10.
ks2= (kalphamax2-kalphamax1)*0.5*(self._glx+1.)+kalphamax1
weights2= (kalphamax2-kalphamax1)*self._glw
sqrtp= nu.sqrt(z**2.+(ks2+R)**2.)
sqrtm= nu.sqrt(z**2.+(ks2-R)**2.)
evalInt2= ks2**2.*special.k0(ks2*self._alpha)*(1./sqrtp+1./sqrtm)/nu.sqrt(R**2.+z**2.-ks2**2.+sqrtp*sqrtm)/(sqrtp+sqrtm)
return -z*2.*nu.sqrt(2.)*self._alpha*nu.sum(weights1*evalInt1
+weights2*evalInt2)
else:
return -z*2.*nu.sqrt(2.)*self._alpha*nu.sum(weights1*evalInt1)
raise NotImplementedError("Not new=True not implemented for RazorThinExponentialDiskPotential") |
java | public static StringBuilder makePage(final String title,
final String subtitle,
final String body) {
return makePage(null, title, subtitle, body);
} |
python | def post_check_request(self, check, subscribers):
"""
Issues a check execution request.
"""
data = {
'check': check,
'subscribers': [subscribers]
}
self._request('POST', '/request', data=json.dumps(data))
return True |
java | public PagedList<LongTermRetentionBackupInner> listByServer(final String locationName, final String longTermRetentionServerName, final Boolean onlyLatestPerDatabase, final LongTermRetentionDatabaseState databaseState) {
ServiceResponse<Page<LongTermRetentionBackupInner>> response = listByServerSinglePageAsync(locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState).toBlocking().single();
return new PagedList<LongTermRetentionBackupInner>(response.body()) {
@Override
public Page<LongTermRetentionBackupInner> nextPage(String nextPageLink) {
return listByServerNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
} |
java | private static String decodeComponent(final String s, final Charset charset) {
if (s == null) {
return EMPTY_STRING;
}
return decodeComponent(s, 0, s.length(), charset, false);
} |
java | @Override
public void property(String name, String value, int nameValueSeparatorIndex)
throws OperationFormatException {
if(name != null) {
// TODO this is not nice
if(name.length() > 1 && name.charAt(0) == '-' && name.charAt(1) == '-') {
assertValidParameterName(name.substring(2));
} else if(name.length() > 0 && name.charAt(0) == '-') {
assertValidParameterName(name.substring(1));
} else {
assertValidParameterName(name);
}
}
if (value.isEmpty()) {
throw new OperationFormatException("Parameter '" + value + "' is missing value.");
}
validatedProperty(name, value, nameValueSeparatorIndex);
} |
python | def proc_fvals(self, fvals):
"""
Postprocess the outputs of the Session.run(). Move the outputs of
sub-graphs to next ones and return the output of the last sub-graph.
:param fvals: A list of fetched values returned by Session.run()
:return: A dictionary of fetched values returned by the last sub-graph.
"""
inputs = self.inputs
outputs = self.outputs
# Move data to the next sub-graph for the next step
cur = 0
for i in range(len(inputs)-1):
if not self.active_gpus[i]:
self.next_vals[i+1] = None
continue
self.next_vals[i+1] = OrderedDict()
for k in outputs[i]:
self.next_vals[i+1][k] = fvals[cur]
cur += 1
if i == 0:
self.next_vals[0] = None
# Return the output of the last sub-graph
last_fvals = OrderedDict()
if self.active_gpus[-1]:
assert cur+len(outputs[-1]) == len(fvals)
for k in outputs[-1]:
last_fvals[k] = fvals[cur]
cur += 1
return last_fvals |
java | public Set<String> getConfiguredWorkplaceBundles() {
Set<String> result = new HashSet<String>();
for (CmsResourceTypeConfig config : internalGetResourceTypes(false)) {
String bundlename = config.getConfiguredWorkplaceBundle();
if (null != bundlename) {
result.add(bundlename);
}
}
return result;
} |
python | def delete_all_banks(self):
"""
Delete all banks files.
Util for manual save, because isn't possible know which banks
were removed
"""
for file in glob(str(self.data_path) + "/*.json"):
Persistence.delete(file) |
python | def _check_acl(self, acl_no, network, netmask):
"""Check a ACL config exists in the running config.
:param acl_no: access control list (ACL) number
:param network: network which this ACL permits
:param netmask: netmask of the network
:return:
"""
exp_cfg_lines = ['ip access-list standard ' + str(acl_no),
' permit ' + str(network) + ' ' + str(netmask)]
ios_cfg = self._get_running_config()
parse = HTParser(ios_cfg)
acls_raw = parse.find_children(exp_cfg_lines[0])
if acls_raw:
if exp_cfg_lines[1] in acls_raw:
return True
LOG.error("Mismatch in ACL configuration for %s", acl_no)
return False
LOG.debug("%s is not present in config", acl_no)
return False |
java | private static void build3ArgConstructor(final Class< ? > superClazz,
final String className,
final ClassWriter cw) {
MethodVisitor mv;
{
mv = cw.visitMethod( Opcodes.ACC_PUBLIC,
"<init>",
Type.getMethodDescriptor( Type.VOID_TYPE,
Type.getType( int.class ), Type.getType( Class.class ), Type.getType( ValueType.class ) ),
null,
null );
mv.visitCode();
final Label l0 = new Label();
mv.visitLabel( l0 );
mv.visitVarInsn( Opcodes.ALOAD,
0 );
mv.visitVarInsn( Opcodes.ILOAD,
1 );
mv.visitVarInsn( Opcodes.ALOAD,
2 );
mv.visitVarInsn( Opcodes.ALOAD,
3 );
mv.visitMethodInsn( Opcodes.INVOKESPECIAL,
Type.getInternalName( superClazz ),
"<init>",
Type.getMethodDescriptor( Type.VOID_TYPE,
Type.getType( int.class ), Type.getType( Class.class ), Type.getType( ValueType.class ) ) );
final Label l1 = new Label();
mv.visitLabel( l1 );
mv.visitInsn( Opcodes.RETURN );
final Label l2 = new Label();
mv.visitLabel( l2 );
mv.visitLocalVariable( "this",
"L" + className + ";",
null,
l0,
l2,
0 );
mv.visitLocalVariable( "index",
Type.getDescriptor( int.class ),
null,
l0,
l2,
1 );
mv.visitLocalVariable( "fieldType",
Type.getDescriptor( Class.class ),
null,
l0,
l2,
2 );
mv.visitLocalVariable( "valueType",
Type.getDescriptor( ValueType.class ),
null,
l0,
l2,
3 );
mv.visitMaxs( 0,
0 );
mv.visitEnd();
}
} |
java | public Matrix3d rotate(double ang, double x, double y, double z) {
return rotate(ang, x, y, z, this);
} |
python | def apply(self, search, field, value):
"""Apply lookup expression to search query."""
if not isinstance(value, list):
value = [x for x in value.strip().split(',') if x]
filters = [Q('match', **{field: item}) for item in value]
return search.query('bool', should=filters) |
python | def random_tournament_graph(n, random_state=None):
"""
Return a random tournament graph [1]_ with n nodes.
Parameters
----------
n : scalar(int)
Number of nodes.
random_state : int or np.random.RandomState, optional
Random seed (integer) or np.random.RandomState instance to set
the initial state of the random number generator for
reproducibility. If None, a randomly initialized RandomState is
used.
Returns
-------
DiGraph
A DiGraph representing the tournament graph.
References
----------
.. [1] `Tournament (graph theory)
<https://en.wikipedia.org/wiki/Tournament_(graph_theory)>`_,
Wikipedia.
"""
random_state = check_random_state(random_state)
num_edges = n * (n-1) // 2
r = random_state.random_sample(num_edges)
row = np.empty(num_edges, dtype=int)
col = np.empty(num_edges, dtype=int)
_populate_random_tournament_row_col(n, r, row, col)
data = np.ones(num_edges, dtype=bool)
adj_matrix = sparse.coo_matrix((data, (row, col)), shape=(n, n))
return DiGraph(adj_matrix) |
java | public OvhRemoteAccess serviceName_remoteAccesses_POST(String serviceName, String allowedIp, Date expirationDate, Long exposedPort, String publicKey) throws IOException {
String qPath = "/overTheBox/{serviceName}/remoteAccesses";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "allowedIp", allowedIp);
addBody(o, "expirationDate", expirationDate);
addBody(o, "exposedPort", exposedPort);
addBody(o, "publicKey", publicKey);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhRemoteAccess.class);
} |
python | def get_default_env(self):
"""
Vanilla Ansible local commands execute with an environment inherited
from WorkerProcess, we must emulate that.
"""
return dict_diff(
old=ansible_mitogen.process.MuxProcess.original_env,
new=os.environ,
) |
java | public Observable<ServiceResponse<Page<AppServiceCertificateResourceInner>>> listCertificatesNextWithServiceResponseAsync(final String nextPageLink) {
return listCertificatesNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<AppServiceCertificateResourceInner>>, Observable<ServiceResponse<Page<AppServiceCertificateResourceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AppServiceCertificateResourceInner>>> call(ServiceResponse<Page<AppServiceCertificateResourceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listCertificatesNextWithServiceResponseAsync(nextPageLink));
}
});
} |
java | public Writer write(Writer writer) throws JSONException {
try {
if (m_map.isEmpty()) {
writer.write("{}");
return writer;
}
// This prefix value applies to the first key only
String keyprefix = "{\"";
for (Entry<String, Object> entry : m_map.entrySet()) {
writer.write(keyprefix);
writer.write(quotable(entry.getKey()));
writer.write("\":");
Object v = entry.getValue();
if (v instanceof JSONObject) {
((JSONObject)v).write(writer);
}
else if (v instanceof JSONArray) {
((JSONArray)v).write(writer);
}
else {
writer.write(valueToString(v));
}
// This prefix value applies to all subsequent keys
keyprefix = ",\"";
}
writer.write('}');
return writer;
}
catch (IOException exception) {
throw new JSONException(exception);
}
} |
python | def adjust_attributes_on_object(self, collection, name, things, values, how):
"""
adjust labels or annotations on object
labels have to match RE: (([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])? and
have at most 63 chars
:param collection: str, object collection e.g. 'builds'
:param name: str, name of object
:param things: str, 'labels' or 'annotations'
:param values: dict, values to set
:param how: callable, how to adjust the values e.g.
self._replace_metadata_things
:return:
"""
url = self._build_url("%s/%s" % (collection, name))
response = self._get(url)
logger.debug("before modification: %s", response.content)
build_json = response.json()
how(build_json['metadata'], things, values)
response = self._put(url, data=json.dumps(build_json), use_json=True)
check_response(response)
return response |
java | @XmlElementDecl(namespace = "http://www.opengis.net/citygml/transportation/1.0", name = "_GenericApplicationPropertyOfTrack")
public JAXBElement<Object> create_GenericApplicationPropertyOfTrack(Object value) {
return new JAXBElement<Object>(__GenericApplicationPropertyOfTrack_QNAME, Object.class, null, value);
} |
java | private static boolean hasNumberMacro(String pattern, String macroStart, String macroEnd) {
String macro = I_CmsFileNameGenerator.MACRO_NUMBER;
String macroPart = macroStart + macro + MACRO_NUMBER_DIGIT_SEPARATOR;
int prefixIndex = pattern.indexOf(macroPart);
if (prefixIndex >= 0) {
// this macro contains an individual digit setting
char n = pattern.charAt(prefixIndex + macroPart.length());
macro = macro + MACRO_NUMBER_DIGIT_SEPARATOR + n;
}
return pattern.contains(macroStart + macro + macroEnd);
} |
java | private void buildSkyBox()
{
_skybox = new Skybox("skybox", 300, 300, 300);
try {
SimpleResourceLocator sr2 = new SimpleResourceLocator(ExampleBase.class.getClassLoader().getResource("org/poly2tri/examples/geotools/textures/"));
ResourceLocatorTool.addResourceLocator(ResourceLocatorTool.TYPE_TEXTURE, sr2);
} catch (final URISyntaxException ex) {
ex.printStackTrace();
}
final String dir = "";
final Texture stars = TextureManager.load(dir + "stars.gif",
Texture.MinificationFilter.Trilinear,
Image.Format.GuessNoCompression, true);
_skybox.setTexture(Skybox.Face.North, stars);
_skybox.setTexture(Skybox.Face.West, stars);
_skybox.setTexture(Skybox.Face.South, stars);
_skybox.setTexture(Skybox.Face.East, stars);
_skybox.setTexture(Skybox.Face.Up, stars);
_skybox.setTexture(Skybox.Face.Down, stars);
_skybox.getTexture( Skybox.Face.North ).setWrap( WrapMode.Repeat );
for( Face f : Face.values() )
{
FloatBufferData fbd = _skybox.getFace(f).getMeshData().getTextureCoords().get( 0 );
fbd.getBuffer().clear();
fbd.getBuffer().put( 0 ).put( 4 );
fbd.getBuffer().put( 0 ).put( 0 );
fbd.getBuffer().put( 4 ).put( 0 );
fbd.getBuffer().put( 4 ).put( 4 );
}
_node.attachChild( _skybox );
} |
python | def addChildren(self, child_ids):
"""Add children to current workitem
:param child_ids: a :class:`list` contains the children
workitem id/number (integer or equivalent string)
"""
if not hasattr(child_ids, "__iter__"):
error_msg = "Input parameter 'child_ids' is not iterable"
self.log.error(error_msg)
raise exception.BadValue(error_msg)
self.log.debug("Try to add children <Workitem %s> to current "
"<Workitem %s>",
child_ids,
self)
self._addChildren(child_ids)
self.log.info("Successfully add children <Workitem %s> to current "
"<Workitem %s>",
child_ids,
self) |
java | protected void addResourceAttributesRules(Digester digester, String xpath) {
digester.addCallMethod(xpath + N_SOURCE, "setSource", 0);
digester.addCallMethod(xpath + N_DESTINATION, "setDestination", 0);
digester.addCallMethod(xpath + N_TYPE, "setType", 0);
digester.addCallMethod(xpath + N_UUIDSTRUCTURE, "setStructureId", 0);
digester.addCallMethod(xpath + N_UUIDRESOURCE, "setResourceId", 0);
digester.addCallMethod(xpath + N_DATELASTMODIFIED, "setDateLastModified", 0);
digester.addCallMethod(xpath + N_USERLASTMODIFIED, "setUserLastModified", 0);
digester.addCallMethod(xpath + N_DATECREATED, "setDateCreated", 0);
digester.addCallMethod(xpath + N_USERCREATED, "setUserCreated", 0);
digester.addCallMethod(xpath + N_DATERELEASED, "setDateReleased", 0);
digester.addCallMethod(xpath + N_DATEEXPIRED, "setDateExpired", 0);
digester.addCallMethod(xpath + N_FLAGS, "setFlags", 0);
} |
python | def end_parallel(self):
"""
Ends a parallel region by merging the channels into a single stream.
Returns:
Stream: Stream for which subsequent transformations are no longer parallelized.
.. seealso:: :py:meth:`set_parallel`, :py:meth:`parallel`
"""
outport = self.oport
if isinstance(self.oport.operator, streamsx.topology.graph.Marker):
if self.oport.operator.kind == "$Union$":
pto = self.topology.graph.addPassThruOperator()
pto.addInputPort(outputPort=self.oport)
outport = pto.addOutputPort(schema=self.oport.schema)
op = self.topology.graph.addOperator("$EndParallel$")
op.addInputPort(outputPort=outport)
oport = op.addOutputPort(schema=self.oport.schema)
endP = Stream(self.topology, oport)
return endP |
python | def createSimpleResourceMap(ore_pid, scimeta_pid, sciobj_pid_list):
"""Create a simple OAI-ORE Resource Map with one Science Metadata document and any
number of Science Data objects.
This creates a document that establishes an association between a Science Metadata
object and any number of Science Data objects. The Science Metadata object contains
information that is indexed by DataONE, allowing both the Science Metadata and the
Science Data objects to be discoverable in DataONE Search. In search results, the
objects will appear together and can be downloaded as a single package.
Args:
ore_pid: str
Persistent Identifier (PID) to use for the new Resource Map
scimeta_pid: str
PID for an object that will be listed as the Science Metadata that is
describing the Science Data objects.
sciobj_pid_list: list of str
List of PIDs that will be listed as the Science Data objects that are being
described by the Science Metadata.
Returns:
ResourceMap : OAI-ORE Resource Map
"""
ore = ResourceMap()
ore.initialize(ore_pid)
ore.addMetadataDocument(scimeta_pid)
ore.addDataDocuments(sciobj_pid_list, scimeta_pid)
return ore |
python | def deactivate(self):
"""
Deactivates the logical volume.
*Raises:*
* HandleError
"""
self.open()
d = lvm_lv_deactivate(self.handle)
self.close()
if d != 0:
raise CommitError("Failed to deactivate LV.") |
java | @Override
public int compare(int i, int j) {
final int bufferNumI = i / this.recordsPerSegment;
final int segmentOffsetI = (i % this.recordsPerSegment) * this.recordSize;
final int bufferNumJ = j / this.recordsPerSegment;
final int segmentOffsetJ = (j % this.recordsPerSegment) * this.recordSize;
final MemorySegment segI = this.sortBuffer.get(bufferNumI);
final MemorySegment segJ = this.sortBuffer.get(bufferNumJ);
int val = MemorySegment.compare(segI, segJ, segmentOffsetI, segmentOffsetJ, this.numKeyBytes);
return this.useNormKeyUninverted ? val : -val;
} |
python | def fidelity_based(h1, h2): # 25 us @array, 51 us @list \w 100 bins
r"""
Fidelity based distance.
Also Bhattacharyya distance; see also the extensions `noelle_1` to `noelle_5`.
The metric between two histograms :math:`H` and :math:`H'` of size :math:`m` is defined as:
.. math::
d_{F}(H, H') = \sum_{m=1}^M\sqrt{H_m * H'_m}
*Attributes:*
- not a metric, a similarity
*Attributes for normalized histograms:*
- :math:`d(H, H')\in[0, 1]`
- :math:`d(H, H) = 1`
- :math:`d(H, H') = d(H', H)`
*Attributes for not-normalized histograms:*
- not applicable
*Attributes for not-equal histograms:*
- not applicable
Parameters
----------
h1 : sequence
The first histogram, normalized.
h2 : sequence
The second histogram, normalized, same bins as ``h1``.
Returns
-------
fidelity_based : float
Fidelity based distance.
Notes
-----
The fidelity between two histograms :math:`H` and :math:`H'` is the same as the
cosine between their square roots :math:`\sqrt{H}` and :math:`\sqrt{H'}`.
"""
h1, h2 = __prepare_histogram(h1, h2)
result = scipy.sum(scipy.sqrt(h1 * h2))
result = 0 if 0 > result else result # for rounding errors
result = 1 if 1 < result else result # for rounding errors
return result |
java | public void marshall(Model model, ProtocolMarshaller protocolMarshaller) {
if (model == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(model.getId(), ID_BINDING);
protocolMarshaller.marshall(model.getName(), NAME_BINDING);
protocolMarshaller.marshall(model.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(model.getSchema(), SCHEMA_BINDING);
protocolMarshaller.marshall(model.getContentType(), CONTENTTYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def add_zone_condition(self, droppable_id, zone_id, match=True):
"""stub"""
self.my_osid_object_form._my_map['zoneConditions'].append(
{'droppableId': droppable_id, 'zoneId': zone_id, 'match': match})
self.my_osid_object_form._my_map['zoneConditions'].sort(key=lambda k: k['zoneId']) |
java | @Override
public <E, R> AppEngineGetScalar<E, R> get(Aggregation<R> aggregation) {
if (aggregation == null) {
throw new IllegalArgumentException("'aggregation' must not be [" + aggregation + "]");
}
return new AppEngineGetScalar<E, R>(aggregation, this);
} |
java | public Observable<ServiceResponse<Page<SiteInner>>> beginChangeVnetNextWithServiceResponseAsync(final String nextPageLink) {
return beginChangeVnetNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() {
@Override
public Observable<ServiceResponse<Page<SiteInner>>> call(ServiceResponse<Page<SiteInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(beginChangeVnetNextWithServiceResponseAsync(nextPageLink));
}
});
} |
java | @SuppressWarnings("unchecked")
@Override
public void itemStateChanged(final ItemEvent e)
{
final ItemSelectable is = e.getItemSelectable();
final Object selected[] = is.getSelectedObjects();
final T sel = (selected.length == 0) ? null : (T)selected[0];
model.setSelectedItem(sel);
} |
python | def wait_for_interrupt(self, check_interval=1.0, max_time=None):
"""Run the event loop until we receive a ctrl-c interrupt or max_time passes.
This method will wake up every 1 second by default to check for any
interrupt signals or if the maximum runtime has expired. This can be
set lower for testing purpose to reduce latency but in production
settings, this can cause increased CPU usage so 1 second is an
appropriate value.
Args:
check_interval (float): How often to wake up and check for
a SIGTERM. Defaults to 1s. Setting this faster is useful
for unit testing. Cannot be < 0.01 s.
max_time (float): Stop the event loop after max_time seconds.
This is useful for testing purposes. Defaults to None,
which means run forever until interrupt.
"""
self.start()
wait = max(check_interval, 0.01)
accum = 0
try:
while max_time is None or accum < max_time:
try:
time.sleep(wait)
except IOError:
pass # IOError comes when this call is interrupted in a signal handler
accum += wait
except KeyboardInterrupt:
pass |
python | def _node_add_with_peer_list(self, child_self, child_other):
'''_node_add_with_peer_list
Low-level api: Apply delta child_other to child_self when child_self is
the peer of child_other. Element child_self and child_other are list
nodes. Element child_self will be modified during the process. RFC6020
section 7.8.6 is a reference of this method.
Parameters
----------
child_self : `Element`
A child of a config node in a config tree.
child_other : `Element`
A child of a config node in another config tree. child_self is
the peer of child_other.
Returns
-------
None
There is no return of this method.
'''
parent_self = child_self.getparent()
s_node = self.device.get_schema_node(child_self)
if child_other.get(operation_tag) != 'delete' and \
child_other.get(operation_tag) != 'remove' and \
s_node.get('ordered-by') == 'user' and \
child_other.get(insert_tag) is not None:
if child_other.get(insert_tag) == 'first':
scope = parent_self.getchildren()
siblings = self._get_sequence(scope, child_other.tag,
parent_self)
if siblings[0] != child_self:
siblings[0].addprevious(child_self)
elif child_other.get(insert_tag) == 'last':
scope = parent_self.getchildren()
siblings = self._get_sequence(scope, child_other.tag,
parent_self)
if siblings[-1] != child_self:
siblings[-1].addnext(child_self)
elif child_other.get(insert_tag) == 'before':
if child_other.get(key_tag) is None:
_inserterror('before', self.device.get_xpath(child_other),
'key')
sibling = parent_self.find(child_other.tag +
child_other.get(key_tag),
namespaces=child_other.nsmap)
if sibling is None:
path = self.device.get_xpath(child_other)
key = child_other.get(key_tag)
_inserterror('before', path, 'key', key)
if sibling != child_self:
sibling.addprevious(child_self)
elif child_other.get(insert_tag) == 'after':
if child_other.get(key_tag) is None:
_inserterror('after', self.device.get_xpath(child_other),
'key')
sibling = parent_self.find(child_other.tag +
child_other.get(key_tag),
namespaces=child_other.nsmap)
if sibling is None:
path = self.device.get_xpath(child_other)
key = child_other.get(key_tag)
_inserterror('after', path, 'key', key)
if sibling != child_self:
sibling.addnext(child_self)
if child_other.get(operation_tag) is None or \
child_other.get(operation_tag) == 'merge':
self.node_add(child_self, child_other)
elif child_other.get(operation_tag) == 'replace':
e = deepcopy(child_other)
parent_self.replace(child_self, self._del_attrib(e))
elif child_other.get(operation_tag) == 'create':
raise ConfigDeltaError('data-exists: try to create node {} but ' \
'it already exists' \
.format(self.device.get_xpath(child_other)))
elif child_other.get(operation_tag) == 'delete' or \
child_other.get(operation_tag) == 'remove':
parent_self.remove(child_self)
else:
raise ConfigDeltaError("unknown operation: node {} contains " \
"operation '{}'" \
.format(self.device.get_xpath(child_other),
child_other.get(operation_tag))) |
java | static MemberMap cloneAdding(MemberMap source, MemberImpl... newMembers) {
Map<Address, MemberImpl> addressMap = new LinkedHashMap<>(source.addressToMemberMap);
Map<String, MemberImpl> uuidMap = new LinkedHashMap<>(source.uuidToMemberMap);
for (MemberImpl member : newMembers) {
putMember(addressMap, uuidMap, member);
}
return new MemberMap(source.version + newMembers.length, addressMap, uuidMap);
} |
java | public float getPixelSize() {
if (mVectorState == null && mVectorState.mVPathRenderer == null ||
mVectorState.mVPathRenderer.mBaseWidth == 0 ||
mVectorState.mVPathRenderer.mBaseHeight == 0 ||
mVectorState.mVPathRenderer.mViewportHeight == 0 ||
mVectorState.mVPathRenderer.mViewportWidth == 0) {
return 1; // fall back to 1:1 pixel mapping.
}
float intrinsicWidth = mVectorState.mVPathRenderer.mBaseWidth;
float intrinsicHeight = mVectorState.mVPathRenderer.mBaseHeight;
float viewportWidth = mVectorState.mVPathRenderer.mViewportWidth;
float viewportHeight = mVectorState.mVPathRenderer.mViewportHeight;
float scaleX = viewportWidth / intrinsicWidth;
float scaleY = viewportHeight / intrinsicHeight;
return Math.min(scaleX, scaleY);
} |
java | public static boolean nullSafeEquals(String text1, String text2) {
if (text1 == null || text2 == null) {
return false;
} else {
return text1.equals(text2);
}
} |
python | def start_server_background(port):
"""Start the newtab server as a background process."""
if sys.version_info[0] == 2:
lines = ('import pydoc\n'
'pydoc.serve({port})')
cell = lines.format(port=port)
else:
# The location of newtabmagic (normally $IPYTHONDIR/extensions)
# needs to be added to sys.path.
path = repr(os.path.dirname(os.path.realpath(__file__)))
lines = ('import sys\n'
'sys.path.append({path})\n'
'import newtabmagic\n'
'newtabmagic.pydoc_cli_monkey_patched({port})')
cell = lines.format(path=path, port=port)
# Use script cell magic so that shutting down IPython stops
# the server process.
line = "python --proc proc --bg --err error --out output"
ip = get_ipython()
ip.run_cell_magic("script", line, cell)
return ip.user_ns['proc'] |
python | def save_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None,
cmap=None, format=None, origin=None):
""" This method saves the image from a numpy array using matplotlib
:param fname: Location and name of the image file to be saved.
:param pixel_array: Numpy pixel array, i.e. ``numpy()`` return value
:param vmin: matplotlib vmin
:param vmax: matplotlib vmax
:param cmap: matplotlib color map
:param format: matplotlib format
:param origin: matplotlib origin
This method will return True if successful
"""
from matplotlib.backends.backend_agg \
import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from pylab import cm
if pixel_array is None:
pixel_array = self.numpy
if cmap is None:
cmap = cm.bone
fig = Figure(figsize=pixel_array.shape[::-1], dpi=1, frameon=False)
canvas = FigureCanvas(fig)
fig.figimage(pixel_array, cmap=cmap, vmin=vmin,
vmax=vmax, origin=origin)
fig.savefig(fname, dpi=1, format=format)
return True |
python | def preserve_channel_dim(func):
"""Preserve dummy channel dim."""
@wraps(func)
def wrapped_function(img, *args, **kwargs):
shape = img.shape
result = func(img, *args, **kwargs)
if len(shape) == 3 and shape[-1] == 1 and len(result.shape) == 2:
result = np.expand_dims(result, axis=-1)
return result
return wrapped_function |
python | def remove_all_labels(stdout=None):
"""
Calls functions for dropping constraints and indexes.
:param stdout: output stream
:return: None
"""
if not stdout:
stdout = sys.stdout
stdout.write("Droping constraints...\n")
drop_constraints(quiet=False, stdout=stdout)
stdout.write('Droping indexes...\n')
drop_indexes(quiet=False, stdout=stdout) |
python | def releases(release_id=None, **kwargs):
"""Get all releases of economic data."""
if not 'id' in kwargs and release_id is not None:
kwargs['release_id'] = release_id
return Fred().release(**kwargs)
return Fred().releases(**kwargs) |
java | @Override
protected String createDialogHtml(String dialog) {
StringBuffer result = new StringBuffer(1024);
// create table
result.append(createWidgetTableStart());
// show error header once if there were validation errors
result.append(createWidgetErrorHeader());
if (dialog.equals(PAGES[0])) {
result.append(dialogBlockStart(key("label.moduleinformation")));
result.append(createWidgetTableStart());
result.append(createDialogRowsHtml(0, 7));
result.append(createWidgetTableEnd());
result.append(dialogBlockEnd());
result.append(dialogBlockStart(key("label.modulecreator")));
result.append(createWidgetTableStart());
result.append(createDialogRowsHtml(8, 9));
result.append(createWidgetTableEnd());
result.append(dialogBlockEnd());
result.append(dialogBlockStart(key("label.moduleexportmode")));
result.append(createWidgetTableStart());
result.append(createDialogRowsHtml(10, 10));
result.append(createWidgetTableEnd());
result.append(dialogBlockEnd());
if (CmsStringUtil.isEmpty(m_module.getName())) {
result.append(dialogBlockStart(key("label.modulefolder")));
result.append(createWidgetTableStart());
result.append(createDialogRowsHtml(11, 17));
result.append(createWidgetTableEnd());
result.append(dialogBlockEnd());
}
}
// close table
result.append(createWidgetTableEnd());
return result.toString();
} |
java | public final static void changeConnection(final int position, final ConnectionNotation notation,
final HELM2Notation helm2notation) {
helm2notation.getListOfConnections().set(position, notation);
} |
java | public ConstantNameAndTypeInfo addConstantNameAndType(String name,
Descriptor type) {
return (ConstantNameAndTypeInfo)addConstant(new ConstantNameAndTypeInfo(this, name, type));
} |
java | public void accept(TokenKind tk) {
if (token.kind == tk) {
nextToken();
} else {
setErrorEndPos(token.pos);
reportSyntaxError(S.prevToken().endPos, "expected", tk);
}
} |
java | private String getCustomReloginErrorPage(HttpServletRequest req) {
String reLogin = CookieHelper.getCookieValue(req.getCookies(), ReferrerURLCookieHandler.CUSTOM_RELOGIN_URL_COOKIENAME);
if (reLogin != null && reLogin.length() > 0) {
if (reLogin.indexOf("?") < 0)
reLogin += "?error=error";
}
return reLogin;
} |
java | public final void setIntent(@NonNull final Activity activity, @NonNull final Intent intent) {
Condition.INSTANCE.ensureNotNull(activity, "The activity may not be null");
Condition.INSTANCE.ensureNotNull(intent, "The intent may not be null");
removeAllItems();
PackageManager packageManager = activity.getPackageManager();
List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(intent, 0);
for (int i = 0; i < resolveInfos.size(); i++) {
ResolveInfo resolveInfo = resolveInfos.get(i);
addItem(i, resolveInfo.loadLabel(packageManager), resolveInfo.loadIcon(packageManager));
}
setOnItemClickListener(
createIntentClickListener(activity, (Intent) intent.clone(), resolveInfos));
} |
python | def pystr(self, min_chars=None, max_chars=20):
"""
Generates a random string of upper and lowercase letters.
:type min_chars: int
:type max_chars: int
:return: String. Random of random length between min and max characters.
"""
if min_chars is None:
return "".join(self.random_letters(length=max_chars))
else:
assert (
max_chars >= min_chars), "Maximum length must be greater than or equal to minium length"
return "".join(
self.random_letters(
length=self.generator.random.randint(min_chars, max_chars),
),
) |
python | def _parse_template_or_argument(self):
"""Parse a template or argument at the head of the wikicode string."""
self._head += 2
braces = 2
while self._read() == "{":
self._head += 1
braces += 1
has_content = False
self._push()
while braces:
if braces == 1:
return self._emit_text_then_stack("{")
if braces == 2:
try:
self._parse_template(has_content)
except BadRoute:
return self._emit_text_then_stack("{{")
break
try:
self._parse_argument()
braces -= 3
except BadRoute:
try:
self._parse_template(has_content)
braces -= 2
except BadRoute:
return self._emit_text_then_stack("{" * braces)
if braces:
has_content = True
self._head += 1
self._emit_all(self._pop())
if self._context & contexts.FAIL_NEXT:
self._context ^= contexts.FAIL_NEXT |
java | private List<Float> interpolatePositions(PositionInfo left, PositionInfo right, int steps) {
if (left.isOutOfBounds()) {
if (right.isNormal()) {
return interpolateDownwards(right.getNavPos(), steps);
} else if (right.isMax() || right.isOutOfBounds()) {
return interpolateEmpty(steps);
} else {
// can't happen
assert false;
}
} else if (left.isNormal()) {
if (right.isOutOfBounds() || right.isMax()) {
return interpolateUpwards(left.getNavPos(), steps);
} else if (right.isNormal()) {
return interpolateBetween(left.getNavPos(), right.getNavPos(), steps);
} else {
// can't happen
assert false;
}
} else {
// can't happen
assert false;
}
return null;
} |
java | public static String digest(CharSequence self, String algorithm) throws NoSuchAlgorithmException {
final String text = self.toString();
return digest(text.getBytes(StandardCharsets.UTF_8), algorithm);
} |
java | public Options setxAxis(final Axis xAxis) {
this.xAxis = new ArrayList<Axis>();
this.xAxis.add(xAxis);
return this;
} |
java | private Object getConnection()
{
/*
* Jedis connection = factory.getConnection();
*
* // If resource is not null means a transaction in progress.
*
* if (settings != null) { for (String key : settings.keySet()) {
* connection.configSet(key, settings.get(key).toString()); } }
*
* if (resource != null && resource.isActive()) { return
* ((RedisTransaction) resource).bindResource(connection); } else {
* return connection; } if (resource == null || (resource != null &&
* !resource.isActive()))
*/
// means either transaction resource is not bound or it is not active,
// but connection has already by initialized
if (isBoundTransaction() && this.connection != null)
{
return this.connection;
}
// if running within transaction boundary.
if (resource != null && resource.isActive())
{
// no need to get a connection from pool, as nested MULTI is not yet
// supported.
if (((RedisTransaction) resource).isResourceBound())
{
return ((RedisTransaction) resource).getResource();
}
else
{
Jedis conn = getAndSetConnection();
return ((RedisTransaction) resource).bindResource(conn);
}
}
else
{
Jedis conn = getAndSetConnection();
return conn;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.