language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public static TermLengthOrPercent createLengthOrPercent(String spec)
{
spec = spec.trim();
if (spec.endsWith("%"))
{
try {
float val = Float.parseFloat(spec.substring(0, spec.length() - 1));
TermPercent perc = CSSFactory.getTermFactory().createPercent(val);
return perc;
} catch (NumberFormatException e) {
return null;
}
}
else
{
try {
float val = Float.parseFloat(spec);
TermLength len = CSSFactory.getTermFactory().createLength(val, TermLength.Unit.px);
return len;
} catch (NumberFormatException e) {
return null;
}
}
} |
python | def format_dict(dic, format_list, separator=',', default_value=str):
"""
Format dict to string passing a list of keys as order
Args:
lista: List with elements to clean duplicates.
"""
dic = collections.defaultdict(default_value, dic)
str_format = separator.join(["{" + "{}".format(head) + "}" for head in format_list])
return str_format.format(**dic) |
python | def overlap(a, b):
"""Check if two ranges overlap.
Parameters
----------
a : range
The first range.
b : range
The second range.
Returns
-------
overlaps : bool
Do these ranges overlap.
Notes
-----
This function does not support ranges with step != 1.
"""
_check_steps(a, b)
return a.stop >= b.start and b.stop >= a.start |
java | public final ValueWithPos<String> formatE123NationalWithPos(
final ValueWithPos<PhoneNumberData> pphoneNumberData) {
if (pphoneNumberData == null) {
return null;
}
int cursor = pphoneNumberData.getPos();
final StringBuilder resultNumber = new StringBuilder();
if (isPhoneNumberNotEmpty(pphoneNumberData.getValue())) {
PhoneCountryData phoneCountryData = null;
for (final PhoneCountryCodeData country : CreatePhoneCountryConstantsClass.create()
.countryCodeData()) {
if (StringUtils.equals(country.getCountryCode(),
pphoneNumberData.getValue().getCountryCode())) {
phoneCountryData = country.getPhoneCountryData();
break;
}
}
if (phoneCountryData == null) {
return this.formatE123InternationalWithPos(pphoneNumberData);
}
if (cursor > 0) {
cursor -= StringUtils.length(pphoneNumberData.getValue().getCountryCode());
cursor += StringUtils.length(phoneCountryData.getTrunkCode());
}
cursor++;
resultNumber.append('(').append(phoneCountryData.getTrunkCode());
if (StringUtils.isNotBlank(pphoneNumberData.getValue().getAreaCode())) {
resultNumber.append(pphoneNumberData.getValue().getAreaCode());
}
if (resultNumber.length() <= cursor) {
cursor += 2;
}
resultNumber.append(") ");
resultNumber.append(pphoneNumberData.getValue().getLineNumber());
if (StringUtils.isNotBlank(pphoneNumberData.getValue().getExtension())) {
if (resultNumber.length() <= cursor) {
cursor++;
}
resultNumber.append(' ');
resultNumber.append(pphoneNumberData.getValue().getExtension());
}
}
return new ValueWithPos<>(StringUtils.trimToNull(resultNumber.toString()), cursor);
} |
python | def qteFocusChanged(self, old, new):
"""
Slot for Qt native focus-changed signal to notify Qtmacs if
the window was switched.
.. note: This method is work in progress.
"""
# Do nothing if new is old.
if old is new:
return
# If neither is None but both have the same top level
# window then do nothing.
if (old is not None) and (new is not None):
if old.isActiveWindow() is new.isActiveWindow():
return |
python | def _validate_signing_cert(ca_certificate, certificate, crl=None):
"""
Validate an X509 certificate using pyOpenSSL.
.. note::
pyOpenSSL is a short-term solution to certificate validation. pyOpenSSL
is basically in maintenance mode and there's a desire in upstream to move
all the functionality into cryptography.
Args:
ca_certificate (str): A PEM-encoded Certificate Authority certificate to
validate the ``certificate`` with.
certificate (str): A PEM-encoded certificate that is in need of validation.
crl (str): A PEM-encoded Certificate Revocation List which, if provided, will
be taken into account when validating the certificate.
Raises:
X509StoreContextError: If the certificate failed validation. The
exception contains the details of the error.
"""
pyopenssl_cert = load_certificate(FILETYPE_PEM, certificate)
pyopenssl_ca_cert = load_certificate(FILETYPE_PEM, ca_certificate)
cert_store = X509Store()
cert_store.add_cert(pyopenssl_ca_cert)
if crl:
pyopenssl_crl = load_crl(FILETYPE_PEM, crl)
cert_store.add_crl(pyopenssl_crl)
cert_store.set_flags(X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
cert_store_context = X509StoreContext(cert_store, pyopenssl_cert)
cert_store_context.verify_certificate() |
java | public boolean onAbout()
{
Application application = this.getApplication();
application.getResources(null, true); // Set the resource bundle to default
String strTitle = this.getString(ThinMenuConstants.ABOUT);
String strMessage = this.getString("Copyright");
JOptionPane.showMessageDialog(ScreenUtil.getFrame(this), strMessage, strTitle, JOptionPane.INFORMATION_MESSAGE);
return true;
} |
python | def to_nibabel(image):
"""
Convert an ANTsImage to a Nibabel image
"""
if image.dimension != 3:
raise ValueError('Only 3D images currently supported')
import nibabel as nib
array_data = image.numpy()
affine = np.hstack([image.direction*np.diag(image.spacing),np.array(image.origin).reshape(3,1)])
affine = np.vstack([affine, np.array([0,0,0,1.])])
affine[:2,:] *= -1
new_img = nib.Nifti1Image(array_data, affine)
return new_img |
java | private void readLayerAndMaskInfo(final boolean pParseData) throws IOException {
readImageResources(false);
if (pParseData && (metadata.layerInfo == null || metadata.globalLayerMask == null) || metadata.imageDataStart == 0) {
imageInput.seek(metadata.layerAndMaskInfoStart);
long layerAndMaskInfoLength = header.largeFormat ? imageInput.readLong() : imageInput.readUnsignedInt();
// NOTE: The spec says that if this section is empty, the length should be 0.
// Yet I have a PSB file that has size 12, and both contained lengths set to 0 (which
// is alo not as per spec, as layer count should be included if there's a layer info
// block, so minimum size should be either 0 or 14 (or 16 if multiple of 4 for PSB))...
if (layerAndMaskInfoLength > 0) {
long pos = imageInput.getStreamPosition();
//if (metadata.layerInfo == null) {
long layerInfoLength = header.largeFormat ? imageInput.readLong() : imageInput.readUnsignedInt();
if (layerInfoLength > 0) {
// "Layer count. If it is a negative number, its absolute value is the number of
// layers and the first alpha channel contains the transparency data for the
// merged result."
int layerCount = imageInput.readShort();
metadata.layerCount = layerCount;
if (pParseData && metadata.layerInfo == null) {
PSDLayerInfo[] layerInfos = new PSDLayerInfo[Math.abs(layerCount)];
for (int i = 0; i < layerInfos.length; i++) {
layerInfos[i] = new PSDLayerInfo(header.largeFormat, imageInput);
}
metadata.layerInfo = Arrays.asList(layerInfos);
metadata.layersStart = imageInput.getStreamPosition();
}
long read = imageInput.getStreamPosition() - pos;
long diff = layerInfoLength - (read - (header.largeFormat ? 8 : 4)); // - 8 or 4 for the layerInfoLength field itself
imageInput.skipBytes(diff);
}
else {
metadata.layerInfo = Collections.emptyList();
}
// Global LayerMaskInfo (18 bytes or more..?)
// 4 (length), 2 (colorSpace), 8 (4 * 2 byte color components), 2 (opacity %), 1 (kind), variable (pad)
long globalLayerMaskInfoLength = imageInput.readUnsignedInt(); // NOTE: Not long for PSB!
if (globalLayerMaskInfoLength > 0) {
if (pParseData && metadata.globalLayerMask == null) {
metadata.globalLayerMask = new PSDGlobalLayerMask(imageInput, globalLayerMaskInfoLength);
}
// TODO: Else skip?
}
else {
metadata.globalLayerMask = PSDGlobalLayerMask.NULL_MASK;
}
// TODO: Parse "Additional layer information"
// TODO: We should now be able to flush input
// imageInput.seek(metadata.layerAndMaskInfoStart + layerAndMaskInfoLength + (header.largeFormat ? 8 : 4));
// imageInput.flushBefore(metadata.layerAndMaskInfoStart + layerAndMaskInfoLength + (header.largeFormat ? 8 : 4));
if (pParseData && DEBUG) {
System.out.println("layerInfo: " + metadata.layerInfo);
System.out.println("globalLayerMask: " + (metadata.globalLayerMask != PSDGlobalLayerMask.NULL_MASK ? metadata.globalLayerMask : null));
}
//}
}
metadata.imageDataStart = metadata.layerAndMaskInfoStart + layerAndMaskInfoLength + (header.largeFormat ? 8 : 4);
}
} |
python | def poisson_source(rate, iterable, target):
"""Send events at random times with uniform probability.
Args:
rate: The average number of events to send per second.
iterable: A series of items which will be sent to the target one by one.
target: The target coroutine or sink.
Returns:
An iterator over any remaining items.
"""
if rate <= 0.0:
raise ValueError("poisson_source rate {} is not positive".format(rate))
it = iter(iterable)
for item in it:
duration = random.expovariate(rate)
sleep(duration)
try:
target.send(item)
except StopIteration:
return prepend(item, it)
return empty_iter() |
java | @Override
public void setX(double min, double max) {
if (min <= max) {
this.minxProperty.set(min);
this.maxxProperty.set(max);
} else {
this.minxProperty.set(max);
this.maxxProperty.set(min);
}
} |
python | def left(self, expand=None):
""" Returns a new Region left of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the left border
of the screen. The new region has the same height and y-position as the current region.
"""
if expand == None:
x = 0
y = self.y
w = self.x
h = self.h
else:
x = self.x-expand
y = self.y
w = expand
h = self.h
return Region(x, y, w, h).clipRegionToScreen() |
java | private void emitSubroutine(final Instantiation instant,
final List<Instantiation> worklist, final InsnList newInstructions,
final List<TryCatchBlockNode> newTryCatchBlocks,
final List<LocalVariableNode> newLocalVariables) {
LabelNode duplbl = null;
if (LOGGING) {
log("--------------------------------------------------------");
log("Emitting instantiation of subroutine " + instant.subroutine);
}
// Emit the relevant instructions for this instantiation, translating
// labels and jump targets as we go:
for (int i = 0, c = instructions.size(); i < c; i++) {
AbstractInsnNode insn = instructions.get(i);
Instantiation owner = instant.findOwner(i);
// Always remap labels:
if (insn.getType() == AbstractInsnNode.LABEL) {
// Translate labels into their renamed equivalents.
// Avoid adding the same label more than once. Note
// that because we own this instruction the gotoTable
// and the rangeTable will always agree.
LabelNode ilbl = (LabelNode) insn;
LabelNode remap = instant.rangeLabel(ilbl);
if (LOGGING) {
// TODO use of default toString().
log("Translating lbl #" + i + ':' + ilbl + " to " + remap);
}
if (remap != duplbl) {
newInstructions.add(remap);
duplbl = remap;
}
continue;
}
// We don't want to emit instructions that were already
// emitted by a subroutine higher on the stack. Note that
// it is still possible for a given instruction to be
// emitted twice because it may belong to two subroutines
// that do not invoke each other.
if (owner != instant) {
continue;
}
if (LOGGING) {
log("Emitting inst #" + i);
}
if (insn.getOpcode() == RET) {
// Translate RET instruction(s) to a jump to the return label
// for the appropriate instantiation. The problem is that the
// subroutine may "fall through" to the ret of a parent
// subroutine; therefore, to find the appropriate ret label we
// find the lowest subroutine on the stack that claims to own
// this instruction. See the class javadoc comment for an
// explanation on why this technique is safe (note: it is only
// safe if the input is verifiable).
LabelNode retlabel = null;
for (Instantiation p = instant; p != null; p = p.previous) {
if (p.subroutine.get(i)) {
retlabel = p.returnLabel;
}
}
if (retlabel == null) {
// This is only possible if the mainSubroutine owns a RET
// instruction, which should never happen for verifiable
// code.
throw new RuntimeException("Instruction #" + i
+ " is a RET not owned by any subroutine");
}
newInstructions.add(new JumpInsnNode(GOTO, retlabel));
} else if (insn.getOpcode() == JSR) {
LabelNode lbl = ((JumpInsnNode) insn).label;
BitSet sub = subroutineHeads.get(lbl);
Instantiation newinst = new Instantiation(instant, sub);
LabelNode startlbl = newinst.gotoLabel(lbl);
if (LOGGING) {
log(" Creating instantiation of subr " + sub);
}
// Rather than JSRing, we will jump to the inline version and
// push NULL for what was once the return value. This hack
// allows us to avoid doing any sort of data flow analysis to
// figure out which instructions manipulate the old return value
// pointer which is now known to be unneeded.
newInstructions.add(new InsnNode(ACONST_NULL));
newInstructions.add(new JumpInsnNode(GOTO, startlbl));
newInstructions.add(newinst.returnLabel);
// Insert this new instantiation into the queue to be emitted
// later.
worklist.add(newinst);
} else {
newInstructions.add(insn.clone(instant));
}
}
// Emit try/catch blocks that are relevant to this method.
for (Iterator<TryCatchBlockNode> it = tryCatchBlocks.iterator(); it
.hasNext();) {
TryCatchBlockNode trycatch = it.next();
if (LOGGING) {
// TODO use of default toString().
log("try catch block original labels=" + trycatch.start + '-'
+ trycatch.end + "->" + trycatch.handler);
}
final LabelNode start = instant.rangeLabel(trycatch.start);
final LabelNode end = instant.rangeLabel(trycatch.end);
// Ignore empty try/catch regions
if (start == end) {
if (LOGGING) {
log(" try catch block empty in this subroutine");
}
continue;
}
final LabelNode handler = instant.gotoLabel(trycatch.handler);
if (LOGGING) {
// TODO use of default toString().
log(" try catch block new labels=" + start + '-' + end + "->"
+ handler);
}
if (start == null || end == null || handler == null) {
throw new RuntimeException("Internal error!");
}
newTryCatchBlocks.add(new TryCatchBlockNode(start, end, handler,
trycatch.type));
}
for (Iterator<LocalVariableNode> it = localVariables.iterator(); it
.hasNext();) {
LocalVariableNode lvnode = it.next();
if (LOGGING) {
log("local var " + lvnode.name);
}
final LabelNode start = instant.rangeLabel(lvnode.start);
final LabelNode end = instant.rangeLabel(lvnode.end);
if (start == end) {
if (LOGGING) {
log(" local variable empty in this sub");
}
continue;
}
newLocalVariables.add(new LocalVariableNode(lvnode.name,
lvnode.desc, lvnode.signature, start, end, lvnode.index));
}
} |
python | def _handle_ansi_color_codes(self, s):
"""Replace ansi escape sequences with spans of appropriately named css classes."""
parts = HtmlReporter._ANSI_COLOR_CODE_RE.split(s)
ret = []
span_depth = 0
# Note that len(parts) is always odd: text, code, text, code, ..., text.
for i in range(0, len(parts), 2):
ret.append(parts[i])
if i + 1 < len(parts):
for code in parts[i + 1].split(';'):
if code == 0: # Reset.
while span_depth > 0:
ret.append('</span>')
span_depth -= 1
else:
ret.append('<span class="ansi-{}">'.format(code))
span_depth += 1
while span_depth > 0:
ret.append('</span>')
span_depth -= 1
return ''.join(ret) |
python | def run_model(self, model_run, run_url):
"""Create entry in run request buffer.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information
"""
# Create model run request
request = RequestFactory().get_request(model_run, run_url)
# Write request and connector information into buffer
self.collection.insert_one({
'connector' : self.connector,
'request' : request.to_dict()
}) |
java | @SuppressWarnings("fallthrough")
protected void inlineWord() {
int pos = bp;
int depth = 0;
loop:
while (bp < buflen) {
switch (ch) {
case '\n':
newline = true;
// fallthrough
case '\r': case '\f': case ' ': case '\t':
return;
case '@':
if (newline)
break loop;
case '{':
depth++;
break;
case '}':
if (depth == 0 || --depth == 0)
return;
break;
}
newline = false;
nextChar();
}
} |
java | public static StackTraceElement element(String declaringClass, String methodName) {
return new StackTraceElement(declaringClass, methodName, null, -1);
} |
java | public void sendRedirect303(String location) throws IOException{
HttpServletResponse resp = getProxiedHttpServletResponse();
if(resp instanceof IExtendedResponse) {
((IExtendedResponse)resp).sendRedirect303(location);
} else {
sendRedirect(location);
}
} |
python | def build_referenceWCS(catalog_list):
""" Compute default reference WCS from list of Catalog objects.
"""
wcslist = []
for catalog in catalog_list:
for scichip in catalog.catalogs:
wcslist.append(catalog.catalogs[scichip]['wcs'])
return utils.output_wcs(wcslist) |
java | private ResourceType getResourceType(String resourceTag) {
if (resourceTag == null || !resourceTag.endsWith("-resource")) {
return ResourceType.unknown;
}
try {
return ResourceType.valueOf(resourceTag.substring(0, resourceTag.length() - 9));
} catch (Exception e) {
return ResourceType.unknown;
}
} |
java | private Observable<HttpClientResponse<O>> submitToServerInURI(
HttpClientRequest<I> request, IClientConfig requestConfig, ClientConfig config,
RetryHandler errorHandler, ExecutionContext<HttpClientRequest<I>> context) {
// First, determine server from the URI
URI uri;
try {
uri = new URI(request.getUri());
} catch (URISyntaxException e) {
return Observable.error(e);
}
String host = uri.getHost();
if (host == null) {
return null;
}
int port = uri.getPort();
if (port < 0) {
if (Optional.ofNullable(clientConfig.get(IClientConfigKey.Keys.IsSecure)).orElse(false)) {
port = 443;
} else {
port = 80;
}
}
return LoadBalancerCommand.<HttpClientResponse<O>>builder()
.withRetryHandler(errorHandler)
.withLoadBalancerContext(lbContext)
.withListeners(listeners)
.withExecutionContext(context)
.withServer(new Server(host, port))
.build()
.submit(this.requestToOperation(request, getRxClientConfig(requestConfig, config)));
} |
python | def _Scroll(self, lines=None):
"""Set attributes to scroll the buffer correctly.
Args:
lines: An int, number of lines to scroll. If None, scrolls
by the terminal length.
"""
if lines is None:
lines = self._cli_lines
if lines < 0:
self._displayed -= self._cli_lines
self._displayed += lines
if self._displayed < 0:
self._displayed = 0
self._lines_to_show = self._cli_lines
else:
self._lines_to_show = lines
self._lastscroll = lines |
python | async def listener(self, channel):
"""
Single-channel listener
"""
while True:
message = await self.channel_layer.receive(channel)
if not message.get("type", None):
raise ValueError("Worker received message with no type.")
# Make a scope and get an application instance for it
scope = {"type": "channel", "channel": channel}
instance_queue = self.get_or_create_application_instance(channel, scope)
# Run the message into the app
await instance_queue.put(message) |
python | def _check_preconditions(self,
state: Sequence[tf.Tensor],
action: Sequence[tf.Tensor],
bound_constraints: Dict[str, Constraints],
default: Sequence[tf.Tensor]) -> Tuple[tf.Tensor, Sequence[tf.Tensor], tf.Tensor]:
'''Samples action fluents until all preconditions are satisfied.
Checks action preconditions for the sampled `action` and current `state`,
and iff all preconditions are satisfied it returns the sampled action fluents.
Args:
state (Sequence[tf.Tensor]): A list of state fluents.
action (Sequence[tf.Tensor]): A list of action fluents.
bound_constraints (Dict[str, Tuple[Optional[TensorFluent], Optional[TensorFluent]]]): The bounds for each action fluent.
default (Sequence[tf.Tensor]): The default action fluents.
Returns:
Tuple[tf.Tensor, Sequence[tf.Tensor], tf.Tensor]: A tuple with
an integer tensor corresponding to the number of samples,
action fluents and a boolean tensor for checking all action preconditions.
'''
def condition(i, a, checking):
not_checking = tf.reduce_any(tf.logical_not(checking))
return not_checking
def body(i, a, checking):
new_action = []
new_sampled_action = self._sample_action(bound_constraints, default)
new_preconds_checking = self.compiler.compile_action_preconditions_checking(state, new_sampled_action)
for action_fluent, new_sampled_action_fluent in zip(a, new_sampled_action):
new_action_fluent = tf.where(checking, action_fluent, new_sampled_action_fluent)
new_action.append(new_action_fluent)
new_action = tuple(new_action)
new_checking = tf.logical_or(checking, new_preconds_checking)
return (i + 1, new_action, new_checking)
i0 = tf.constant(0)
preconds_checking = self.compiler.compile_action_preconditions_checking(state, action)
return tf.while_loop(condition, body, loop_vars=[i0, action, preconds_checking]) |
python | def next_workday(dt):
"""
returns next weekday used for observances
"""
dt += timedelta(days=1)
while dt.weekday() > 4:
# Mon-Fri are 0-4
dt += timedelta(days=1)
return dt |
python | def ctrl_transfer(self,
dev_handle,
bmRequestType,
bRequest,
wValue,
wIndex,
data,
timeout):
r"""Perform a control transfer on the endpoint 0.
The direction of the transfer is inferred from the bmRequestType
field of the setup packet.
dev_handle is the value returned by the open_device() method.
bmRequestType, bRequest, wValue and wIndex are the same fields
of the setup packet. data is an array object, for OUT requests
it contains the bytes to transmit in the data stage and for
IN requests it is the buffer to hold the data read. The number
of bytes requested to transmit or receive is equal to the length
of the array times the data.itemsize field. The timeout parameter
specifies a time limit to the operation in miliseconds.
Return the number of bytes written (for OUT transfers) or the data
read (for IN transfers), as an array.array object.
"""
_not_implemented(self.ctrl_transfer) |
python | def _check_list_minions(self, expr, greedy, ignore_missing=False): # pylint: disable=unused-argument
'''
Return the minions found by looking via a list
'''
if isinstance(expr, six.string_types):
expr = [m for m in expr.split(',') if m]
minions = self._pki_minions()
return {'minions': [x for x in expr if x in minions],
'missing': [] if ignore_missing else [x for x in expr if x not in minions]} |
java | @Override
public int compare(final Orderable<T> orderable1, final Orderable<T> orderable2) {
return orderable1.getOrder().compareTo(orderable2.getOrder());
} |
python | def delete_efs_by_id(efs_id):
"""Deletion sometimes fails, try several times."""
start_time = time.time()
efs_client = get_efs_client()
sys.stdout.write("deleting %s ... " % (efs_id,))
while True:
try:
response = efs_client.delete_file_system(FileSystemId=efs_id)
if is_good_response(response):
print("succeeded")
break
time.sleep(RETRY_INTERVAL_SEC)
except Exception as e:
print("Failed with %s" % (e,))
if time.time() - start_time - RETRY_INTERVAL_SEC < RETRY_TIMEOUT_SEC:
print("Retrying in %s sec" % (RETRY_INTERVAL_SEC,))
time.sleep(RETRY_INTERVAL_SEC)
else:
print("Giving up")
break |
java | public static LogFactory set(LogFactory logFactory) {
logFactory.getLog(GlobalLogFactory.class).debug("Custom Use [{}] Logger.", logFactory.name);
currentLogFactory = logFactory;
return currentLogFactory;
} |
java | public static ObfuscatedData fromString(String obfuscatedString) {
String[] parts = obfuscatedString.split("\\$");
if (parts.length != 5) {
throw new IllegalArgumentException("Invalid obfuscated data");
}
if (!parts[1].equals(SIGNATURE)) {
throw new IllegalArgumentException("Invalid obfuscated data");
}
return new ObfuscatedData(Integer.parseInt(parts[2]), Base64.decode(parts[3]), Base64.decode(parts[4]));
} |
python | def get_category(self, metric):
"""
Return a string category for the metric.
The category is made up of this reporter's prefix and the
metric's group and tags.
Examples:
prefix = 'foo', group = 'bar', tags = {'a': 1, 'b': 2}
returns: 'foo.bar.a=1,b=2'
prefix = 'foo', group = 'bar', tags = None
returns: 'foo.bar'
prefix = None, group = 'bar', tags = None
returns: 'bar'
"""
tags = ','.join('%s=%s' % (k, v) for k, v in
sorted(metric.metric_name.tags.items()))
return '.'.join(x for x in
[self._prefix, metric.metric_name.group, tags] if x) |
java | @Benchmark
public int unionAndIter(BitmapsForUnion state)
{
ImmutableBitmap intersection = factory.union(Arrays.asList(state.bitmaps));
return iter(intersection);
} |
java | public static <T> Transformer<T, T> removePairs(
final Func1<? super T, Boolean> isCandidateForFirst,
final Func2<? super T, ? super T, Boolean> remove) {
return new Transformer<T, T>() {
@Override
public Observable<T> call(Observable<T> o) {
return o.compose(Transformers. //
stateMachine() //
.initialState(Optional.<T> absent()) //
.transition(new Transition<Optional<T>, T, T>() {
@Override
public Optional<T> call(Optional<T> state, T value,
Subscriber<T> subscriber) {
if (!state.isPresent()) {
if (isCandidateForFirst.call(value)) {
return Optional.of(value);
} else {
subscriber.onNext(value);
return Optional.absent();
}
} else {
if (remove.call(state.get(), value)) {
// emit nothing and reset state
return Optional.absent();
} else {
subscriber.onNext(state.get());
if (isCandidateForFirst.call(value)) {
return Optional.of(value);
} else {
subscriber.onNext(value);
return Optional.absent();
}
}
}
}
}).completion(new Completion<Optional<T>, T>() {
@Override
public Boolean call(Optional<T> state, Subscriber<T> subscriber) {
if (state.isPresent())
subscriber.onNext(state.get());
// yes, complete
return true;
}
}).build());
}
};
} |
python | def download_sample_and_align(job, sample, inputs, ids):
"""
Downloads the sample and runs BWA-kit
:param JobFunctionWrappingJob job: Passed by Toil automatically
:param tuple(str, list) sample: UUID and URLS for sample
:param Namespace inputs: Contains input arguments
:param dict ids: FileStore IDs for shared inputs
"""
uuid, urls = sample
r1_url, r2_url = urls if len(urls) == 2 else (urls[0], None)
job.fileStore.logToMaster('Downloaded sample: {0}. R1 {1}\nR2 {2}\nStarting BWA Run'.format(uuid, r1_url, r2_url))
# Read fastq samples from file store
ids['r1'] = job.addChildJobFn(download_url_job, r1_url, s3_key_path=inputs.ssec, disk=inputs.file_size).rv()
if r2_url:
ids['r2'] = job.addChildJobFn(download_url_job, r2_url, s3_key_path=inputs.ssec, disk=inputs.file_size).rv()
else:
ids['r2'] = None
# Create config for bwakit
inputs.cores = min(inputs.maxCores, multiprocessing.cpu_count())
inputs.uuid = uuid
config = dict(**vars(inputs)) # Create config as a copy of inputs since it has values we want
config.update(ids) # Overwrite attributes with the FileStoreIDs from ids
config = argparse.Namespace(**config)
# Define and wire job functions
bam_id = job.wrapJobFn(run_bwakit, config, sort=inputs.sort, trim=inputs.trim,
disk=inputs.file_size, cores=inputs.cores)
job.addFollowOn(bam_id)
output_name = uuid + '.bam' + str(inputs.suffix) if inputs.suffix else uuid + '.bam'
if urlparse(inputs.output_dir).scheme == 's3':
bam_id.addChildJobFn(s3am_upload_job, file_id=bam_id.rv(), file_name=output_name, s3_dir=inputs.output_dir,
s3_key_path=inputs.ssec, cores=inputs.cores, disk=inputs.file_size)
else:
mkdir_p(inputs.ouput_dir)
bam_id.addChildJobFn(copy_file_job, name=output_name, file_id=bam_id.rv(), output_dir=inputs.output_dir,
disk=inputs.file_size) |
java | public static String getSearchFilePattern(final String... fileExtensions)
{
if (fileExtensions.length == 0)
{
return "";
}
final String searchFilePatternPrefix = "([^\\s]+(\\.(?i)(";
final String searchFilePatternSuffix = "))$)";
final StringBuilder sb = new StringBuilder();
int count = 1;
for (final String fileExtension : fileExtensions)
{
if (count < fileExtensions.length)
{
sb.append(fileExtension).append("|");
}
else
{
sb.append(fileExtension);
}
count++;
}
return searchFilePatternPrefix + sb.toString().trim() + searchFilePatternSuffix;
} |
python | def _refresh_state(self):
""" Get the state of a job. If the job is complete this does nothing;
otherwise it gets a refreshed copy of the job resource.
"""
# TODO(gram): should we put a choke on refreshes? E.g. if the last call was less than
# a second ago should we return the cached value?
if self._is_complete:
return
try:
response = self._api.jobs_get(self._job_id)
except Exception as e:
raise e
if 'status' in response:
status = response['status']
if 'state' in status and status['state'] == 'DONE':
self._end_time = datetime.datetime.utcnow()
self._is_complete = True
self._process_job_status(status)
if 'statistics' in response:
statistics = response['statistics']
start_time = statistics.get('creationTime', None)
end_time = statistics.get('endTime', None)
if start_time and end_time and end_time >= start_time:
self._start_time = datetime.datetime.fromtimestamp(float(start_time) / 1000.0)
self._end_time = datetime.datetime.fromtimestamp(float(end_time) / 1000.0) |
java | @Override
public DataBuffer relocateConstantSpace(DataBuffer dataBuffer) {
// we always assume that data is sync, and valid on host side
Integer deviceId = AtomicAllocator.getInstance().getDeviceId();
ensureMaps(deviceId);
if (dataBuffer instanceof CudaIntDataBuffer) {
int[] data = dataBuffer.asInt();
return getConstantBuffer(data, DataType.INT);
} else if (dataBuffer instanceof CudaFloatDataBuffer) {
float[] data = dataBuffer.asFloat();
return getConstantBuffer(data, DataType.FLOAT);
} else if (dataBuffer instanceof CudaDoubleDataBuffer) {
double[] data = dataBuffer.asDouble();
return getConstantBuffer(data, DataType.DOUBLE);
} else if (dataBuffer instanceof CudaHalfDataBuffer) {
float[] data = dataBuffer.asFloat();
return getConstantBuffer(data, DataType.HALF);
} else if (dataBuffer instanceof CudaLongDataBuffer) {
long[] data = dataBuffer.asLong();
return getConstantBuffer(data, DataType.LONG);
}
throw new IllegalStateException("Unknown CudaDataBuffer opType");
} |
java | @com.fasterxml.jackson.annotation.JsonProperty("ErrorDetails")
public void setErrorDetails(java.util.Collection<ErrorDetail> errorDetails) {
if (errorDetails == null) {
this.errorDetails = null;
return;
}
this.errorDetails = new java.util.ArrayList<ErrorDetail>(errorDetails);
} |
java | public int getProcessExitCode()
{
// Make sure it's terminated
try
{
ffmpeg.waitFor();
}
catch (InterruptedException ex)
{
LOG.warn("Interrupted during waiting on process, forced shutdown?", ex);
}
return ffmpeg.exitValue();
} |
java | private final void _remove(final BehindRef removeref)
{
if (_firstLinkBehind != null)
{
if (removeref == _firstLinkBehind)
{
// It's the first in the list ...
if (removeref == _lastLinkBehind)
{
// ... and the only entry, the list is now empty
_firstLinkBehind = null;
_lastLinkBehind = null;
}
else
{
// ... and there are more entries, the first will change
BehindRef nextref = removeref._next;
removeref._next = null;
nextref._prev = null;
_firstLinkBehind = nextref;
}
}
else if (removeref == _lastLinkBehind)
{
// It's the list in the list and not the first also, the last will change
BehindRef prevref = removeref._prev;
removeref._prev = null;
prevref._next = null;
_lastLinkBehind = prevref;
}
else
{
// It's in the middle of the list
BehindRef prevref = removeref._prev;
BehindRef nextref = removeref._next;
removeref._next = null;
removeref._prev = null;
prevref._next = nextref;
nextref._prev = prevref;
}
}
} |
java | public T newProxy() {
Object proxy = Proxy.newProxyInstance(classLoader, exportInterfaces, this);
return clazz.cast(proxy);
} |
java | public ListenableFuture<OperationResult<Void>> execute(final MutationBatch m) throws WalException {
final WriteAheadEntry walEntry = wal.createEntry();
walEntry.writeMutation(m);
return executeWalEntry(walEntry, m);
} |
java | public void setLog(String log) throws ApplicationException {
if (StringUtil.isEmpty(log, true)) return;
this.log = log.trim();
// throw new ApplicationException("invalid value for attribute log ["+log+"]","valid values are
// [application, scheduler,console]");
} |
python | def radius_of_gyration(neurite):
'''Calculate and return radius of gyration of a given neurite.'''
centre_mass = neurite_centre_of_mass(neurite)
sum_sqr_distance = 0
N = 0
dist_sqr = [distance_sqr(centre_mass, s) for s in nm.iter_segments(neurite)]
sum_sqr_distance = np.sum(dist_sqr)
N = len(dist_sqr)
return np.sqrt(sum_sqr_distance / N) |
java | public <T extends R> T get(CheckedSupplier<T> supplier) {
return call(execution -> Assert.notNull(supplier, "supplier"));
} |
python | def get_port_profile_status_input_port_profile_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_profile_status = ET.Element("get_port_profile_status")
config = get_port_profile_status
input = ET.SubElement(get_port_profile_status, "input")
port_profile_name = ET.SubElement(input, "port-profile-name")
port_profile_name.text = kwargs.pop('port_profile_name')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
python | def send_email(to=None, message=None, template='base',
context={}, subject=None):
"""
Generic Method to Send Emails from template in an easier and modular way
:param to: Email Address to send the email message
:param message: Message content that is added to context
:param template: Path of the email template (Without extension)
:param context: Dict context variables to send to the template
:param subject: Email subject
"""
from_email = settings.DEFAULT_FROM_EMAIL
if to is None:
if len(settings.ADMINS) > 0:
to = settings.ADMINS[0][1]
else:
raise AttributeError("Not Admins defined")
if isinstance(to, (tuple, str)) or isinstance(to, (list, str)):
pass
elif unicode:
if not isinstance(to, unicode):
raise TypeError(
"email_to parameter has to be a List, Tuple or a String")
else:
raise TypeError(
"email_to parameter has to be a List, Tuple or a String")
email_to = to if isinstance(to, tuple) else (to,)
context.update(get_default_context())
if message is not None:
context.update({'message': message})
try:
email_template = get_email_template(template)
except EmailTemplateNotFound:
email_template = get_email_template('email/base')
email_subject = subject or "System Notification"
if email_template.get('txt'):
template_txt = email_template.get('txt')
msg = EmailMultiAlternatives(
email_subject,
template_txt.render(context), from_email, email_to)
if email_template.get('html'):
template_html = email_template.get('html')
html_content = template_html.render(context)
msg.attach_alternative(html_content, 'text/html')
return msg.send()
else:
raise AttributeError(".txt template does not exist")
raise Exception("Could Not Send Email") |
python | def get_datasets(self):
# type: () -> List[hdx.data.dataset.Dataset]
"""Get any datasets in the showcase
Returns:
List[Dataset]: List of datasets
"""
assoc_result, datasets_dicts = self._read_from_hdx('showcase', self.data['id'], fieldname='showcase_id',
action=self.actions()['list_datasets'])
datasets = list()
if assoc_result:
for dataset_dict in datasets_dicts:
dataset = hdx.data.dataset.Dataset(dataset_dict, configuration=self.configuration)
datasets.append(dataset)
return datasets |
java | public static final void varDataDump(Var2Data data, Integer id, boolean dumpShort, boolean dumpInt, boolean dumpDouble, boolean dumpTimeStamp, boolean dumpUnicodeString, boolean dumpString)
{
System.out.println("VARDATA");
for (int i = 0; i < 500; i++)
{
if (dumpShort)
{
try
{
int sh = data.getShort(id, Integer.valueOf(i));
System.out.println(i + ":" + sh);
}
catch (Exception ex)
{
// Silently ignore exceptions
}
}
if (dumpInt)
{
try
{
int sh = data.getInt(id, Integer.valueOf(i));
System.out.println(i + ":" + sh);
}
catch (Exception ex)
{
// Silently ignore exceptions
}
}
if (dumpDouble)
{
try
{
double d = data.getDouble(id, Integer.valueOf(i));
System.out.println(i + ":" + d);
System.out.println(i + ":" + d / 60000);
}
catch (Exception ex)
{
// Silently ignore exceptions
}
}
if (dumpTimeStamp)
{
try
{
Date d = data.getTimestamp(id, Integer.valueOf(i));
if (d != null)
{
System.out.println(i + ":" + d.toString());
}
}
catch (Exception ex)
{
// Silently ignore exceptions
}
}
if (dumpUnicodeString)
{
try
{
String s = data.getUnicodeString(id, Integer.valueOf(i));
if (s != null)
{
System.out.println(i + ":" + s);
}
}
catch (Exception ex)
{
// Silently ignore exceptions
}
}
if (dumpString)
{
try
{
String s = data.getString(id, Integer.valueOf(i));
if (s != null)
{
System.out.println(i + ":" + s);
}
}
catch (Exception ex)
{
// Silently ignore exceptions
}
}
}
} |
java | public static DescriptionDescriptor createDescription(DescriptionType descriptionType, Store store) {
DescriptionDescriptor descriptionDescriptor = store.create(DescriptionDescriptor.class);
descriptionDescriptor.setLang(descriptionType.getLang());
descriptionDescriptor.setValue(descriptionType.getValue());
return descriptionDescriptor;
} |
python | def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize, position0, momentum0):
"""
Recursively builds a tree for proposing new position and momentum
"""
if depth == 0:
position_bar, momentum_bar, candidate_set_size, accept_set_bool =\
self._initalize_tree(position, momentum, slice_var, direction * stepsize)
alpha = min(1, self._acceptance_prob(position, position_bar, momentum, momentum_bar))
return (position_bar, momentum_bar, position_bar, momentum_bar, position_bar,
candidate_set_size, accept_set_bool, alpha, 1)
else:
(position_backward, momentum_backward, position_forward, momentum_forward, position_bar,
candidate_set_size, accept_set_bool, alpha, n_alpha) =\
self._build_tree(position, momentum, slice_var,
direction, depth - 1, stepsize, position0, momentum0)
if accept_set_bool == 1:
if direction == -1:
# Build tree in backward direction
(position_backward, momentum_backward, _, _, position_bar2, candidate_set_size2, accept_set_bool2,
alpha2, n_alpha2) = self._build_tree(position_backward, momentum_backward, slice_var, direction,
depth - 1, stepsize, position0, momentum0)
else:
# Build tree in forward direction
(_, _, position_forward, momentum_forward, position_bar2, candidate_set_size2, accept_set_bool2,
alpha2, n_alpha2) = self._build_tree(position_forward, momentum_forward, slice_var, direction,
depth - 1, stepsize, position0, momentum0)
if np.random.rand() < candidate_set_size2 / (candidate_set_size2 + candidate_set_size):
position_bar = position_bar2
alpha += alpha2
n_alpha += n_alpha2
accept_set_bool, candidate_set_size =\
self._update_acceptance_criteria(position_forward, position_backward, momentum_forward,
momentum_backward, accept_set_bool2, candidate_set_size,
candidate_set_size2)
return (position_backward, momentum_backward, position_forward, momentum_forward, position_bar,
candidate_set_size, accept_set_bool, alpha, n_alpha) |
java | protected TicketGrantingTicket createTicketGrantingTicketForRequest(final MultiValueMap<String, String> requestBody,
final HttpServletRequest request) {
val credential = this.credentialFactory.fromRequest(request, requestBody);
if (credential == null || credential.isEmpty()) {
throw new BadRestRequestException("No credentials are provided or extracted to authenticate the REST request");
}
val service = this.serviceFactory.createService(request);
val authenticationResult =
authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(service, credential);
return centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
} |
java | @Override
public void delete(IEntityLock lock) throws LockingException {
Map m = getLockCache(lock.getEntityType());
synchronized (m) {
m.remove(getCacheKey(lock));
}
} |
python | def all_subnets_shorter_prefix(ip_net, cidr, include_default=False):
"""
Function to return every subnet a ip can belong to with a shorter prefix
Args:
ip_net: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1
cidr: CIDR value of 0 to 32
include_default: If you want the list to inlclude the default route set to True
Returns: returns a list of subnets
"""
subnets_list = list()
if include_default:
while int(cidr) >= 0:
try:
subnets_list.append('%s/%s' % (whole_subnet_maker(ip_net, cidr), cidr))
except Exception as e:
LOGGER.critical('Function all_subnets_shorter_prefix {item}'.format(item=e))
cidr = str(int(cidr) - 1)
else:
while int(cidr) > 0:
try:
subnets_list.append('%s/%s' % (whole_subnet_maker(ip_net, cidr), cidr))
except Exception as e:
LOGGER.critical('Function all_subnets_shorter_prefix {item}'.format(item=e))
cidr = str(int(cidr) - 1)
return subnets_list |
java | public Content getNavLinkNext() {
Content li;
if (next == null) {
li = HtmlTree.LI(nextpackageLabel);
} else {
DocPath path = DocPath.relativePath(packageDoc, next);
li = HtmlTree.LI(getHyperLink(path.resolve(DocPaths.profilePackageSummary(profileName)),
nextpackageLabel, "", ""));
}
return li;
} |
python | async def get_supported_methods(self):
"""Get information about supported methods.
Calling this as the first thing before doing anything else is
necessary to fill the available services table.
"""
response = await self.request_supported_methods()
if "result" in response:
services = response["result"][0]
_LOGGER.debug("Got %s services!" % len(services))
for x in services:
serv = await Service.from_payload(
x, self.endpoint, self.idgen, self.debug, self.force_protocol
)
if serv is not None:
self.services[x["service"]] = serv
else:
_LOGGER.warning("Unable to create service %s", x["service"])
for service in self.services.values():
if self.debug > 1:
_LOGGER.debug("Service %s", service)
for api in service.methods:
# self.logger.debug("%s > %s" % (service, api))
if self.debug > 1:
_LOGGER.debug("> %s" % api)
return self.services
return None |
java | public Observable<CloudJob> getAsync(String jobId, JobGetOptions jobGetOptions) {
return getWithServiceResponseAsync(jobId, jobGetOptions).map(new Func1<ServiceResponseWithHeaders<CloudJob, JobGetHeaders>, CloudJob>() {
@Override
public CloudJob call(ServiceResponseWithHeaders<CloudJob, JobGetHeaders> response) {
return response.body();
}
});
} |
python | def parse_partial(self, data):
"""Incrementally decodes JSON data sets into Python objects.
Raises
------
~ipfsapi.exceptions.DecodingError
Returns
-------
generator
"""
try:
# Python 3 requires all JSON data to be a text string
lines = self._decoder1.decode(data, False).split("\n")
# Add first input line to last buffer line, if applicable, to
# handle cases where the JSON string has been chopped in half
# at the network level due to streaming
if len(self._buffer) > 0 and self._buffer[-1] is not None:
self._buffer[-1] += lines[0]
self._buffer.extend(lines[1:])
else:
self._buffer.extend(lines)
except UnicodeDecodeError as error:
raise exceptions.DecodingError('json', error)
# Process data buffer
index = 0
try:
# Process each line as separate buffer
#PERF: This way the `.lstrip()` call becomes almost always a NOP
# even if it does return a different string it will only
# have to allocate a new buffer for the currently processed
# line.
while index < len(self._buffer):
while self._buffer[index]:
# Make sure buffer does not start with whitespace
#PERF: `.lstrip()` does not reallocate if the string does
# not actually start with whitespace.
self._buffer[index] = self._buffer[index].lstrip()
# Handle case where the remainder of the line contained
# only whitespace
if not self._buffer[index]:
self._buffer[index] = None
continue
# Try decoding the partial data buffer and return results
# from this
data = self._buffer[index]
for index2 in range(index, len(self._buffer)):
# If decoding doesn't succeed with the currently
# selected buffer (very unlikely with our current
# class of input data) then retry with appending
# any other pending pieces of input data
# This will happen with JSON data that contains
# arbitrary new-lines: "{1:\n2,\n3:4}"
if index2 > index:
data += "\n" + self._buffer[index2]
try:
(obj, offset) = self._decoder2.raw_decode(data)
except ValueError:
# Treat error as fatal if we have already added
# the final buffer to the input
if (index2 + 1) == len(self._buffer):
raise
else:
index = index2
break
# Decoding succeeded – yield result and shorten buffer
yield obj
if offset < len(self._buffer[index]):
self._buffer[index] = self._buffer[index][offset:]
else:
self._buffer[index] = None
index += 1
except ValueError as error:
# It is unfortunately not possible to reliably detect whether
# parsing ended because of an error *within* the JSON string, or
# an unexpected *end* of the JSON string.
# We therefor have to assume that any error that occurs here
# *might* be related to the JSON parser hitting EOF and therefor
# have to postpone error reporting until `parse_finalize` is
# called.
self._lasterror = error
finally:
# Remove all processed buffers
del self._buffer[0:index] |
java | @Override
public BulkPublishResult bulkPublish(BulkPublishRequest request) {
request = beforeClientExecution(request);
return executeBulkPublish(request);
} |
python | def sniff_extension(file_path,verbose=True):
'''sniff_extension will attempt to determine the file type based on the extension,
and return the proper mimetype
:param file_path: the full path to the file to sniff
:param verbose: print stuff out
'''
mime_types = { "xls": 'application/vnd.ms-excel',
"xlsx": 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
"xml": 'text/xml',
"ods": 'application/vnd.oasis.opendocument.spreadsheet',
"csv": 'text/plain',
"tmpl": 'text/plain',
"pdf": 'application/pdf',
"php": 'application/x-httpd-php',
"jpg": 'image/jpeg',
"png": 'image/png',
"gif": 'image/gif',
"bmp": 'image/bmp',
"txt": 'text/plain',
"doc": 'application/msword',
"js": 'text/js',
"swf": 'application/x-shockwave-flash',
"mp3": 'audio/mpeg',
"zip": 'application/zip',
"simg": 'application/zip',
"rar": 'application/rar',
"tar": 'application/tar',
"arj": 'application/arj',
"cab": 'application/cab',
"html": 'text/html',
"htm": 'text/html',
"default": 'application/octet-stream',
"folder": 'application/vnd.google-apps.folder',
"img" : "application/octet-stream" }
ext = os.path.basename(file_path).split('.')[-1]
mime_type = mime_types.get(ext,None)
if mime_type == None:
mime_type = mime_types['txt']
if verbose==True:
bot.info("%s --> %s" %(file_path, mime_type))
return mime_type |
java | @GET
@Path("/health")
@Produces(MediaType.APPLICATION_JSON)
public HealthStatus health() throws ExecutionException, InterruptedException {
final HealthStatus status = new HealthStatus();
final Future<HealthDetails> dbStatus = healthDBService.dbStatus();
final Future<List<HealthDetails>> networkStatus = healthNetworkService.networkStatus();
status.add(dbStatus.get());
networkStatus.get().forEach(status::add);
return status;
} |
python | def delete_char(self, e): # (C-d)
u"""Delete the character at point. If point is at the beginning of
the line, there are no characters in the line, and the last
character typed was not bound to delete-char, then return EOF."""
self.l_buffer.delete_char(self.argument_reset)
self.finalize() |
java | public PaymillList<Payment> list( Integer count, Integer offset ) {
return this.list( null, null, count, offset );
} |
java | public void addAlias(CmsDbContext dbc, CmsProject project, CmsAlias alias) throws CmsException {
I_CmsVfsDriver vfsDriver = getVfsDriver(dbc);
vfsDriver.insertAlias(dbc, project, alias);
} |
java | @Override
public Optional<Field> indexedField(String name, Double value) {
DoubleField doubleField = new DoubleField(name, value, STORE);
doubleField.setBoost(boost);
return Optional.of(doubleField);
} |
java | @Override
public boolean add(S solution) {
boolean solutionInserted = false ;
if (solutionList.size() == 0) {
solutionList.add(solution) ;
solutionInserted = true ;
} else {
Iterator<S> iterator = solutionList.iterator();
boolean isDominated = false;
boolean isContained = false;
while (((!isDominated) && (!isContained)) && (iterator.hasNext())) {
S listIndividual = iterator.next();
int flag = dominanceComparator.compare(solution, listIndividual);
if (flag == -1) {
iterator.remove();
} else if (flag == 1) {
isDominated = true; // dominated by one in the list
} else if (flag == 0) {
int equalflag = equalSolutions.compare(solution, listIndividual);
if (equalflag == 0) // solutions are equals
isContained = true;
}
}
if (!isDominated && !isContained) {
solutionList.add(solution);
solutionInserted = true;
}
return solutionInserted;
}
return solutionInserted ;
} |
java | public static Class<?> getPrimitiveClass(final Object object) {
if (object == null) {
return null;
}
return getPrimitiveClass(object.getClass());
} |
java | public static ClassFile buildClassFile(String className, Class<?>[] classes)
throws IllegalArgumentException
{
return buildClassFile(className, classes, null, null, OBSERVER_DISABLED);
} |
python | def retain_identities(retention_time, es_enrichment_url, sortinghat_db, data_source, active_data_sources):
"""Select the unique identities not seen before `retention_time` and
delete them from SortingHat. Furthermore, it deletes also the orphan unique identities,
those ones stored in SortingHat but not in IDENTITIES_INDEX.
:param retention_time: maximum number of minutes wrt the current date to retain the identities
:param es_enrichment_url: URL of the ElasticSearch where the enriched data is stored
:param sortinghat_db: instance of the SortingHat database
:param data_source: target data source (e.g., git, github, slack)
:param active_data_sources: list of active data sources
"""
before_date = get_diff_current_date(minutes=retention_time)
before_date_str = before_date.isoformat()
es = Elasticsearch([es_enrichment_url], timeout=120, max_retries=20, retry_on_timeout=True, verify_certs=False)
# delete the unique identities which have not been seen after `before_date`
delete_inactive_unique_identities(es, sortinghat_db, before_date_str)
# delete the unique identities for a given data source which are not in the IDENTITIES_INDEX
delete_orphan_unique_identities(es, sortinghat_db, data_source, active_data_sources) |
python | def copy_from_model(cls, model_name, reference, **kwargs):
"""
Set-up a user-defined grid using specifications of a reference
grid model.
Parameters
----------
model_name : string
name of the user-defined grid model.
reference : string or :class:`CTMGrid` instance
Name of the reference model (see :func:`get_supported_models`),
or a :class:`CTMGrid` object from which grid set-up is copied.
**kwargs
Any set-up parameter which will override the settings of the
reference model (see :class:`CTMGrid` parameters).
Returns
-------
A :class:`CTMGrid` object.
"""
if isinstance(reference, cls):
settings = reference.__dict__.copy()
settings.pop('model')
else:
settings = _get_model_info(reference)
settings.pop('model_name')
settings.update(kwargs)
settings['reference'] = reference
return cls(model_name, **settings) |
java | @Check(CheckType.NORMAL)
public void checkMultipleCapacityUses(SarlCapacityUses uses) {
if (!isIgnored(REDUNDANT_CAPACITY_USE)) {
final XtendTypeDeclaration declaringType = uses.getDeclaringType();
if (declaringType != null) {
final Set<String> previousCapacityUses = doGetPreviousCapacities(uses,
declaringType.getMembers().iterator());
int index = 0;
for (final JvmTypeReference capacity : uses.getCapacities()) {
if (previousCapacityUses.contains(capacity.getIdentifier())) {
addIssue(MessageFormat.format(
Messages.SARLValidator_79,
capacity.getSimpleName()),
uses,
SARL_CAPACITY_USES__CAPACITIES,
index,
REDUNDANT_CAPACITY_USE,
capacity.getSimpleName());
} else {
previousCapacityUses.add(capacity.getIdentifier());
}
++index;
}
}
}
} |
python | def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_for_action("delete", self.remove_action_callback)
shortcut_manager.add_callback_for_action("add", self.add_action_callback)
shortcut_manager.add_callback_for_action("copy", self.copy_action_callback)
shortcut_manager.add_callback_for_action("cut", self.cut_action_callback)
shortcut_manager.add_callback_for_action("paste", self.paste_action_callback) |
python | def flow_tuple(data):
"""Tuple for flow (src, dst, sport, dport, proto)"""
src = net_utils.inet_to_str(data['packet'].get('src')) if data['packet'].get('src') else None
dst = net_utils.inet_to_str(data['packet'].get('dst')) if data['packet'].get('dst') else None
sport = data['transport'].get('sport') if data.get('transport') else None
dport = data['transport'].get('dport') if data.get('transport') else None
proto = data['transport'].get('type') if data.get('transport') else data['packet']['type']
return (src, dst, sport, dport, proto) |
java | public static Date addDays(Date date, int numberOfDays) {
return Date.from(date.toInstant().plus(numberOfDays, ChronoUnit.DAYS));
} |
java | @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (!httpAuth.isAllowed(req, resp)) {
return;
}
final long start = System.currentTimeMillis();
final CollectorController collectorController = new CollectorController(collectorServer);
final String application = collectorController.getApplication(req, resp);
I18N.bindLocale(req.getLocale());
try {
if (application == null) {
CollectorController.writeOnlyAddApplication(resp);
return;
}
if (!collectorServer.isApplicationDataAvailable(application)
&& HttpParameter.ACTION.getParameterFrom(req) == null) {
CollectorController.writeDataUnavailableForApplication(application, resp);
return;
}
collectorController.doMonitoring(req, resp, application);
} finally {
I18N.unbindLocale();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("monitoring from " + req.getRemoteAddr() + ", request="
+ req.getRequestURI()
+ (req.getQueryString() != null ? '?' + req.getQueryString() : "")
+ ", application=" + application + " in "
+ (System.currentTimeMillis() - start) + "ms");
}
}
} |
java | public static CmsJspContentAccessValueWrapper createWrapper(
CmsObject cms,
I_CmsXmlContentValue value,
I_CmsXmlDocument content,
String valueName,
Locale locale) {
if ((value != null) && (cms != null)) {
return new CmsJspContentAccessValueWrapper(cms, value);
}
if ((content != null) && (valueName != null) && (locale != null) && (cms != null)) {
CmsJspContentAccessValueWrapper wrapper = new CmsJspContentAccessValueWrapper();
wrapper.m_nullValueInfo = new NullValueInfo(content, valueName, locale);
wrapper.m_cms = cms;
return wrapper;
}
// if no value is available,
return NULL_VALUE_WRAPPER;
} |
java | public ServiceFuture<Void> deleteAsync(String thumbprintAlgorithm, String thumbprint, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromHeaderResponse(deleteWithServiceResponseAsync(thumbprintAlgorithm, thumbprint), serviceCallback);
} |
java | public void marshall(CreateAliasRequest createAliasRequest, ProtocolMarshaller protocolMarshaller) {
if (createAliasRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createAliasRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(createAliasRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(createAliasRequest.getRoutingStrategy(), ROUTINGSTRATEGY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def _print_results(file, status):
"""Print the download results.
Args:
file (str): The filename.
status (str): The file download status.
"""
file_color = c.Fore.GREEN
status_color = c.Fore.RED
if status == 'Success':
status_color = c.Fore.GREEN
elif status == 'Skipped':
status_color = c.Fore.YELLOW
print(
'{}{!s:<13}{}{!s:<35}{}{!s:<8}{}{}'.format(
c.Fore.CYAN,
'Downloading:',
file_color,
file,
c.Fore.CYAN,
'Status:',
status_color,
status,
)
) |
python | def enableHook(self, msgObj):
"""
Enable yank-pop.
This method is connected to the 'yank-qtmacs_text_edit' hook
(triggered by the yank macro) to ensure that yank-pop only
gets activated afterwards.
"""
self.killListIdx = len(qte_global.kill_list) - 2
self.qteMain.qtesigKeyseqComplete.connect(self.disableHook) |
python | def _unscaled_dist(self, X, X2=None):
"""
Compute the Euclidean distance between each row of X and X2, or between
each pair of rows of X if X2 is None.
"""
#X, = self._slice_X(X)
if X2 is None:
Xsq = np.sum(np.square(X),1)
r2 = -2.*tdot(X) + (Xsq[:,None] + Xsq[None,:])
util.diag.view(r2)[:,]= 0. # force diagnoal to be zero: sometime numerically a little negative
r2 = np.clip(r2, 0, np.inf)
return np.sqrt(r2)
else:
#X2, = self._slice_X(X2)
X1sq = np.sum(np.square(X),1)
X2sq = np.sum(np.square(X2),1)
r2 = -2.*np.dot(X, X2.T) + (X1sq[:,None] + X2sq[None,:])
r2 = np.clip(r2, 0, np.inf)
return np.sqrt(r2) |
python | def pushover(message, token, user, title="JCVI: Job Monitor", \
priority=0, timestamp=None):
"""
pushover.net python API
<https://pushover.net/faq#library-python>
"""
assert -1 <= priority <= 2, \
"Priority should be an int() between -1 and 2"
if timestamp == None:
from time import time
timestamp = int(time())
retry, expire = (300, 3600) if priority == 2 \
else (None, None)
conn = HTTPSConnection("api.pushover.net:443")
conn.request("POST", "/1/messages.json",
urlencode({
"token": token,
"user": user,
"message": message,
"title": title,
"priority": priority,
"timestamp": timestamp,
"retry": retry,
"expire": expire,
}), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse() |
java | protected TerminalSize getBounds(String[] lines, TerminalSize currentBounds) {
if(currentBounds == null) {
currentBounds = TerminalSize.ZERO;
}
currentBounds = currentBounds.withRows(lines.length);
if(labelWidth == null || labelWidth == 0) {
int preferredWidth = 0;
for(String line : lines) {
int lineWidth = TerminalTextUtils.getColumnWidth(line);
if(preferredWidth < lineWidth) {
preferredWidth = lineWidth;
}
}
currentBounds = currentBounds.withColumns(preferredWidth);
}
else {
List<String> wordWrapped = TerminalTextUtils.getWordWrappedText(labelWidth, lines);
currentBounds = currentBounds.withColumns(labelWidth).withRows(wordWrapped.size());
}
return currentBounds;
} |
python | def r_oauth_login(self):
"""
Route for OAuth2 Login
:param next next url
:type str
:return: Redirects to OAuth Provider Login URL
"""
session['next'] = request.args.get('next','')
callback_url = self.authcallback
if callback_url is None:
callback_url = url_for('.r_oauth_authorized', _external=True)
return self.authobj.authorize(callback=callback_url) |
java | private Map<String, Message> getMessages(Query qry, Folder folder, String[] uids, String[] messageNumbers, int startRow, int maxRow, boolean all) throws MessagingException {
Message[] messages = folder.getMessages();
Map<String, Message> map = qry == null ? new HashMap<String, Message>() : null;
int k = 0;
if (uids != null || messageNumbers != null) {
startRow = 0;
maxRow = -1;
}
Message message;
for (int l = startRow; l < messages.length; l++) {
if (maxRow != -1 && k == maxRow) {
break;
}
message = messages[l];
int messageNumber = message.getMessageNumber();
String id = getId(folder, message);
if (uids == null ? messageNumbers == null || contains(messageNumbers, messageNumber) : contains(uids, id)) {
k++;
if (qry != null) {
toQuery(qry, message, id, all);
}
else map.put(id, message);
}
}
return map;
} |
java | public static PolymerNotation getAntiparallel(PolymerNotation polymer)
throws RNAUtilsException, ChemistryException, NucleotideLoadingException {
checkRNA(polymer);
PolymerNotation reversePolymer;
try {
reversePolymer = SequenceConverter.readRNA(generateAntiparallel(polymer)).getCurrentPolymer();
reversePolymer = new PolymerNotation(reversePolymer.getPolymerID(), reversePolymer.getPolymerElements(),
"Antiparallel to " + polymer.getPolymerID().getId());
return reversePolymer;
} catch (NotationException | FastaFormatException | HELM2HandledException e) {
e.printStackTrace();
throw new RNAUtilsException("The reverse polymer can not be built");
}
} |
python | def _is_valid_relpath(
relpath,
maxdepth=None):
'''
Performs basic sanity checks on a relative path.
Requires POSIX-compatible paths (i.e. the kind obtained through
cp.list_master or other such calls).
Ensures that the path does not contain directory transversal, and
that it does not exceed a stated maximum depth (if specified).
'''
# Check relpath surrounded by slashes, so that `..` can be caught as
# a path component at the start, end, and in the middle of the path.
sep, pardir = posixpath.sep, posixpath.pardir
if sep + pardir + sep in sep + relpath + sep:
return False
# Check that the relative path's depth does not exceed maxdepth
if maxdepth is not None:
path_depth = relpath.strip(sep).count(sep)
if path_depth > maxdepth:
return False
return True |
java | public INDArray scoreExamples(MultiDataSet dataSet, boolean addRegularizationTerms) {
try{
return scoreExamplesHelper(dataSet, addRegularizationTerms);
} catch (OutOfMemoryError e){
CrashReportingUtil.writeMemoryCrashDump(this, e);
throw e;
}
} |
java | public static void removeStatsGroup(StatsGroup group)
throws StatsFactoryException {
if (tc.isEntryEnabled())
Tr.entry(tc, new StringBuffer("removeStatsGroup:name=").append(group.getName()).toString());
StatsFactoryUtil.unRegisterStats((PmiModule) group, group.getMBean());
if (tc.isEntryEnabled())
Tr.exit(tc, "removeStatsGroup");
} |
python | def message_received(request, backend_name):
"""Handle HTTP requests from Tropo.
"""
logger.debug("@@ request from Tropo - raw data: %s" % request.body)
try:
post = json.loads(request.body)
except ValueError:
logger.exception("EXCEPTION decoding post data in incoming request")
return HttpResponseBadRequest()
except Exception:
logger.exception("@@responding to tropo with error")
return HttpResponseServerError()
logger.debug("@@ Decoded data: %r" % post)
if 'session' not in post:
logger.error("@@HEY, post does not contain session, "
"what's going on?")
return HttpResponseBadRequest()
session = post['session']
parms = session.get('parameters', {})
if 'program' in parms:
# Execute a program that we passed to Tropo to pass back to us.
# Extract the program, while verifying it came from us and
# has not been modified.
try:
program = signing.loads(parms['program'])
except signing.BadSignature:
logger.exception("@@ received program with bad signature")
return HttpResponseBadRequest()
return HttpResponse(json.dumps(program))
if 'from' in session:
# Must have received a message
# FIXME: is there any way we can verify it's really Tropo calling us?
logger.debug("@@Got a text message")
try:
from_address = session['from']['id']
text = session['initialText']
logger.debug("@@Received message from %s: %s" %
(from_address, text))
# pass the message to RapidSMS
identity = from_address
connections = lookup_connections(backend_name, [identity])
receive(text, connections[0])
# Respond nicely to Tropo
program = json.dumps({"tropo": [{"hangup": {}}]})
logger.debug("@@responding to tropo with hangup")
return HttpResponse(program)
except Exception:
logger.exception("@@responding to tropo with error")
return HttpResponseServerError()
logger.error("@@No recognized command in request from Tropo")
return HttpResponseBadRequest() |
java | public void sendMailWithAttachment (String to, String subject, String content, String filename) throws MessagingException{
Properties props = new Properties();
props.put("mail.smtp.user", emailConfg.getUser());
props.put("mail.smtp.host", emailConfg.getHost());
props.put("mail.smtp.port", emailConfg.getPort());
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.debug", emailConfg.getDebug());
props.put("mail.smtp.auth", emailConfg.getAuth());
props.put("mail.smtp.ssl.trust", emailConfg.host);
SMTPAuthenticator auth = new SMTPAuthenticator(emailConfg.getUser(), (String)secret.get(SecretConstants.EMAIL_PASSWORD));
Session session = Session.getInstance(props, auth);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(emailConfg.getUser()));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText(content);
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
if(logger.isInfoEnabled()) logger.info("An email has been sent to " + to + " with subject " + subject);
} |
python | def filter(self, request, queryset, view):
""" Filter each resource separately using its own filter """
summary_queryset = queryset
filtered_querysets = []
for queryset in summary_queryset.querysets:
filter_class = self._get_filter(queryset)
queryset = filter_class(request.query_params, queryset=queryset).qs
filtered_querysets.append(queryset)
summary_queryset.querysets = filtered_querysets
return summary_queryset |
java | public static int calculateHeapSize(int memory, org.apache.flink.configuration.Configuration conf) {
float memoryCutoffRatio = conf.getFloat(ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_RATIO);
int minCutoff = conf.getInteger(ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN);
if (memoryCutoffRatio > 1 || memoryCutoffRatio < 0) {
throw new IllegalArgumentException("The configuration value '"
+ ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_RATIO.key()
+ "' must be between 0 and 1. Value given=" + memoryCutoffRatio);
}
if (minCutoff > memory) {
throw new IllegalArgumentException("The configuration value '"
+ ResourceManagerOptions.CONTAINERIZED_HEAP_CUTOFF_MIN.key()
+ "' is higher (" + minCutoff + ") than the requested amount of memory " + memory);
}
int heapLimit = (int) ((float) memory * memoryCutoffRatio);
if (heapLimit < minCutoff) {
heapLimit = minCutoff;
}
return memory - heapLimit;
} |
python | def extend_with(func):
"""Extends with class or function"""
if not func.__name__ in ArgParseInator._plugins:
ArgParseInator._plugins[func.__name__] = func |
python | def _property_names(self):
"""
Gather up properties and cached_properties which may be methods
that were decorated. Need to inspect class versions b/c doing
getattr on them could cause unwanted side effects.
"""
property_names = []
for name in dir(self):
try:
attr = getattr(type(self), name)
if isinstance(attr, property) or isinstance(attr, cached_property):
property_names.append(name)
except AttributeError:
pass
return property_names |
python | def sync(self, force=None):
"""Synchronize between the file in the file system and the field record"""
try:
if force:
sd = force
else:
sd = self.sync_dir()
if sd == self.SYNC_DIR.FILE_TO_RECORD:
if force and not self.exists():
return None
self.fs_to_record()
elif sd == self.SYNC_DIR.RECORD_TO_FILE:
self.record_to_fs()
else:
return None
self._dataset.config.sync[self.file_const][sd] = time.time()
return sd
except Exception as e:
self._bundle.rollback()
self._bundle.error("Failed to sync '{}': {}".format(self.file_const, e))
raise |
java | public static void add() {
String current = System.getProperties().getProperty(HANDLER_PKGS, "");
if (current.length() > 0) {
if (current.contains(PKG)) {
return;
}
current = current + "|";
}
System.getProperties().put(HANDLER_PKGS, current + PKG);
} |
java | public static void setUnsupported(SocketAddress remoteAddress, SessionProtocol protocol) {
final String key = key(remoteAddress);
final CacheEntry e = getOrCreate(key);
if (e.addUnsupported(protocol)) {
logger.debug("Updated: '{}' does not support {}", key, e);
}
} |
java | @Override
public <T extends BaseModel> T get(String path, Class<T> cls) throws IOException {
HttpGet getMethod = new HttpGet(UrlUtils.toJsonApiUri(uri, context, path));
HttpResponse response = client.execute(getMethod, localContext);
jenkinsVersion = ResponseUtils.getJenkinsVersion(response);
try {
httpResponseValidator.validateResponse(response);
return objectFromResponse(cls, response);
} finally {
EntityUtils.consume(response.getEntity());
releaseConnection(getMethod);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.