language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def _call_mount(self, volume, mountpoint, type=None, opts=""):
"""Calls the mount command, specifying the mount type and mount options."""
# default arguments for calling mount
if opts and not opts.endswith(','):
opts += ","
opts += 'loop,offset=' + str(volume.offset) + ',si... |
python | def keys(self, full_grid=False):
"""Returns the keys of the GridSpace
Args:
full_grid (bool, optional): Return full cross-product of keys
Returns:
List of keys
"""
keys = super(GridSpace, self).keys()
if self.ndims == 1 or not full_grid:
... |
python | def verify(self, signature, data):
"""Verifies some data was signed by this private key.
:param signature: The signature to verify.
:type signature: ``bytes``
:param data: The data that was supposedly signed.
:type data: ``bytes``
:rtype: ``bool``
"""
ret... |
java | private void detectAndRejectHybridSyntax(final String optionName) {
if (optionName.contains(ARGUMENT_KEY_VALUE_SEPARATOR)) {
throw new CommandLineException(String.format("Can't parse option name containing an embedded '=' (%s)", optionName));
}
} |
java | public ServiceFuture<List<HybridRunbookWorkerGroupInner>> listByAutomationAccountAsync(final String resourceGroupName, final String automationAccountName, final ListOperationCallback<HybridRunbookWorkerGroupInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByAutomationAccount... |
java | @View(name = "by_serviceId", map = "function(doc) { if (doc.service) { emit(doc.service.serviceId, doc._id) }}")
public RegisteredServiceDocument findByServiceId(final String serviceId) {
return queryView("by_serviceId", serviceId).stream().findFirst().orElse(null);
} |
python | def delete_files_within_dir(directory: str, filenames: List[str]) -> None:
"""
Delete files within ``directory`` whose filename *exactly* matches one of
``filenames``.
"""
for dirpath, dirnames, fnames in os.walk(directory):
for f in fnames:
if f in filenames:
ful... |
java | private void doDeployNetwork(final NetworkContext context, final Message<JsonObject> message) {
final WrappedWatchableMap<String, String> data = new WrappedWatchableMap<String, String>(context.address(), this.data.<String, String>getMap(context.address()), vertx);
// When the context is set in the cluster, the... |
python | def touch(self, expiration):
"""Updates the current document's expiration value.
:param expiration: Expiration in seconds for the document to be removed by
couchbase server, defaults to 0 - will never expire.
:type expiration: int
:returns: Response from CouchbaseClient.
... |
python | async def get_inputs(self) -> List[Input]:
"""Return list of available outputs."""
res = await self.services["avContent"]["getCurrentExternalTerminalsStatus"]()
return [Input.make(services=self.services, **x) for x in res if 'meta:zone:output' not in x['meta']] |
java | private void extractStyles(Document doc) {
String stylesheet = fetchStyles(doc);
String trimmedStylesheet = stylesheet.replaceAll("\n", "").replaceAll("/\\*.*?\\*/", "").replaceAll(" +", " ");
String styleRules = trimmedStylesheet.trim(), delims = "{}";
StringTokenizer st = new StringTo... |
python | def setup_name(self, name, address=None, transact={}):
"""
Set up the address for reverse lookup, aka "caller ID".
After successful setup, the method :meth:`~ens.main.ENS.name` will return
`name` when supplied with `address`.
:param str name: ENS name that address will point to
... |
java | public ApiResponse<ApiSuccessResponse> mergeWithHttpInfo(String id, MergeData mergeData) throws ApiException {
com.squareup.okhttp.Call call = mergeValidateBeforeCall(id, mergeData, null, null);
Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType();
return apiClient.execute(c... |
java | public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption("custom-delimiter", options);
if (tmpStr.length() != 0)
setCustomDelimiter(tmpStr);
else
setCustomDelimiter("");
tmpStr = Utils.getOption("list", options);
if (tmpStr.length() != 0)
... |
python | def parse_timedelta(text):
"""Robustly parses a short text description of a time period into a
:class:`datetime.timedelta`. Supports weeks, days, hours, minutes,
and seconds, with or without decimal points:
Args:
text (str): Text to parse.
Returns:
datetime.timedelta
Raises:
... |
python | def list_vhosts(runas=None):
'''
Return a list of vhost based on rabbitmqctl list_vhosts.
CLI Example:
.. code-block:: bash
salt '*' rabbitmq.list_vhosts
'''
if runas is None and not salt.utils.platform.is_windows():
runas = salt.utils.user.get_user()
res = __salt__['cmd.r... |
java | public InventoryResultEntity withData(java.util.Map<String, InventoryResultItem> data) {
setData(data);
return this;
} |
java | public static RecordingUpdater updater(final String pathAccountSid,
final String pathConferenceSid,
final String pathSid,
final Recording.Status status) {
return new RecordingUpdat... |
python | def cleanup(self):
"""Delete expired metadata."""
expires = maybe_timedelta(self.expires)
for model in self.TaskModel, self.TaskSetModel:
model._default_manager.delete_expired(expires) |
java | public void marshall(GetDeployablePatchSnapshotForInstanceRequest getDeployablePatchSnapshotForInstanceRequest, ProtocolMarshaller protocolMarshaller) {
if (getDeployablePatchSnapshotForInstanceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
... |
python | def get_current_branch(self, location):
"""
Return the current branch, or None if HEAD isn't at a branch
(e.g. detached HEAD).
"""
# git-symbolic-ref exits with empty stdout if "HEAD" is a detached
# HEAD rather than a symbolic ref. In addition, the -q causes the
... |
java | public boolean setSampleRate(int rate) {
boolean result = (rate <= MAX_SAMPLE_RATE && rate >= MIN_SAMPLE_RATE);
sampleRate = rate;
return result;
} |
python | def top(**kwargs):
'''
Compile tops
'''
# Node definitions path will be retrieved from args (or set to default),
# then added to 'salt_data' dict that is passed to the 'get_pillars'
# function. The dictionary contains:
# - __opts__
# - __salt__
# - __grains__
# - ... |
python | def scale_to_control(x, axis_scale=350., min_v=-1.0, max_v=1.0):
"""Normalize raw HID readings to target range."""
x = x / axis_scale
x = min(max(x, min_v), max_v)
return x |
java | public static String adHocSQLStringFromPlannedStatement(AdHocPlannedStatement statement, Object[] userparams) {
final int MAX_PARAM_LINE_CHARS = 120;
StringBuilder sb = new StringBuilder();
String sql = new String(statement.sql, Charsets.UTF_8);
sb.append(sql);
Object[] params ... |
java | public static void replaceHttpHeaderMapNodeSpecific(
Map<String, String> httpHeaderMap,
Map<String, String> requestParameters) {
boolean needToReplaceVarInHttpHeader = false;
for (String parameter : requestParameters.keySet()) {
if (parameter.contains(PcConstants.NOD... |
java | public void registerJob(final ExecutionGraph executionGraph, final boolean profilingAvailable,
final long submissionTimestamp) {
final Iterator<ExecutionVertex> it = new ExecutionGraphIterator(executionGraph, true);
while (it.hasNext()) {
final ExecutionVertex vertex = it.next();
// Register the listen... |
java | @DeleteMapping(path = "/instances/{id}")
public Mono<ResponseEntity<Void>> unregister(@PathVariable String id) {
LOGGER.debug("Unregister instance with ID '{}'", id);
return registry.deregister(InstanceId.of(id))
.map(v -> ResponseEntity.noContent().<Void>build())
... |
python | def authenticate(self, request, application, method):
"""Authenticate the AJAX request.
By default any request to fetch a model is allowed for any user,
including anonymous users. All other methods minimally require that
the user is already logged in.
Most likely you will want ... |
python | def consider_member(name_member, member, module, class_=None):
"""Return |True| if the given member should be added to the
substitutions. If not return |False|.
Some examples based on the site-package |numpy|:
>>> from hydpy.core.autodoctools import Substituter
>>> import numpy... |
python | def _merge_section(original, to_merge):
# type: (str, str) -> str
"""Merge two sections together.
Args:
original: The source of header and initial section lines.
to_merge: The source for the additional section lines to append.
Returns:
A new section string that uses the header ... |
python | def saved_search(search_id, sort, pretty, limit):
'''Execute a saved search'''
sid = read(search_id)
cl = clientv1()
page_size = min(limit, 250)
echo_json_response(call_and_wrap(
cl.saved_search, sid, page_size=page_size, sort=sort
), limit=limit, pretty=pretty) |
java | public static String guessLineTerminatorOfFile(String _file) {
if (StringUtil.isEmpty(_file)) {
return SystemUtil.LINE_SEPARATOR;
}
File file = new File(_file);
if (!file.exists() || !file.canRead()) {
return SystemUtil.LINE_SEPARATOR;
}
try (Buf... |
java | @Override
public FilterSupportStatus isFilterSupported(
FilterAdapterContext context,
FilterList filter) {
List<FilterSupportStatus> unsupportedSubfilters = new ArrayList<>();
try (ContextCloseable ignored = context.beginFilterList(filter)) {
collectUnsupportedStatuses(context, filter, unsup... |
java | public double[] getRow(int row) {
checkIndices(row, 0);
double[] rowArr = new double[cols];
int index = getIndex(row, 0);
for (int i = 0; i < cols; ++i)
rowArr[i] = matrix[index++];
return rowArr;
} |
python | def purge_old(self):
'''
Removes keys that are beyond our keep_max limit
'''
if self.keep_max is not None:
keys = self.redis_conn.keys(self.get_key() + ':*')
keys.sort(reverse=True)
while len(keys) > self.keep_max:
key = keys.pop()
... |
java | private Node parseRecordType(JsDocToken token) {
Node recordType = newNode(Token.LC);
Node fieldTypeList = parseFieldTypeList(token);
if (fieldTypeList == null) {
return reportGenericTypeSyntaxWarning();
}
skipEOLs();
if (!match(JsDocToken.RIGHT_CURLY)) {
return reportTypeSyntaxWar... |
java | private final boolean cvc(int i) {
if (i < 2 || !isConsonant(i) || isConsonant(i - 1) || !isConsonant(i - 2)) {
return false;
}
{
int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') {
return false;
}
}
return tru... |
java | public static byte[] process(CharSequence html) {
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
process(html, baos);
return baos.toByteArray();
}
finally {
if (baos != null) {
try {
baos.close();
}
catch (IOException e) {
log.warn("Close Byte Arra... |
java | private boolean validInstanceOfExpression(Node expr) {
// The expression must have two children:
// - The instanceOf keyword
// - A string
if (!checkParameterCount(expr, Keywords.INSTANCEOF)) {
return false;
}
if (!validTypeTransformationExpression(getCallArgument(expr, 0))) {
warnIn... |
python | def set_num_occupants(self, num_occupants):
"""
Set the max number of occupants living in the property for rent.
:param num_occupants: int
"""
self._query_params += str(QueryParam.NUM_OCCUPANTS) + str(num_occupants) |
java | public synchronized String lookupContainer(String lookup) {
if (aliasToContainerMap.containsKey(lookup)) {
return aliasToContainerMap.get(lookup);
}
return imageToContainerMap.get(lookup);
} |
java | public void setGlobalTableGlobalSecondaryIndexSettingsUpdate(
java.util.Collection<GlobalTableGlobalSecondaryIndexSettingsUpdate> globalTableGlobalSecondaryIndexSettingsUpdate) {
if (globalTableGlobalSecondaryIndexSettingsUpdate == null) {
this.globalTableGlobalSecondaryIndexSettingsUpda... |
java | public static String getStackTrace(final Throwable ex) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw, true);
ex.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
} |
java | @Override
@CheckReturnValue
public RoleManager reset(long fields)
{
super.reset(fields);
if ((fields & NAME) == NAME)
this.name = null;
if ((fields & COLOR) == COLOR)
this.color = Role.DEFAULT_COLOR_RAW;
return this;
} |
java | public void addHole( Polygon poly )
{
if( _holes == null )
{
_holes = new ArrayList<Polygon>();
}
_holes.add( poly );
// XXX: tests could be made here to be sure it is fully inside
// addSubtraction( poly.getPoints() );
} |
java | private String generateJavaCode() {
final StringBuilder builder = new StringBuilder();
final String newLine = "\n";
// package information
builder.append(StatusUpdateTemplate.class.getPackage().toString());
builder.append(".templates");
builder.append(";");
builder.append(newLine);
builder.append(newLi... |
java | public final EObject entryRuleModel() throws RecognitionException {
EObject current = null;
EObject iv_ruleModel = null;
try {
// InternalPureXbase.g:64:46: (iv_ruleModel= ruleModel EOF )
// InternalPureXbase.g:65:2: iv_ruleModel= ruleModel EOF
{
... |
java | public DenseMatrix getR() {
int n = qr.ncols();
DenseMatrix R = Matrix.zeros(n, n);
for (int i = 0; i < n; i++) {
R.set(i, i, tau[i]);
for (int j = i+1; j < n; j++) {
R.set(i, j, qr.get(i, j));
}
}
return R;
} |
java | public IfBlock<T, INIT> ElseIf(RFunc0<INIT> init, T val) {
return ElseIf(init, () -> val);
} |
java | public EEnum getFontDescriptorSpecificationFtUsFlags() {
if (fontDescriptorSpecificationFtUsFlagsEEnum == null) {
fontDescriptorSpecificationFtUsFlagsEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(115);
}
return fontDescriptorSpecificationFtUsFlagsEEnum;
} |
python | def fieldAlphaHistogram(
self, name, q='*:*', fq=None, nbins=10, includequeries=True
):
"""Generates a histogram of values from a string field. Output is:
[[low, high, count, query], ... ] Bin edges is determined by equal division
of the fields
"""
oldpersist = s... |
python | def execute_request(conn, classname, max_open, max_pull):
"""
Enumerate instances defined by the function's
classname argument using the OpenEnumerateInstances and
PullInstancesWithPath.
* classname - Classname for the enumeration.
* max_open - defines the maximum number of... |
java | public static String dumpString(byte[] frame, int offset, int length, boolean ascii) {
if ((frame == null)|| (length == 0)) return null;
// Main formatting is performed in buf. asciibuf is used to hold the
// ascii translation. asciibuf is appended to buf before a new line is started
StringBuffer buf = ... |
python | def get_grammatically_correct_vocabulary_subset(self, text,
sent_filter='combined'):
"""
Returns a subset of a given vocabulary based on whether its
terms are "grammatically correct".
"""
tokens = word_tokenize(text)
sen... |
python | def _get_broadcasts(tables):
"""
Get the broadcasts associated with a set of tables.
Parameters
----------
tables : sequence of str
Table names for which broadcasts have been registered.
Returns
-------
casts : dict of `Broadcast`
Keys are tuples of strings like (cast_n... |
java | public void init(AsymmetricKeyParameter privateKey, CipherParameters params, KeyParser publicKeyParser) {
this.forEncryption = false;
this.privParam = privateKey;
this.keyParser = publicKeyParser;
extractParams(params);
} |
python | def nvmlDeviceGetHandleByPciBusId(pciBusId):
r"""
/**
* Acquire the handle for a particular device, based on its PCI bus id.
*
* For all products.
*
* This value corresponds to the nvmlPciInfo_t::busId returned by \ref nvmlDeviceGetPciInfo().
*
* Starting from NVML 5, this API... |
java | @SuppressWarnings({"unused", "WeakerAccess"})
public void pushNotificationClickedEvent(final Bundle extras) {
if (this.config.isAnalyticsOnly()) {
getConfigLogger().debug(getAccountId(), "is Analytics Only - will not process Notification Clicked event.");
return;
}
... |
java | protected static void checkSkippedError(long skipped, int instead) throws IOException
{
if (skipped != instead)
{
throw new IOException(MESSAGE_SKIPPED + skipped + MESSAGE_BYTES_INSTEAD_OF + instead);
}
} |
python | def dcos_user(user_id, password):
""" Provides a context with user otherthan super
"""
o_token = dcos_acs_token()
token = shakedown.authenticate(user_id, password)
dcos.config.set_val('core.dcos_acs_token', token)
yield
dcos.config.set_val('core.dcos_acs_token', o_token) |
python | def root(self, parts):
"""
Find the path root.
@param parts: A list of path parts.
@type parts: [str,..]
@return: The root.
@rtype: L{xsd.sxbase.SchemaObject}
"""
result = None
name = parts[0]
log.debug('searching schema for (%s)', name)
... |
python | def from_pyfile(self, filename):
"""
在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名
:return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常
"""
d = types.ModuleType('config')
d.__file__ = filename
with open(filename) as config_file:
exec(compile(config_file.r... |
java | private static boolean hasPossibleMutatingMethods(@Nonnull final List<Method> methods) {
boolean result = false;
for (final Method method : methods) {
if (!method.getAttributes().isEmpty()) {
result = true;
break;
}
}
return result;
} |
java | private void addToTail(Trie.Node node) {
while (true) {
if (tailBuffer.capacity() < tailIndex - TAIL_OFFSET + 1) {
CharBuffer newTailBuffer = CharBuffer.allocate(
tailBuffer.capacity() + (int) (tailBuffer.capacity() * BUFFER_GROWTH_PERCENTAGE));
... |
python | def qrandom(n):
"""
Creates an array of n true random numbers obtained from the quantum random
number generator at qrng.anu.edu.au
This function requires the package quantumrandom and an internet connection.
Args:
n (int):
length of the random array
Return:
array of ints:
array of tru... |
python | def detect_aromatic_rings_in_protein(self):
"""Use rdkit to detect aromatic rings in protein. A (relatively) simpler case, since only 4 of 20 aa have rings.
Since different forcefields can have different atom names, each of 4 aromatic residues is extracted as PDB file
and the aromatic rings are ... |
java | static Selector convertLike(Selector arg, String pattern, String escape) {
try
{
pattern = reduceStringLiteralToken(pattern);
boolean escaped = false;
char esc = 0;
if (escape != null) {
escape = reduceStringLiteralToken(escape);
if (escape.length() != 1)
return... |
python | def clip(arg, lower=None, upper=None):
"""
Trim values at input threshold(s).
Parameters
----------
lower : float
upper : float
Returns
-------
clipped : same as type of the input
"""
if lower is None and upper is None:
raise ValueError("at least one of lower and " ... |
java | @Override
public GetSnapshotTaskResult getSnapshot(String snapshotId)
throws ContentStoreException {
GetSnapshotTaskParameters taskParams = new GetSnapshotTaskParameters();
taskParams.setSnapshotId(snapshotId);
String taskResult =
contentStore.performTask(SnapshotConstan... |
python | def get_avatar_upload_to(self, filename):
""" Returns the path to upload the associated avatar to. """
dummy, ext = os.path.splitext(filename)
return os.path.join(
machina_settings.PROFILE_AVATAR_UPLOAD_TO,
'{id}{ext}'.format(id=str(uuid.uuid4()).replace('-', ''), ext=ext... |
python | def store_pulse_pushes(body, exchange, routing_key):
"""
Fetches the pushes pending from pulse exchanges and loads them.
"""
newrelic.agent.add_custom_parameter("exchange", exchange)
newrelic.agent.add_custom_parameter("routing_key", routing_key)
PushLoader().process(body, exchange) |
python | def CheckHuntAccess(self, username, hunt_id):
"""Checks whether a given user can access given hunt."""
self._CheckAccess(
username, str(hunt_id),
rdf_objects.ApprovalRequest.ApprovalType.APPROVAL_TYPE_HUNT) |
python | def get_module_resources(mod):
"""Return probed sub module names from given module"""
path = os.path.dirname(os.path.realpath(mod.__file__))
prefix = kf.basename(mod.__file__, (".py", ".pyc"))
if not os.path.exists(mod.__file__):
import pkg_resources
for resource_name in pkg_resources.... |
java | @Override
public GetJobsResult getJobs(GetJobsRequest request) {
request = beforeClientExecution(request);
return executeGetJobs(request);
} |
java | protected base_resource stat_resource(nitro_service service,options option) throws Exception
{
if (!service.isLogin())
service.login();
base_resource[] response = stat_request(service, option);
if (response != null && response.length > 0)
{
return response[0];
}
return null;
} |
python | def require_root(fn):
"""
Decorator to make sure, that user is root.
"""
@wraps(fn)
def xex(*args, **kwargs):
assert os.geteuid() == 0, \
"You have to be root to run function '%s'." % fn.__name__
return fn(*args, **kwargs)
return xex |
java | public static String notEmptyIfNotNull(String value, String name, String info) {
if (value == null) {
return value;
}
if (value.trim().length() == 0) {
throw new IllegalArgumentException(name + " cannot be empty" + (info == null ? "" : ", " + info));
}
re... |
java | private static void debug(String header, String msg) {
if (logger.isTraceEnabled()) {
logger.trace(header);
logger.trace(msg);
}
} |
java | public static FloatStream zip(final float[] a, final float[] b, final float[] c, final float valueForNoneA, final float valueForNoneB,
final float valueForNoneC, final FloatTriFunction<Float> zipFunction) {
return Stream.zip(a, b, c, valueForNoneA, valueForNoneB, valueForNoneC, zipFunction).mapToF... |
python | def download_file(self, response, outfile, quiet=True, chunk_size=1048576):
""" download a file to an output file based on a chunk size
Parameters
==========
response: the response to download
outfile: the output file to download to
quiet: suppress ve... |
python | def service_executions(self, name=None, pk=None, scope=None, service=None, **kwargs):
"""
Retrieve Service Executions.
If additional `keyword=value` arguments are provided, these are added to the request parameters. Please
refer to the documentation of the KE-chain API for additional qu... |
python | def ar_path_to_x_path(ar_path, dest_element=None):
# type: (str, typing.Optional[str]) -> str
"""Get path in translation-dictionary."""
ar_path_elements = ar_path.strip('/').split('/')
xpath = "."
for element in ar_path_elements[:-1]:
xpath += "//A:SHORT-NAME[text()='" + element + "']/.."
... |
python | def _as_graph_element(self):
"""Returns the underlying graph element if possible."""
if self.is_sequence():
raise TypeError('A Pretty Tensor that holds a sequence cannot be '
'represented as a graph element.')
else:
# Self might be holding something else that isn't a true t... |
java | public Map<String, String> handleCorsPreflightRequest(String pOrigin, String pRequestHeaders) {
Map<String,String> ret = new HashMap<String, String>();
if (backendManager.isOriginAllowed(pOrigin,false)) {
// CORS is allowed, we set exactly the origin in the header, so there are no problems w... |
java | public PoolPatchHeaders withLastModified(DateTime lastModified) {
if (lastModified == null) {
this.lastModified = null;
} else {
this.lastModified = new DateTimeRfc1123(lastModified);
}
return this;
} |
java | public static Map<String, ? extends CacheConfig> fromJSON(Reader reader) throws IOException {
return new CacheConfigSupport().fromJSON(reader);
} |
java | public static String jpaFetch(PackageImportAdder adder, FetchTypeGetter... fetchTypeGetters) {
Assert.notNull(adder);
if (fetchTypeGetters == null) {
return "";
}
// we look for the first non empty conf.
// not that it could be a NONE conf => user does not want any ... |
java | @Override
public Iterator<FileSet<CopyEntity>> getFileSetIterator(FileSystem targetFs, CopyConfiguration configuration,
Comparator<FileSet<CopyEntity>> prioritizer, PushDownRequestor<FileSet<CopyEntity>> requestor)
throws IOException {
if (!canCopyTable()) {
return Iterators.emptyIterator();
... |
java | public static void main(final String[] args) {
Switch about = new Switch("a", "about", "display about message");
Switch help = new Switch("h", "help", "display help message");
FileArgument firstFastqFile = new FileArgument("1", "first-fastq-file", "first FASTQ input file", true);
FileArg... |
python | def imresize(src, w, h, *args, **kwargs):
r"""Resize image with OpenCV.
.. note:: `imresize` uses OpenCV (not the CV2 Python library). MXNet must have been built
with USE_OPENCV=1 for `imresize` to work.
Parameters
----------
src : NDArray
source image
w : int, required
... |
python | def by_user(self): # pragma: no cover
"""
Display group membership sorted by group.
Returns:
Array with a dictionary of group membership.
For example: {'test.user': ['testgroup', 'testgroup2']}
"""
users = [i for i in self.__get_users()]
use... |
python | def plot_figures():
"""Plot figures for multivariate distribution section."""
rc("figure", figsize=[8.,4.])
rc("figure.subplot", left=.08, top=.95, right=.98)
rc("image", cmap="gray")
seed(1000)
Q1 = cp.Gamma(2)
Q2 = cp.Normal(0, Q1)
Q = cp.J(Q1, Q2)
#end
subplot(121)
s,t =... |
python | def recall_curve(self, delta_tau=0.01):
""" Computes the relationship between probability threshold
and classification precision. """
# compute thresholds based on the sorted probabilities
orig_thresh = self.threshold
sorted_labels, sorted_probs = self.sorted_values
scor... |
python | def error(self, **kwargs):
'''
Stores the specified error in self.errors.
Accepts the same kwargs as the binwalk.core.module.Error class.
Returns None.
'''
exception_header_width = 100
e = Error(**kwargs)
e.module = self.__class__.__name__
self... |
java | private void addMainPanelHoverHandlers(Panel panel) {
final CmsStyleVariable hoverPanel = new CmsStyleVariable(panel);
hoverPanel.setValue(I_CmsLayoutBundle.INSTANCE.globalWidgetCss().openerNoHover());
panel.addDomHandler(new MouseOverHandler() {
public void onMouseOver(MouseOverEv... |
python | def mstmap(args):
"""
%prog mstmap bcffile/vcffile > matrixfile
Convert bcf/vcf format to mstmap input.
"""
from jcvi.assembly.geneticmap import MSTMatrix
p = OptionParser(mstmap.__doc__)
p.add_option("--dh", default=False, action="store_true",
help="Double haploid populat... |
python | def sample_zip(items_list, num_samples, allow_overflow=False, per_bin=1):
""" Helper for sampling
Given a list of lists, samples one item for each list and bins them into
num_samples bins. If all sublists are of equal size this is equivilent to a
zip, but otherewise consecutive bins will have monotonic... |
java | public static int getNumPoints(Geometry geometry) {
if (geometry == null) {
throw new IllegalArgumentException("Cannot get total number of points for null geometry.");
}
int count = 0;
if (geometry.getGeometries() != null) {
for (Geometry child : geometry.getGeometries()) {
count += getNumPoints(child... |
python | def readlines(self, offset=0):
"""Open the file for reading and yield lines as they are added"""
try:
with open(self._filepath) as fp:
# For full read go through existing lines in file
if self._full_read:
fp.seek(offset)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.