language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public boolean hasExtPros() {
Field[] fields = getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if (!(Modifier.isFinal(fields[i].getModifiers())
|| Modifier.isStatic(fields[i].getModifiers()))) { return true; }
}
return false;
} |
python | def simple_wait(func):
"""
Decorator for adding simple text wait animation to
long running functions.
Examples:
>>> @animation.simple_wait
>>> def long_running_function():
>>> ... 5 seconds later ...
>>> return
"""
@wraps(func)
def wrapper(*args, **kw... |
python | def get_td_qnm(template=None, taper=None, **kwargs):
"""Return a time domain damped sinusoid.
Parameters
----------
template: object
An object that has attached properties. This can be used to substitute
for keyword arguments. A common example would be a row in an xml table.
taper: ... |
java | public static void setMapScaleBar(MapView mapView,
DistanceUnitAdapter primaryDistanceUnitAdapter,
DistanceUnitAdapter secondaryDistanceUnitAdapter) {
if (null == primaryDistanceUnitAdapter && null == secondaryDistanceUnitAdapter) {
... |
python | def safe_temp_edit(filename):
"""Safely modify a file within context that automatically reverts any changes afterwards
The file mutatation occurs in place. The file is backed up in a temporary file before edits
occur and when the context is closed, the mutated file is discarded and replaced with the backup.
W... |
java | public E pop() {
modCount++;
if (size == 0) {
throw new NoSuchElementException();
}
size--;
if (cntInBucket == 1) {
cntInBucket = bucketSize;
return buckets.removeLast()[0];
}
return buckets.getLast()[--cntInBucket];
} |
java | public boolean isTypeMatch(String commandId, Class targetType) {
Assert.notNull(commandId, "commandId");
Assert.notNull(targetType, "targetType");
Class commandType = getType(commandId);
if (commandType == null) {
return false;
}
els... |
java | private Method findDataProvider() throws PerfidixMethodCheckException {
final Bench benchAnno = getMethodToBench().getAnnotation(Bench.class);
Method dataProvider = null;
if (benchAnno != null && !benchAnno.dataProvider().equals("")) {
try {
// Getting the String name for the dataProvider
final String... |
python | def timeit(hosts=None,
stmt=None,
warmup=30,
repeat=None,
duration=None,
concurrency=1,
output_fmt=None,
fail_if=None,
sample_mode='reservoir'):
"""Run the given statement a number of times and return the runtime stats
Args... |
python | def get_count(self, request, notifications, mark_as_read=False):
""" return count of unread notification """
return Response({'count': notifications.filter(is_read=False).count()}) |
python | def _monthly_operation(self, operation, percentile=0):
"""Get a MonthlyCollection given a certain operation."""
# Retrive the correct operation.
if operation == 'average':
funct = self._average
elif operation == 'total':
funct = self._total
else:
... |
java | public static synchronized Grammar getMainGrammar() {
if (mainGrammar == null) {
// Create it...
try {
final Grammar root = new XmlGrammar("ROOT", null, null, XmlGrammar.class.getClassLoader());
final InputStream inpt = XmlGrammar.class.getResourceAsStream(MAIN_GRAMMAR_LOCATI... |
java | public void marshall(SetSourceRequest setSourceRequest, ProtocolMarshaller protocolMarshaller) {
if (setSourceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(setSourceRequest.getDecryption(... |
java | public <V extends Enum<V>> TextAccessor getTextForms(
String name,
Class<V> type,
String... variants
) {
if (this.mre != null) {
throw new MissingResourceException(
this.mre.getMessage(),
this.mre.getClassName(),
this.mre.g... |
java | @Override
public UpdateObjectAttributesResult updateObjectAttributes(UpdateObjectAttributesRequest request) {
request = beforeClientExecution(request);
return executeUpdateObjectAttributes(request);
} |
java | public static BinaryString blankString(int length) {
byte[] spaces = new byte[length];
Arrays.fill(spaces, (byte) ' ');
return fromBytes(spaces);
} |
python | def enter_proc(self, lineno):
""" Enters (pushes) a new context
"""
self.local_labels.append({}) # Add a new context
self.scopes.append(lineno)
__DEBUG__('Entering scope level %i at line %i' % (len(self.scopes), lineno)) |
python | def register_project(self, path, ensure_uniqueness=False):
"""
Registers given path in the Model as a project.
:param path: Project path to register.
:type path: unicode
:param ensure_uniqueness: Ensure registrar uniqueness.
:type ensure_uniqueness: bool
:return:... |
python | def get_valid_filename(s):
"""
like the regular get_valid_filename, but also slugifies away
umlauts and stuff.
"""
s = get_valid_filename_django(s)
filename, ext = os.path.splitext(s)
filename = slugify(filename)
ext = slugify(ext)
if ext:
return "%s.%s" % (filename, ext)
... |
java | @Deprecated
public CheckPolicyComplianceResult checkPolicyCompliance(String orgToken,
String product,
String productVersion,
Collecti... |
java | protected void scrollUpSubtitles (int dy)
{
// dirty and move all the old glyphs
Rectangle vbounds = _target.getViewBounds();
int miny = vbounds.y + vbounds.height - _subtitleHeight;
for (Iterator<ChatGlyph> iter = _subtitles.iterator(); iter.hasNext();) {
ChatGlyph sub =... |
python | def min_validator(min_value):
"""Return validator function that ensures lower bound of a number.
Result validation function will validate the internal value of resource
instance field with the ``value >= min_value`` check
Args:
min_value: minimal value for new validator
"""
def valida... |
java | private String getEventLogName(String name, String id) {
return String.format("%s-%s", name, id);
} |
java | void setDefAttrValue(StylesheetHandler handler, ElemTemplateElement elem)
throws org.xml.sax.SAXException
{
setAttrValue(handler, this.getNamespace(), this.getName(),
this.getName(), this.getDefault(), elem);
} |
java | public ServiceFuture<List<SharedAccessAuthorizationRuleResourceInner>> listAuthorizationRulesAsync(final String resourceGroupName, final String namespaceName, final ListOperationCallback<SharedAccessAuthorizationRuleResourceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listAu... |
python | def gpu_load(wproc=0.5, wmem=0.5):
"""Return a list of namedtuples representing the current load for
each GPU device. The processor and memory loads are fractions
between 0 and 1. The weighted load represents a weighted average
of processor and memory loads using the parameters `wproc` and
`wmem` re... |
java | public void writeObject(Writer out, BioPAXElement bean) throws IOException
{
String name = "bp:" + bean.getModelInterface().getSimpleName();
writeIDLine(out, bean, name);
Set<PropertyEditor> editors = editorMap.getEditorsOf(bean);
if (editors == null || editors.isEmpty())
{
log.info("no editors for " + b... |
python | def _set_port_channel(self, v, load=False):
"""
Setter method for port_channel, mapped from YANG variable /interface/port_channel (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_channel is considered as a private
method. Backends looking to populate this ... |
python | def predict(self,param_dict):
""" predict new waveforms using multivar fit """
encoder_dict = self._designmatrix_object.encoder
X, col_names = self._designmatrix_object.run_encoder(param_dict, encoder_dict)
# compute predictions
Y_pred = self._compute_prediction(X)
return... |
java | private Result listSessions() {
StringBuilder sb = new StringBuilder("<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
" <meta charset=\"utf-8\">\n" +
" <title>Training sessions - DL4J Training UI</title>\n" +
... |
java | public static ImageOption https() {
return new ImageOption("https", "") {
@Override public String apply(String url) {
if (url.startsWith("//")) {
return "https:" + url;
} else {
return url;
}
}
};
} |
python | def f1_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the F1 score.
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score ... |
java | public String getUrlEncodedQueryString(){
StringBuilder sb = new StringBuilder();
for (Entry<String, Object> parameter : parameters.entrySet()){
if (sb.length() > 0){
sb.append("&");
}
try {
StringBuilder sb2 = new StringBuilder();
... |
java | public void addChild(Command cmd)
{
if (cmd != null)
{
cmd.setContext(this);
commands.add(cmd);
}
} |
python | def add_to_waiting_parents(self, node):
"""
Returns the number of nodes added to our waiting parents list:
1 if we add a unique waiting parent, 0 if not. (Note that the
returned values are intended to be used to increment a reference
count, so don't think you can "clean up" this... |
python | def isAvailable(self, requester, access):
""" Return a boolean whether the lock is available for claiming """
debuglog("%s isAvailable(%s, %s): self.owners=%r"
% (self, requester, access, self.owners))
num_excl, num_counting = self._claimed_excl, self._claimed_counting
... |
java | public void setResult(java.util.Collection<WorkspacesIpGroup> result) {
if (result == null) {
this.result = null;
return;
}
this.result = new com.amazonaws.internal.SdkInternalList<WorkspacesIpGroup>(result);
} |
python | def xml_get_tag(xml, tag, parent_tag=None, multi_line=False):
"""
Returns the tag data for the first instance of the named tag, or for all instances if multi is true.
If a parent tag is specified, then that will be required before the tag.
"""
expr_str = '[<:]' + tag + '.*?>(?P<matched_text>.+?)<'
... |
java | public <T> T get() {
_fjtask.join(); // Block until top-level job is done
T ans = (T) UKV.get(destination_key);
remove(); // Remove self-job
return ans;
} |
java | public void marshall(DescribeElasticsearchDomainConfigRequest describeElasticsearchDomainConfigRequest, ProtocolMarshaller protocolMarshaller) {
if (describeElasticsearchDomainConfigRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {... |
python | def publish_gsi_notification(
table_key, gsi_key, message, message_types, subject=None):
""" Publish a notification for a specific GSI
:type table_key: str
:param table_key: Table configuration option key name
:type gsi_key: str
:param gsi_key: Table configuration option key name
:type ... |
python | def __get_segment_types(self, element):
"""
given a <segment> or <group> element, returns its segment type and the
segment type of its parent (i.e. its dominating node)
Parameters
----------
element : ??? etree Element
Returns
-------
segment_typ... |
python | async def parse_result(response, response_type=None, *, encoding="utf-8"):
"""
Convert the response to native objects by the given response type
or the auto-detected HTTP content-type.
It also ensures release of the response object.
"""
if response_type is None:
ct = response.headers.get... |
python | def ObjectEnum(ctx):
"""Object Enumeration.
Should export the whole list from the game for the best accuracy.
"""
return Enum(
ctx,
villager_male=83,
villager_female=293,
scout_cavalry=448,
eagle_warrior=751,
king=434,
flare=332,
relic=285... |
python | def timeline_public(self, max_id=None, min_id=None, since_id=None, limit=None, only_media=False):
"""
Fetches the public / visible-network timeline, not including replies.
Set `only_media` to True to retrieve only statuses with media attachments.
Returns a list of `toot dicts`_.
... |
java | public void marshall(AssociateHostedConnectionRequest associateHostedConnectionRequest, ProtocolMarshaller protocolMarshaller) {
if (associateHostedConnectionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMar... |
python | def confirm(what, where):
'''
Method to show a CLI based confirmation message, waiting for a yes/no answer.
"what" and "where" are used to better define the message.
'''
ans = input('Are you sure you want to delete the '
'{} {} from the service?\n[yN]> '.format(what, where))
if '... |
python | def process_frames(self, data, sampling_rate, offset=0, last=False, utterance=None, corpus=None):
"""
Execute the processing of this step and all dependent parent steps.
"""
if offset == 0:
self.steps_sorted = list(nx.algorithms.dag.topological_sort(self.graph))
... |
python | def _autobox(content, format):
'''
Autobox response content.
:param content: Response content
:type content: str
:param format: Format to return
:type format: `yaxil.Format`
:returns: Autoboxed content
:rtype: dict|xml.etree.ElementTree.Element|csvreader
'''
if format == Format.... |
java | public void delete(String photoId) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("method", METHOD_DELETE);
parameters.put("photo_id", photoId);
// Note: This method requires an HTTP POST request.
Response response... |
python | def read_creds_from_csv(filename):
"""
Read credentials from a CSV file
:param filename:
:return:
"""
key_id = None
secret = None
mfa_serial = None
secret_next = False
with open(filename, 'rt') as csvfile:
for i, line in enumerate(csvfile):
values = line.spli... |
python | def create_session_entity_type(project_id, session_id, entity_values,
entity_type_display_name, entity_override_mode):
"""Create a session entity type with the given display name."""
import dialogflow_v2 as dialogflow
session_entity_types_client = dialogflow.SessionEntityTypes... |
python | def call(self, name, *args, **kwds):
"""
Call method connected to this handler.
:type name: str
:arg name: Method name to call.
:type args: list
:arg args: Arguments for remote method to call.
:type callback: callable
:arg callback: A f... |
java | public void setThings(java.util.Collection<ThingDocument> things) {
if (things == null) {
this.things = null;
return;
}
this.things = new java.util.ArrayList<ThingDocument>(things);
} |
java | public static BitSet and(BitSet left, BitSet right) {
BitSet result = (BitSet) left.clone();
result.and(right);
return result;
} |
python | def run(self):
"""Run the main loop. Returns exit code."""
self.exit_code = 1
self.mainloop = GLib.MainLoop()
try:
future = ensure_future(self._start_async_tasks())
future.callbacks.append(self.set_exit_code)
self.mainloop.run()
return self... |
java | @Override
public DeleteInterconnectResult deleteInterconnect(DeleteInterconnectRequest request) {
request = beforeClientExecution(request);
return executeDeleteInterconnect(request);
} |
python | def wait(self, interval=SGE_WAIT):
"""Wait until the job finishes, and poll SGE on its status."""
finished = False
while not finished:
time.sleep(interval)
interval = min(2 * interval, 60)
finished = os.system("qstat -j %s > /dev/null" % (self.name)) |
python | def format_column(self, label, column):
"""Return a formatting function that pads & truncates values."""
if len(column) == 0:
val_width = 0
else:
val_width = max(len(self.format_value(v)) for v in column)
val_width = min(val_width, self.max_width)
width = ... |
python | def begin(self, access_mode=None):
"""
Begins a new transaction, raises SystemError exception if a transaction is in progress
"""
if self._active_transaction:
raise SystemError("Transaction in progress")
self._active_transaction = self.driver.session(access_mode=acces... |
python | def ascii_listing2program_dump(self, basic_program_ascii, program_start=None):
"""
convert a ASCII BASIC program listing into tokens.
This tokens list can be used to insert it into the
Emulator RAM.
"""
if program_start is None:
program_start = self.DEFAULT_PR... |
python | def xy2geom(x, y, t_srs=None):
"""Convert x and y point coordinates to geom
"""
geom_wkt = 'POINT({0} {1})'.format(x, y)
geom = ogr.CreateGeometryFromWkt(geom_wkt)
if t_srs is not None and not wgs_srs.IsSame(t_srs):
ct = osr.CoordinateTransformation(t_srs, wgs_srs)
geom.Transform(ct)... |
python | def report_exception(self, http_context=None, user=None):
""" Reports the details of the latest exceptions to Stackdriver Error
Reporting.
:type http_context: :class`google.cloud.error_reporting.HTTPContext`
:param http_context: The HTTP request which was processed when the
... |
java | @Override
public List<CommerceDiscount> findByGroupId(long groupId) {
return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} |
java | protected void generateIElementBuilder() {
final List<TopElementDescription> topElements = generateTopElements(true, false);
for (final TopElementDescription element : topElements) {
final StringConcatenationClient content = new StringConcatenationClient() {
@Override
protected void appendTo(TargetString... |
java | public static Filter<URIResponse> adaptFilterHttpResponse2URIResponse(final Filter<HttpResponse> original) {
return new AbstractFilter<URIResponse>() {
@Override
public boolean apply(URIResponse x) {
return original.apply(x.response());
}
@Override
public String toString() {
return original.toS... |
java | @Pure
Iterator<N> nodeIterator(Rectangle2afp<?, ?, ?, ?, ?, ?> clipBounds) {
return new BroadFirstTreeIterator<>(this.tree, new FrustumSelector<P, N>(clipBounds));
} |
java | private void writeArray(SerIterator itemIterator) throws IOException {
output.writeArrayStart();
while (itemIterator.hasNext()) {
itemIterator.next();
output.writeArrayItemStart();
writeObject(itemIterator.valueType(), itemIterator.value(), itemIterator);
}
... |
python | def convert_source_location(self, source_reading, reference_reading):
"""
Converts the source (x, y) location from reading into the coordinate
system of reference_reading.
"""
offset_x, offset_y = reference_reading.get_coordinate_offset(source_reading)
focus = source_read... |
java | public static String formatIsoDate(ZonedDateTime value) {
if (value == null) {
return null;
}
// to match the format we get from Python's .isoformat(), we don't include second fraction if it's zero
if (value.getNano() == 0) {
return ISO_DATETIME_FORMAT_NO_SECOND_... |
python | def canned_handlers(self, environ, start_response, code = '200', headers = []):
'''
We convert an error code into
certain action over start_response and return a WSGI-compliant payload.
'''
headerbase = [('Content-Type', 'text/plain')]
if headers:
hObj ... |
python | def _set_serial_console(self):
"""
Configures the first serial port to allow a serial console connection.
"""
pipe_name = self._get_pipe_name()
serial_port = {"serial0.present": "TRUE",
"serial0.filetype": "pipe",
"serial0.filename":... |
java | private void report(I_CmsReport report, int counter, int resCount, CmsResource resource) {
// report entries
report.print(
org.opencms.report.Messages.get().container(
org.opencms.report.Messages.RPT_SUCCESSION_2,
String.valueOf(counter),
Stri... |
java | public QProfileDto getProfile(DbSession dbSession, QProfileReference ref) {
QProfileDto profile;
if (ref.hasKey()) {
profile = dbClient.qualityProfileDao().selectByUuid(dbSession, ref.getKey());
checkFound(profile, "Quality Profile with key '%s' does not exist", ref.getKey());
// Load organiza... |
python | def _get_active_stats(self, app_stats):
"""
Process:
* active_scheduled_host_check_stats
* active_scheduled_service_check_stats
* active_ondemand_host_check_stats
* active_ondemand_service_check_stats
"""
stats = {}
app_keys = [
... |
python | def _parseResourceDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the C{IMAGE_RESOURCE_DIRECTORY} directory.
@type rva: int
@param rva: The RVA where the C{IMAGE_RESOURCE_DIRECTORY} starts.
@type size: int
@param size: The size of the C{IMAG... |
java | public Observable<Void> pauseAsync(String resourceGroupName, String serverName, String databaseName) {
return pauseWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> respons... |
python | def run(self):
"""run the model"""
model = self.model
configfile = self.configfile
interval = self.interval
sockets = self.sockets
model.initialize(configfile)
if model.state == 'pause':
logger.info(
"model initialized and started in ... |
python | async def refresh_token(self, refresh_token):
"""
:param refresh_token: an openid refresh-token from a previous token request
"""
async with self._client_session() as client:
well_known = await self._get_well_known(client)
try:
return await self._... |
python | def get_value(record, key, default=None):
"""Return item as `dict.__getitem__` but using 'smart queries'.
.. note::
Accessing one value in a normal way, meaning d['a'], is almost as
fast as accessing a regular dictionary. But using the special
name convention is a bit slower than using... |
python | def _find_to_filter(in_file, exclude_file, params, to_exclude):
"""Identify regions in the end file that overlap the exclusion file.
We look for ends with a large percentage in a repeat or where the end contains
an entire repeat.
"""
for feat in pybedtools.BedTool(in_file).intersect(pybedtools.BedT... |
java | @Override
public ListVPCAssociationAuthorizationsResult listVPCAssociationAuthorizations(ListVPCAssociationAuthorizationsRequest request) {
request = beforeClientExecution(request);
return executeListVPCAssociationAuthorizations(request);
} |
python | def disconnect(self, device):
"""Disconnect using protocol specific method."""
self.device.ctrl.sendcontrol('d')
self.device.ctrl.send("c.")
self.log("CONSOLE SERVER disconnect")
try:
self.device.ctrl.send(chr(4))
except OSError:
self.log("Protocol... |
java | @SuppressWarnings("rawtypes")
public static <T> List<T> topp(final T[] a, final int fromIndex, final int toIndex, final int n, final Comparator<? super T> cmp) {
N.checkArgNotNegative(n, "n");
if (n == 0) {
return new ArrayList<>();
} else if (n >= toIndex - fromIndex) {
... |
java | private boolean isValidNamedEntity(final Double score, final String text) {
return !StringUtils.isBlank(text)
|| score != null;
} |
python | def get_template(template_name, using=None):
"""
Loads and returns a template for the given name.
Raises TemplateDoesNotExist if no such template exists.
"""
engines = _engine_list(using)
for engine in engines:
try:
return engine.get_template(template_name)
except Tem... |
java | private static double[] collectDomain(NonBlockingHashMapLong ls) {
int sz = ls.size(); // Uniques
double ds[] = new double[sz];
int x = 0;
for (NonBlockingHashMapLong.IteratorLong i = iter(ls); i.hasNext(); )
ds[x++] = Double.longBitsToDouble(i.nextLong());
Arrays.sort(ds);
return ... |
java | private JsonWriter write(JsonWriter writer, Schema schema, Set<String> knownRecords) throws IOException {
// Simple type, just emit the type name as a string
if (schema.getType().isSimpleType()) {
return writer.value(schema.getType().name().toLowerCase());
}
// Union type is an array of schemas
... |
python | def _set_replicator(self, v, load=False):
"""
Setter method for replicator, mapped from YANG variable /tunnel_settings/system/tunnel/replicator (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_replicator is considered as a private
method. Backends looking ... |
python | def _convert_asset_timestamp_fields(dict_):
"""
Takes in a dict of Asset init args and converts dates to pd.Timestamps
"""
for key in _asset_timestamp_fields & viewkeys(dict_):
value = pd.Timestamp(dict_[key], tz='UTC')
dict_[key] = None if isnull(value) else value
return dict_ |
python | def find(self, groupid):
""" return all of the indices of particles of groupid """
return self.indices[self.offset[groupid]
:self.offset[groupid]+ self.length[groupid]] |
python | def serialize(self, occur=None):
"""Return RELAX NG representation of the receiver and subtree.
"""
fmt = self.ser_format.get(self.name, SchemaNode._default_format)
return fmt(self, occur) % (escape(self.text) +
self.serialize_children()) |
java | @Override
public Content getConstructorDetailsTreeHeader(TypeElement typeElement,
Content memberDetailsTree) {
memberDetailsTree.addContent(HtmlConstants.START_OF_CONSTRUCTOR_DETAILS);
Content constructorDetailsTree = writer.getMemberTreeHeader();
constructorDetailsTree.addConten... |
python | def cumsum(x, dim, exclusive=False):
"""Cumulative sum.
Args:
x: a Tensor
dim: a Dimension
exclusive: a boolean
Returns:
a Tensor with the same shape as x.
"""
with tf.variable_scope("cumsum"):
new_name = "tmp_dim_cumsum"
new_dim = Dimension(new_name, dim.size)
new_shape = x.shap... |
java | @Override
public ChronicleMapBuilder<K, V> averageKey(K averageKey) {
Objects.requireNonNull(averageKey);
checkSizeIsStaticallyKnown(keyBuilder, "Key");
this.averageKey = averageKey;
sampleKey = null;
averageKeySize = UNDEFINED_DOUBLE_CONFIG;
return this;
} |
python | def bookmark_delete(bookmark_id_or_name):
"""
Executor for `globus bookmark delete`
"""
client = get_client()
bookmark_id = resolve_id_or_name(client, bookmark_id_or_name)["id"]
res = client.delete_bookmark(bookmark_id)
formatted_print(res, text_format=FORMAT_TEXT_RAW, response_key="message... |
python | def _preprocess(text, tab=4):
"""Normalize a text."""
text = re.sub(r'\r\n|\r', '\n', text)
text = text.replace('\t', ' ' * tab)
text = text.replace('\u00a0', ' ')
text = text.replace('\u2424', '\n')
pattern = re.compile(r'^ +$', re.M)
text = pattern.sub('', text)
text = _rstrip_lines(te... |
python | def processEscalatedException(self, ex):
"""
Process an exception escalated from a Replica
"""
if isinstance(ex, SuspiciousNode):
self.reportSuspiciousNodeEx(ex)
else:
raise RuntimeError("unhandled replica-escalated exception") from ex |
python | def _applytfms(args):
"""
Applies ANTs' antsApplyTransforms to the input image.
All inputs are zipped in one tuple to make it digestible by
multiprocessing's map
"""
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
from niworkflows.interfaces.fixes import FixHeader... |
python | def _get_decision_trees_bulk(self, payload, valid_indices, invalid_indices, invalid_dts):
"""Tool for the function get_decision_trees_bulk.
:param list payload: contains the informations necessary for getting
the trees. Its form is the same than for the function.
get_decision_trees_bulk.
:param lis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.