language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def split_from_df(self, col:IntsOrStrs=2):
"Split the data from the `col` in the dataframe in `self.inner_df`."
valid_idx = np.where(self.inner_df.iloc[:,df_names_to_idx(col, self.inner_df)])[0]
return self.split_by_idx(valid_idx) |
java | public static void removeName(Node n) {
checkState(n.isFunction() || n.isClass());
Node originalName = n.getFirstChild();
Node emptyName = n.isFunction() ? IR.name("") : IR.empty();
n.replaceChild(originalName, emptyName.useSourceInfoFrom(originalName));
} |
python | def run_command(local_root, command, env_var=True, pipeto=None, retry=0, environ=None):
"""Run a command and return the output.
:raise CalledProcessError: Command exits non-zero.
:param str local_root: Local path to git root directory.
:param iter command: Command to run.
:param dict environ: Envi... |
java | public void ifHasMemberWithTag(String template, Properties attributes) throws XDocletException
{
ArrayList allMemberNames = new ArrayList();
HashMap allMembers = new HashMap();
boolean hasTag = false;
addMembers(allMemberNames, allMembers, getCurrentClass(), null, null, null);... |
python | def major_axis(points):
"""
Returns an approximate vector representing the major axis of points
Parameters
-------------
points: (n, dimension) float, points in space
Returns
-------------
axis: (dimension,) float, vector along approximate major axis
"""
U, S, V = np.linalg.svd... |
python | def _randomize_direction(base_heading, sigma) -> int:
"""
Creates a variation in direction
Args:
base_heading: base direction
sigma: sigma value for gaussian variation
Returns: random direction
"""
val = MissionWeather._gauss(base_heading, sigma... |
java | public void setLastHlsIngestDateTime(com.google.api.ads.admanager.axis.v201808.DateTime lastHlsIngestDateTime) {
this.lastHlsIngestDateTime = lastHlsIngestDateTime;
} |
python | def p_group_command(p):
'''group_command : LEFT_CURLY compound_list RIGHT_CURLY'''
lcurly = ast.node(kind='reservedword', word=p[1], pos=p.lexspan(1))
rcurly = ast.node(kind='reservedword', word=p[3], pos=p.lexspan(3))
parts = [lcurly, p[2], rcurly]
p[0] = ast.node(kind='compound', list=parts, redir... |
java | public static <F extends ConfigurationComponent<F>> void basicValidate(final F component, final String section) throws ConfigException {
final Optional<F> maybeComponent = Optional.ofNullable(component);
if (maybeComponent.isPresent()) {
maybeComponent.get().basicValidate(section);
}... |
java | protected void compareServerMode(Session other) throws ClientException {
if (transferMode != MODE_EBLOCK) {
super.compareServerMode(other);
} else {
if (serverMode == SERVER_DEFAULT &&
other.serverMode == SERVER_DEFAULT) {
// this is OK
... |
java | public static Account getAccount(Context mContext) {
String ACCOUNT_NAME = mContext.getString(R.string.app_name);
return new Account(ACCOUNT_NAME, ACCOUNT_NAME);
} |
java | int closestPoint( Point2D_F64 target ) {
double bestDistance = Double.MAX_VALUE;
int bestIndex = -1;
for (int i = 0; i < contour.size(); i++) {
Point2D_I32 c = contour.get(i);
double d = UtilPoint2D_F64.distanceSq(target.x,target.y,c.x,c.y);
if( d < bestDistance ) {
bestDistance = d;
bestIndex =... |
java | protected Node inlineThumbnail(Document doc, ParsedURL urldata, Node eold) {
RenderableImage img = ThumbnailRegistryEntry.handleURL(urldata);
if(img == null) {
LoggingUtil.warning("Image not found in registry: " + urldata.toString());
return null;
}
ByteArrayOutputStream os = new ByteArrayOu... |
java | public static base_response add(nitro_service client, responderaction resource) throws Exception {
responderaction addresource = new responderaction();
addresource.name = resource.name;
addresource.type = resource.type;
addresource.target = resource.target;
addresource.htmlpage = resource.htmlpage;
addresou... |
java | public static Matcher<MethodTree> methodIsNamed(final String methodName) {
return new Matcher<MethodTree>() {
@Override
public boolean matches(MethodTree methodTree, VisitorState state) {
return methodTree.getName().contentEquals(methodName);
}
};
} |
java | private String[] collectPartitionKeyAnnotations(Method method) {
Annotation[][] annotations = method.getParameterAnnotations();
String[] keyMappings = new String[annotations.length];
boolean keyMappingFound = false;
Map<String, Integer> unique = Maps.newHashMap();
for (int i = 0;... |
python | def setup_directories(builddir):
"""Create the in and out directories of the container."""
build_dir = local.path(builddir)
in_dir = build_dir / "container-in"
out_dir = build_dir / "container-out"
if not in_dir.exists():
in_dir.mkdir()
if not out_dir.exists():
out_dir.mkdir() |
java | public Task extendVirtualDisk_Task(String name, Datacenter datacenter, long newCapacityKb, Boolean eagerZero) throws FileFault, RuntimeFault, RemoteException {
return new Task(getServerConnection(),
getVimService().extendVirtualDisk_Task(getMOR(), name, datacenter == null ? null : datacenter.getMO... |
java | public GetSignatureResponse getSignature(String nonceStr, long timestame, String url) {
BeanUtil.requireNonNull(url, "请传入当前网页的URL,不包含#及其后面部分");
GetSignatureResponse response = new GetSignatureResponse();
String jsApiTicket = this.config.getJsApiTicket();
String sign;
try {
... |
python | def david_results_iterator(fn, verbose=False):
"""
Iterate over a DAVID result set and yeild GeneOntologyTerm objects
representing each of the terms reported. The expected format for a DAVID
result file is tab-seperated format. The following fields should be present:
=== =============== ========== =======... |
java | public static base_response delete(nitro_service client, String selectorname) throws Exception {
cacheselector deleteresource = new cacheselector();
deleteresource.selectorname = selectorname;
return deleteresource.delete_resource(client);
} |
python | def command_subscribe(self, command, **kwargs):
""" Subscribe to a topic or list of topics """
topic = command['topic']
encoding = command.get('encoding', 'utf-8')
name = command['name']
if not hasattr(self.engine, '_mqtt'):
self.engine._mqtt = {}
self.engine.... |
python | def _get_policy_set(self, policy_set_id):
"""
Get a specific policy set by id.
"""
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._get(uri) |
python | def average_spectrogram(timeseries, method_func, stride, *args, **kwargs):
"""Generate an average spectrogram using a method function
Each time bin of the resulting spectrogram is a PSD generated using
the method_func
"""
# unpack CSD TimeSeries pair, or single timeseries
try:
timeserie... |
java | public void removeEventListener() {
logger.fine("RXTXPort:removeEventListener() called");
waitForTheNativeCodeSilly();
//if( monThread != null && monThread.isAlive() )
if (monThreadisInterrupted == true) {
logger.fine(" RXTXPort:removeEventListener() already interrupted");
... |
java | public void putUnchecked(CodeBuilder adapter) {
checkState(!isStatic(), "This field is static!");
adapter.putField(owner().type(), name(), type());
} |
python | def function(self, x, y, amp, R_sersic, n_sersic, e1, e2, center_x=0, center_y=0):
"""
returns Sersic profile
"""
#if n_sersic < 0.2:
# n_sersic = 0.2
#if R_sersic < 10.**(-6):
# R_sersic = 10.**(-6)
R_sersic = np.maximum(0, R_sersic)
phi_G, ... |
python | def execfile(fname, _globals, _locals):
"""
Usage: execfile('path/to/file.py', globals(), locals())
"""
if os.path.exists(fname):
with open(fname) as f:
code = compile(f.read(), os.path.basename(fname), 'exec')
exec(code, _globals, _locals)
return True
els... |
python | def application(cls, f):
"""Decorate a function as responder that accepts the request as first
argument. This works like the :func:`responder` decorator but the
function is passed the request object as first argument and the
request object will be closed automatically::
@Re... |
python | def id_pools(self):
"""
Gets the IdPools API client.
Returns:
IdPools:
"""
if not self.__id_pools:
self.__id_pools = IdPools(self.__connection)
return self.__id_pools |
java | @Override
public final void visit(final SubmitterLinkDocumentMongo document) {
setGedObject(new SubmitterLink(getParent(), "Submitter",
new ObjectId(document.getString())));
} |
python | def _isValidTrigger(block, ch):
"""check if the trigger characters are in the right context,
otherwise running the indenter might be annoying to the user
"""
if ch == "" or ch == "\n":
return True # Explicit align or new line
match = rxUnindent.match(block.text())
... |
python | def purge(name=None, pkgs=None, **kwargs):
'''
Remove a package and extra configuration files.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored ... |
python | def get_stat(self, key):
"""
Returns a stat that was previously reported. This is necessary for reporting new stats that are
derived from two stats, one of which may have been reported by an earlier run. For example,
if you first use report_result to report (number of trimmed reads), an... |
java | public com.google.protobuf.ByteString
getVmNameBytes() {
java.lang.Object ref = vmName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
vmName_ = b;
return b;
} e... |
java | public static List<DataPoint> parse(String points, String splitRegex, Class<?> type, long ts) {
String[] items = points.split(splitRegex);
List<DataPoint> ret = new ArrayList<DataPoint>();
for (String i : items) {
if (i.length() == 0) {
continue;
}
... |
java | public static void gc() {
class GCTask extends DTask<GCTask> {
public GCTask() {super(GUI_PRIORITY);}
@Override public void compute2() {
Log.info("Calling System.gc() now...");
System.gc();
Log.info("System.gc() finished");
tryComplete();
}
}
for (H2ONode n... |
java | protected void handleError(final HttpServletRequest httpServletRequest,
final HttpServletResponse httpServletResponse, final Throwable throwable)
throws ServletException, IOException {
HttpServletHelper helper = createServletHelper(httpServletRequest, httpServletResponse);
ServletUtil.handleError(helper, thro... |
python | def top3_reduced(votes):
"""
Description:
Top 3 alternatives 16 moment conditions values calculation
Parameters:
votes: ordinal preference data (numpy ndarray of integers)
"""
res = np.zeros(16)
for vote in votes:
# the top ranked alternative is in vote[0][0], second in v... |
java | public void alias(final @NonNull String newId, final @Nullable Options options) {
assertNotShutdown();
if (isNullOrEmpty(newId)) {
throw new IllegalArgumentException("newId must not be null or empty.");
}
analyticsExecutor.submit(
new Runnable() {
@Override
public void... |
java | protected void updateDistances(Relation<V> relation, double[][] means, final WritableDataStore<Meta> metas, NumberVectorDistanceFunction<? super V> df) {
for(DBIDIter id = relation.iterDBIDs(); id.valid(); id.advance()) {
Meta c = metas.get(id);
V fv = relation.get(id);
// Update distances to mean... |
python | def _compute_hamming_matrix(N):
"""Compute and store a Hamming matrix for |N| nodes.
Hamming matrices have the following sizes::
N MBs
== ===
9 2
10 8
11 32
12 128
13 512
Given these sizes and the fact that large matrices are needed infrequ... |
python | def recognize_verify_code(image_path, broker="ht"):
"""识别验证码,返回识别后的字符串,使用 tesseract 实现
:param image_path: 图片路径
:param broker: 券商 ['ht', 'yjb', 'gf', 'yh']
:return recognized: verify code string"""
if broker == "gf":
return detect_gf_result(image_path)
if broker in ["yh_client", "gj_clie... |
java | protected String buildDeleteSQL(final TableMetadata metadata, final Class<? extends Object> type,
final SqlConfig sqlConfig, final boolean addCondition) {
StringBuilder sql = new StringBuilder("DELETE ").append("/* ")
.append(sqlConfig.getSqlAgentFactory().getSqlIdKeyName()).append(" */")
.append(" FROM ")... |
python | def after_init_app(self, app: FlaskUnchained):
"""
Configure an after request hook to set the ``csrf_token`` in the cookie.
"""
from flask_wtf.csrf import generate_csrf
# send CSRF token in the cookie
@app.after_request
def set_csrf_cookie(response):
... |
java | public E getEdge( V source, V target )
{
return directedGraph.getEdge( target, source );
} |
python | def verbose_option(fn):
""" Decorator to add a --verbose option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'verbose' if the command needs it. To get the current value you can d... |
python | def __register_fully_extracted_warc_file(self, warc_url):
"""
Saves the URL warc_url in the log file for fully extracted WARC URLs
:param warc_url:
:return:
"""
with open(self.__log_pathname_fully_extracted_warcs, 'a') as log_file:
log_file.write(warc_url + '\... |
python | def _delete(self):
"""Deletes this AssessmentSection from database.
Will be called by AssessmentTaken._delete() for clean-up purposes.
"""
collection = JSONClientValidated('assessment',
collection='AssessmentSection',
... |
java | public static PageSearchResult pageSearch(String accessToken,
PageSearch pageSearch) {
return pageSearch(accessToken, JsonUtil.toJSONString(pageSearch));
} |
java | public static String parseWithMetric(final String metric,
final HashMap<String, String> tags) {
final int curly = metric.indexOf('{');
if (curly < 0) {
return metric;
}
final int len = metric.length();
if (metric.charAt(len - 1) != '}') { // "foo{"
... |
java | private static Matrix execute(Matrix dataMatrix, MatrixFile affMatrixFile,
int dims) throws IOException {
// Write the input matrix to a file for Matlab/Octave to use
File mInput = File.createTempFile("lpp-input-data-matrix",".dat");
mInput.deleteOnExit();
... |
java | public void animateProgress(int start, int end, int duration) {
List<Boolean> list = new ArrayList<>();
list.add(true);
mCirclePieceFillList = list;
setProgress(0);
AnimatorSet set = new AnimatorSet();
set.playTogether(Glider.glide(Skill.QuadEaseInOut, duration, ObjectAni... |
python | async def connect(self, conn_id, connection_string):
"""Connect to a device.
See :meth:`AbstractDeviceAdapter.connect`.
"""
self._logger.info("Inside connect, conn_id=%d, conn_string=%s", conn_id, connection_string)
try:
self._setup_connection(conn_id, connection_s... |
java | public IfcCondenserTypeEnum createIfcCondenserTypeEnumFromString(EDataType eDataType, String initialValue) {
IfcCondenserTypeEnum result = IfcCondenserTypeEnum.get(initialValue);
if (result == null)
throw new IllegalArgumentException(
"The value '" + initialValue + "' is not a valid enumerator of '" + e... |
java | public static String removePrefix(String principalName) {
String result = principalName;
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(principalName)) {
if (hasPrefix(principalName)) {
result = principalName.trim().substring(I_CmsPrincipal.PRINCIPAL_GROUP.length() + 1);
... |
java | public static Class getClassOfOpenEngSBModel(String clazz,
String version,
OsgiUtilsService serviceFinder) throws ClassNotFoundException {
ModelRegistry registry = serviceFinder.getService(ModelRegistry.class);
ModelDescription modelDescription = new ModelDescription(clazz, vers... |
java | public JSONBuilder serialize(String name, Object value) {
return quote(name).append(':').serialize(value);
} |
java | public void marshall(ResultSetMetadata resultSetMetadata, ProtocolMarshaller protocolMarshaller) {
if (resultSetMetadata == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resultSetMetadata.getColumnC... |
python | def _read_data_legacy(prefix, batch_size):
"""
Loads a tf record as tensors you can use.
:param prefix: The path prefix as defined in the write data method.
:param batch_size: The batch size you want for the tensors.
:return: A feature tensor dict and a label tensor dict.
"""
prefix = prefix... |
python | def match(self, expression=None, xpath=None, namespaces=None):
"""decorator that allows us to match by expression or by xpath for each transformation method"""
class MatchObject(Dict):
pass
def _match(function):
self.matches.append(
MatchObject(expression... |
python | def make_mreq(family, address):
"""
Makes a mreq structure object for the given address and socket family.
:param family: A socket family (AF_INET or AF_INET6)
:param address: A multicast address (group)
:raise ValueError: Invalid family or address
"""
if not address:
raise ValueErr... |
python | def abort_submission(namespace, workspace, submission_id):
"""Abort running job in a workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
submission_id (str): Submission's unique identifier
Swagger:
https://api.firecloud.org/#... |
java | public static BulkheadMetricsCollector ofSupplier(MetricNames names, Supplier<? extends Iterable<? extends Bulkhead>> supplier) {
return new BulkheadMetricsCollector(names, supplier);
} |
python | def get_random_item(enum: Any, rnd: Optional[Random] = None) -> Any:
"""Get random item of enum object.
:param enum: Enum object.
:param rnd: Custom random object.
:return: Random item of enum.
"""
if rnd and isinstance(rnd, Random):
return rnd.choice(list(enum))
return random_modul... |
python | def crl_managed(name,
signing_private_key,
signing_private_key_passphrase=None,
signing_cert=None,
revoked=None,
days_valid=100,
digest="",
days_remaining=30,
include_expired=False,
... |
python | def render(self, mode=None, vertices=-1, *, first=0, instances=1) -> None:
'''
The render primitive (mode) must be the same as
the input primitive of the GeometryShader.
Args:
mode (int): By default :py:data:`TRIANGLES` will be used.
vertices ... |
python | def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self._data = data
self._token = logfilter.add_secret(data.attrib.get('authenticationToken'))
self._webhooks = []
self.authenticationToken = self._token
self.certificateVersion = data.attrib.g... |
java | @SuppressWarnings("unchecked")
@Override
public EList<CompareItem> getItems() {
return (EList<CompareItem>) eGet(StorePackage.Literals.COMPARE_CONTAINER__ITEMS, true);
} |
python | def resize(fname, basewidth, opFilename):
""" resize an image to basewidth """
if basewidth == 0:
basewidth = 300
img = Image.open(fname)
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
i... |
java | public static JavaRDD<DataSet> shuffleExamples(JavaRDD<DataSet> rdd, int newBatchSize, int numPartitions) {
//Step 1: split into individual examples, mapping to a pair RDD (random key in range 0 to numPartitions)
JavaPairRDD<Integer, DataSet> singleExampleDataSets =
rdd.flatMapT... |
python | def parse(self, argument):
"""Determine validity of argument and return the correct element of enum.
If self.enum_values is empty, then all arguments are valid and argument
will be returned.
Otherwise, if argument matches an element in enum, then the first
matching element will be returned.
A... |
python | def tensor(x:Any, *rest)->Tensor:
"Like `torch.as_tensor`, but handle lists too, and can pass multiple vector elements directly."
if len(rest): x = (x,)+rest
# XXX: Pytorch bug in dataloader using num_workers>0; TODO: create repro and report
if is_listy(x) and len(x)==0: return tensor(0)
res = torch... |
python | def run( self, for_time=None ):
"""
Run the simulation.
Args:
for_time (:obj:Float, optional): If `for_time` is set, then run the simulation until a set amount of time has passed. Otherwise, run the simulation for a set number of jumps. Defaults to None.
Returns:
... |
python | def _can_process_pre_prepare(self, pre_prepare: PrePrepare, sender: str) -> Optional[int]:
"""
Decide whether this replica is eligible to process a PRE-PREPARE.
:param pre_prepare: a PRE-PREPARE msg to process
:param sender: the name of the node that sent the PRE-PREPARE msg
"""... |
python | def create_host(url="local://local:6666/host"):
'''
This is the main function to create a new Host to which you can
spawn actors. It will be set by default at local address if no
parameter *url* is given, which would result in remote
incomunication between hosts. This function shuould be called once... |
java | public DescribeMLModelsResult withResults(MLModel... results) {
if (this.results == null) {
setResults(new com.amazonaws.internal.SdkInternalList<MLModel>(results.length));
}
for (MLModel ele : results) {
this.results.add(ele);
}
return this;
} |
python | def dialog_checklist(self):
"""Create checklist to choose packages for upgrade
"""
data = []
for upg in self.upgrade_all:
data.append(upg[:-4])
text = "Press 'spacebar' to unchoose packages from upgrade"
title = " Upgrade "
backtitle = "{0} {1}".format... |
python | def save_ip_ranges(profile_name, prefixes, force_write, debug, output_format = 'json'):
"""
Creates/Modifies an ip-range-XXX.json file
:param profile_name:
:param prefixes:
:param force_write:
:param debug:
:return:
"""
filename = 'ip-ranges-%s.json' % profile_name
ip_ranges = ... |
java | static boolean modifierIsAcceptable(Element item) {
// kotlin define properties as final
Object[] values = { Modifier.NATIVE, Modifier.STATIC, /* Modifier.FINAL, */ Modifier.ABSTRACT };
for (Object i : values) {
if (item.getModifiers().contains(i))
return false;
}
return true;
} |
python | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._uuid is not None:
return False
if self._amount_inquired is not None:
return False
if self._alias is not None:
return False
if self._description is not None:
... |
python | def wait_for_keypress(self, key, modifiers: list=None, timeOut=10.0):
"""
Wait for a keypress or key combination
Usage: C{keyboard.wait_for_keypress(self, key, modifiers=[], timeOut=10.0)}
Note: this function cannot be used to wait for modifier keys on their own
... |
java | @Override
public void putAttribute(String key, AttributeValue value) {
Utils.checkNotNull(key, "key");
Utils.checkNotNull(value, "value");
} |
python | def middle_frame(obj):
"Only display the (approximately) middle frame of an animated plot"
plot, renderer, fmt = single_frame_plot(obj)
middle_frame = int(len(plot) / 2)
plot.update(middle_frame)
return {'text/html': renderer.html(plot, fmt)} |
python | def getsourcefile(object):
"""Return the Python source file an object was defined in, if it exists."""
filename = getfile(object)
if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
filename = filename[:-4] + '.py'
for suffix, mode, kind in imp.get_suffixes():
if 'b' in mode and string.l... |
java | public void setMonitorPlugin(MonitorPlugin plugin) throws TooManyListenersException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "setMonitorPlugin", plugin);
}
if (this.monitorPlugin != null && !this.monitorPlugin.equals(plugin)) {
t... |
java | private static int doUnescape(
String s, int i, StringBuilder sb, ErrorReporter errorReporter, SourceLocation loc) {
checkArgument(i < s.length(), "Found escape sequence at the end of a string.");
char c = s.charAt(i++);
switch (c) {
case 'n':
sb.append('\n');
break;
case ... |
java | public void marshall(SecretListEntry secretListEntry, ProtocolMarshaller protocolMarshaller) {
if (secretListEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(secretListEntry.getARN(), ARN_BIND... |
python | def run(argv=argv):
"""Runs the search_google command line tool.
This function runs the search_google command line tool
in a terminal. It was intended for use inside a py file
(.py) to be executed using python.
Notes:
* ``[q]`` reflects key ``q`` in the ``cseargs`` parameter for :class:`api.result... |
java | public static <T> Spliterator<T> spliterator(Object[] array,
int additionalCharacteristics) {
return new ArraySpliterator<>(Objects.requireNonNull(array),
additionalCharacteristics);
} |
python | def get_connection(self, alias='default'):
"""
Retrieve a connection, construct it if necessary (only configuration
was passed to us). If a non-string alias has been passed through we
assume it's already a client instance and will just return it as-is.
Raises ``KeyError`` if no ... |
java | public void setRow(int i, double value) {
VectorIterator it = iteratorOfRow(i);
while (it.hasNext()) {
it.next();
it.set(value);
}
} |
python | def dispatch(self):
"""Wraps the dispatch method to add session support."""
try:
webapp2.RequestHandler.dispatch(self)
finally:
self.session_store.save_sessions(self.response) |
python | def _init_xml(self, body):
""" Parse the present body as xml """
tree = etree.fromstring(body.encode(self.encoding), PARSER)
# Extract and replace inner DIDL xml in tags
for text in tree.xpath('.//text()[contains(., "DIDL")]'):
item = text.getparent()
didl_tree = ... |
java | public static NodeSequence withNodeKeys( final Iterator<NodeKey> keys,
final long keyCount,
final float score,
final String workspaceName,
f... |
java | @Override
public String getContext() {
final AbstractSchemaNode parent = getProperty(SchemaMethod.schemaNode);
final StringBuilder buf = new StringBuilder();
if (parent != null) {
buf.append(parent.getProperty(SchemaNode.name));
buf.append(".");
buf.append(getProperty(name));
}
return buf.toStri... |
python | def _new(self, dx_hash, **kwargs):
'''
:param dx_hash: Standard hash populated in :func:`dxpy.bindings.DXDataObject.new()` containing attributes common to all data object classes.
:type dx_hash: dict
:param runSpec: Run specification
:type runSpec: dict
:param dxapi: API ... |
java | public Double append( Double s1, Double s2 )
{
if ( s1 == null || s2 == null )
{
return null;
}
return s1 + s2;
} |
java | public HBCIExecStatus execute(boolean closeDialog) {
HBCIExecStatus ret = new HBCIExecStatus();
log.debug("executing dialog");
try {
ret.setDialogStatus(doIt(closeDialog));
} catch (Exception e) {
ret.addException(e);
}
return ret;
} |
python | def get_namespace(self, namespace, lowercase=True, trim_namespace=True):
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage:
app.config['IMAGE_STORE_TYPE']='fs'
app.config['IMAGE_STORE_PATH']='/var/app... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.