language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def display(self):
""" dump operation
"""
print("{}".format(self))
for task in self.tasks:
print(" - {}".format(task)) |
java | @Override
public void copyFrom(final CopyFrom obj) {
final OpenSearchModule osm = (OpenSearchModule) obj;
setTotalResults(osm.getTotalResults());
setItemsPerPage(osm.getItemsPerPage());
setStartIndex(osm.getStartIndex());
setLink(osm.getLink());
for (final OSQuery q :... |
python | def _raw_to_der(self, raw_signature):
"""Convert signature from RAW encoding to DER encoding."""
component_length = self._sig_component_length()
if len(raw_signature) != int(2 * component_length):
raise ValueError("Invalid signature")
r_bytes = raw_signature[:component_lengt... |
python | def pretty_echo(cls, message):
""" Display message using pretty print formatting. """
if cls.intty():
if message:
from pprint import pprint
pprint(message) |
python | def _get_query_uri(self):
"""
Returns the URI endpoint for performing queries of a
Predix Time Series instance from environment inspection.
"""
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_timeseries = services... |
java | private synchronized <T> void connect(OpenStackRequest<T> request) throws KeyManagementException,
NoSuchAlgorithmException {
/*
* If we've already set up the client, return it. Otherwise, set it up and cache the client for subsequent use.
*/
if (client != null) {
re... |
python | def prepare_headers(oauth_params, headers=None, realm=None):
"""**Prepare the Authorization header.**
Per `section 3.5.1`_ of the spec.
Protocol parameters can be transmitted using the HTTP "Authorization"
header field as defined by `RFC2617`_ with the auth-scheme name set to
"OAuth" (case insensit... |
python | def assemble(ops, target=None):
"""
Assemble a set of :class:`Op` and :class:`Label` instance back into
bytecode.
Arguments:
ops(list): A list of opcodes and labels (as returned by
:func:`disassemble`).
target: The opcode specification of the targeted python
vers... |
python | def setEventCallback(self, event, callback):
"""
Set a function to call for a given event.
event must be one of:
TRANSFER_COMPLETED
TRANSFER_ERROR
TRANSFER_TIMED_OUT
TRANSFER_CANCELLED
TRANSFER_STALL
TRANSFER_NO_DEVICE
... |
java | public static Evaluation getEvaluation(ComputationGraph model, MultiDataSetIterator testData) {
if (model.getNumOutputArrays() != 1)
throw new IllegalStateException("GraphSetSetAccuracyScoreFunction cannot be "
+ "applied to ComputationGraphs with more than one output. Nu... |
java | @Override
public int countByCommerceShippingMethodId(long commerceShippingMethodId) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_COMMERCESHIPPINGMETHODID;
Object[] finderArgs = new Object[] { commerceShippingMethodId };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == n... |
python | def start_to(self, ip, tcpport=102):
"""
start server on a specific interface.
"""
if tcpport != 102:
logger.info("setting server TCP port to %s" % tcpport)
self.set_param(snap7.snap7types.LocalPort, tcpport)
assert re.match(ipv4, ip), '%s is invalid ipv4'... |
java | private void update(I image) {
computeCurrToInit_PixelTran();
// only process a cropped portion to speed up processing
RectangleLength2D_I32 box = DistortImageOps.boundBox(image.width, image.height,
stitchedImage.width, stitchedImage.height,work, tranCurrToWorld);
int x0 = box.x0;
int y0 = box.y0;
int... |
python | def serving_input_fn(self, hparams):
"""For serving/predict, assume that only video frames are provided."""
video_input_frames = tf.placeholder(
dtype=tf.float32,
shape=[
None, hparams.video_num_input_frames, self.frame_width,
self.frame_height, self.num_channels
... |
java | public static int getResId(@NonNull final Context context, @AttrRes final int resourceId,
final int defaultValue) {
return getResId(context, -1, resourceId, defaultValue);
} |
java | private CALC unbindAll(AbstractCalculator<CALC> undbindFrom) {
// find root and first child
AbstractCalculator root = undbindFrom.parentCalculator != null ? undbindFrom.parentCalculator : undbindFrom;
AbstractCalculator child = root.childCalculator;
while (root != null) {
... |
python | def repel_text_from_bboxes(add_bboxes, texts, renderer=None, ax=None,
expand=(1.2, 1.2), only_use_max_min=False,
move=False):
"""
Repel texts from other objects' bboxes while expanding their (texts')
bounding boxes by expand (x, y), e.g. (1.2, 1.2) would... |
java | @Override protected FieldItem[] getDefaultTaskData()
{
FieldItem[] result = new FieldItem[]
{
new FieldItem(TaskField.UNIQUE_ID, FieldLocation.FIXED_DATA, 0, 0, 0, 0, 0),
new FieldItem(TaskField.ID, FieldLocation.FIXED_DATA, 0, 4, 0, 0, 0),
new FieldItem(TaskField.EARLY_FINISH,... |
java | public void addColumn(ByteBuffer name, ByteBuffer value, long timestamp) throws IOException
{
addColumn(new BufferCell(metadata.comparator.cellFromByteBuffer(name), value, timestamp));
} |
python | def process_stats(self, stats, prefix, metric_categories, nested_tags, tags, recursion_level=0):
"""
The XML will have Stat Nodes and Nodes that contain the metrics themselves
This code recursively goes through each Stat Node to properly setup tags
where each Stat will have a different t... |
java | public Iterable<DColumn> getAllColumns(String storeName, String rowKey) {
return getColumnSlice(storeName, rowKey, null, null);
} |
python | def fintlist(alist):
"""A list of integers"""
outlist = []
if not isinstance(alist, (list, tuple)):
# we have a string (comma-separated integers)
alist = alist.strip().strip("[] ").split(",")
for it in alist:
if it:
outlist.append(fint(it))
return outlist |
java | public void encode(DataItem dataItem) throws CborException {
if (dataItem == null) {
dataItem = SimpleValue.NULL;
}
if (dataItem.hasTag()) {
Tag tagDi = dataItem.getTag();
tagEncoder.encode(tagDi);
}
switch (dataItem.getMajorType()) {
... |
python | def from_handle(fh, stream_default='fasta'):
"""
Look up the BioPython file type corresponding to a file-like object.
For stdin, stdout, and stderr, ``stream_default`` is used.
"""
if fh in (sys.stdin, sys.stdout, sys.stderr):
return stream_default
return from_filename(fh.name) |
java | @Override
public AdminAddUserToGroupResult adminAddUserToGroup(AdminAddUserToGroupRequest request) {
request = beforeClientExecution(request);
return executeAdminAddUserToGroup(request);
} |
python | def paired_reader_from_bamfile(args,
log,
usage_logger,
annotated_writer):
'''Given a BAM file, return a generator that yields filtered, paired reads'''
total_aligns = pysamwrapper.total_align_count(args.input_bam)
... |
java | protected void prepareDirectories() throws ManagedProcessException {
baseDir = Util.getDirectory(configuration.getBaseDir());
libDir = Util.getDirectory(configuration.getLibDir());
try {
String dataDirPath = configuration.getDataDir();
if (Util.isTemporaryDirectory(dataDi... |
java | public RouteTableInner createOrUpdate(String resourceGroupName, String routeTableName, RouteTableInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeTableName, parameters).toBlocking().last().body();
} |
python | def piece_to_id(input, model_file=None, model_proto=None, name=None):
"""Converts piece into vocabulary id.
Args:
input: An arbitrary tensor of string.
model_file: The sentencepiece model file path.
model_proto: The sentencepiece model serialized proto.
Either `model_file` or `model_pr... |
java | private String getJspRfsPath(CmsResource resource, boolean online) throws CmsLoaderException {
String jspVfsName = resource.getRootPath();
String extension;
int loaderId = OpenCms.getResourceManager().getResourceType(resource.getTypeId()).getLoaderId();
if ((loaderId == CmsJspLoader.RES... |
java | public static Double getDoubleValue(JSONObject jsonObject, String key) throws JSONException {
checkArguments(jsonObject, key);
JSONValue value = jsonObject.get(key);
if (value != null && value.isNumber() != null) {
double number = ((JSONNumber) value).doubleValue();
return number;
}
return null;
} |
java | @Override
public String processReturningText(String xml, HttpAction hm) {
XmlConverter.failOnError(xml);
if (moveToken) {
token.processReturningText(xml, hm);
moveToken = false;
} else {
log.debug("Got returning text: \"{}\"", xml);
setHasMoreMessages(false);
}
return "";
... |
python | def expand_abbreviations(template, abbreviations):
"""Expand abbreviations in a template name.
:param template: The project template name.
:param abbreviations: Abbreviation definitions.
"""
if template in abbreviations:
return abbreviations[template]
# Split on colon. If there is no c... |
java | public static Status cpe(String value) {
if ("cpe:2.3:".regionMatches(0, value, 0, 8)) {
return formattedString(value);
}
return cpeUri(value);
} |
java | public void debug(Object message)
{
if (IS12)
{
getLogger().log(FQCN, Level.DEBUG, message, null);
}
else
{
getLogger().log(FQCN, Level.DEBUG, message, null);
}
} |
java | public static String getcompressedKeyword(Text keyword)
{
String compressedKeyword = "";
String key = keyword.getText();
String remove = " ()+,/:[]<>\"*";
for (int i = 0; i < key.length(); i++)
{
if (remove.indexOf(key.charAt(i)) == -1)
{
compressedKeyword = compressedKeyword + key.charAt(i);
}
... |
java | public static int calculateMaxPartitionSize(int maxEntryCount, int partitionCount) {
final double balancedPartitionSize = (double) maxEntryCount / (double) partitionCount;
final double approximatedStdDev = Math.sqrt(balancedPartitionSize);
int stdDevMultiplier;
if (maxEntryCount <= STD_... |
java | public void serialize(DocumentImpl doc) throws IOException {
org.w3c.dom.Document w3cDoc = doc.getDocument();
if (w3cDoc instanceof HTMLDocumentImpl) {
// if w3cDoc has no document type default to html5: <!DOCTYPE html>
writer.write("<!DOCTYPE html");
DocumentType dt = w3cDoc.getDoctype();
if (dt ... |
java | protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted, boolean flushImmediately) {
return newThread(new StreamPumper(is, os, closeWhenExhausted, flushImmediately));
} |
java | @Nullable
public static Properties loadPropertiesFromResource(URL resource) {
try (InputStream stream = resource.openStream()) {
return loadProperties(stream);
} catch (IOException e) {
LOG.warn("Failed to read properties from {}: {}", resource, e.toString());
return null;
}
} |
java | void log(IpcLogEntry entry) {
Level level = entry.getLevel();
Predicate<Marker> enabled;
BiConsumer<Marker, String> log;
switch (level) {
case TRACE:
enabled = logger::isTraceEnabled;
log = logger::trace;
break;
case DEBUG:
enabled = logger::isDebugEnabled;
... |
java | private void resetCorrectOffsets() {
String kafkaServers = consumerContext.getProperties().getProperty("bootstrap.servers");
String zkServers = consumerContext.getProperties().getProperty("zookeeper.connect");
if(StringUtils.isAnyBlank(kafkaServers,zkServers)){
logger.warn("resetCorrectOffsets exit。Please chec... |
java | @NonNull
public static Intent newIntent(@NonNull Context context,
boolean requirePostalField,
boolean updatesCustomer) {
return new Intent(context, AddSourceActivity.class)
.putExtra(EXTRA_SHOW_ZIP, requirePostalField)
... |
python | def QA_fetch_future_day_adv(
code,
start, end=None,
if_drop_index=True,
# 🛠 todo collections 参数没有用到, 且数据库是固定的, 这个变量后期去掉
collections=DATABASE.index_day):
'''
:param code: code: 字符串str eg 600085
:param start: 字符串str 开始日期 eg 2011-01-01
:param end: 字符串str 结束日期 eg ... |
java | public void addReport(ValidationReport report) {
errors.addAll(report.errors);
warnings.addAll(report.warnings);
oks.addAll(report.oks);
cdkErrors.addAll(report.cdkErrors);
} |
java | private void writeVarUInt(int v)
{
int offset = myOffset;
if (v < (1 << (7 * 1))) // 1 byte - 7 bits used - 0x7f max
{
if (--offset < 0) {
offset = growBuffer(offset);
}
myBuffer[offset] = (byte) (v | 0x80 );
}
... |
python | def fit(self, X, y, **fit_params):
"""Find the best parameters for a particular model.
Parameters
----------
X, y : array-like
**fit_params
Additional partial fit keyword arguments for the estimator.
"""
return default_client().sync(self._fit, X, y, *... |
python | def process_gene_interaction(self, limit):
"""
The gene interaction file includes identified interactions,
that are between two or more gene (products).
In the case of interactions with >2 genes, this requires creating
groups of genes that are involved in the interaction.
... |
java | public void removeLockedObject() {
if (this != resourceLocks.root && !this.getPath().equals("/")) {
int size = parent.children.length;
for (int i = 0; i < size; i++) {
if (parent.children[i].equals(this)) {
LockedObject[] newChildren = new LockedObjec... |
java | protected void reflectionAppendArrayDetail(StringBuilder buffer, String fieldName, Object array) {
buffer.append(arrayStart);
int length = Array.getLength(array);
for (int i = 0; i < length; i++) {
Object item = Array.get(array, i);
if (i > 0) {
buffer.app... |
python | def roots(self):
"""get the nodes with no children"""
return [x for x in self._nodes.values() if x.id not in self._c2p] |
java | public double getDouble(final int index, final ByteOrder byteOrder)
{
if (SHOULD_BOUNDS_CHECK)
{
boundsCheck0(index, SIZE_OF_DOUBLE);
}
if (NATIVE_BYTE_ORDER != byteOrder)
{
final long bits = UNSAFE.getLong(byteArray, addressOffset + index);
... |
java | public static FileFilter adapt(final Filter<File> toAdapt) {
// Check sanity
Validate.notNull(toAdapt, "toAdapt");
// Already a FileFilter?
if (toAdapt instanceof FileFilter) {
return (FileFilter) toAdapt;
}
// Wrap and return.
return new FileFilter... |
java | private void fill() throws IOException {
byte[] buffer = getBufIfOpen();
if (markpos < 0)
pos = 0; /* no mark: throw away the buffer */
else if (pos >= buffer.length) /* no room left in buffer */
if (markpos > 0) { /* can throw away early part of the buffer *... |
python | def _parse_tree(self, node):
""" Parse a <checksum> object """
if 'filename' in node.attrib:
self.filename = node.attrib['filename']
if 'type' in node.attrib:
self.kind = node.attrib['type']
if 'target' in node.attrib:
self.target = node.attrib['target... |
java | public void show(int x, int y) {
disabledHLayout.setSize("100%", "100%");
disabledHLayout.setStyleName("disabledBackgroundStyle");
disabledHLayout.show();
loadingImg.setSize("100px", "100px");
loadingImg.setTop(y); //loading image height is 50px
loadingImg.setLeft(x); //... |
python | def draw(self, img, pixmapper, bounds):
'''draw a polygon on the image'''
if self.hidden:
return
(x,y,w,h) = bounds
spacing = 1000
while True:
start = mp_util.latlon_round((x,y), spacing)
dist = mp_util.gps_distance(x,y,x+w,y+h)
cou... |
python | def insert(self, data, **kwargs):
"""
Calls the create method of OBJTYPE
NOTE: this function is only properly usable on children classes that
have overridden either OBJTYPE or PATH.
@param data: the data of the new object to be created
@param **kwargs: f... |
python | def _write_triggers(self, fh, triggers, indent=""):
"""Write triggers to a file handle.
Parameters:
fh (file): file object.
triggers (list): list of triggers to write.
indent (str): indentation for each line.
"""
for trig in triggers:
fh.... |
python | def best_oob_mae_weight(trees):
"""
Returns weights so that the tree with smallest out-of-bag mean absolute error
"""
best = (+1e999999, None)
for tree in trees:
oob_mae = tree.out_of_bag_mae
if oob_mae is None or oob_mae.mean is None:
cont... |
python | def _from_dict(cls, _dict):
"""Initialize a MessageContext object from a json dictionary."""
args = {}
if 'global' in _dict:
args['global_'] = MessageContextGlobal._from_dict(
_dict.get('global'))
if 'skills' in _dict:
args['skills'] = MessageConte... |
java | protected ListItemHostWidget getRecycleableView(int dataIndex) {
ListItemHostWidget host = null;
try {
host = getHostView(dataIndex);
if (host != null) {
if (host.isRecycled()) {
Widget view = getViewFromAdapter(dataIndex, host);
... |
python | def fetch_search_document(self, *, index):
"""Fetch the object's document from a search index by id."""
assert self.pk, "Object must have a primary key before being indexed."
client = get_client()
return client.get(index=index, doc_type=self.search_doc_type, id=self.pk) |
java | protected boolean prePrepare() {
if (tc.isEntryEnabled())
Tr.entry(tc, "prePrepare");
//
// Cancel timeout prior to completion phase
//
cancelAlarms();
//
// Inform the Synchronisations we are about to complete
//
if (!_rollbackOnly) ... |
python | def translate(rect, x, y, width=1):
"""
Given four points of a rectangle, translate the
rectangle to the specified x and y coordinates and,
optionally, change the width.
:type rect: list of tuples
:param rect: Four points describing a rectangle.
:type x: float
:param x: The amount to sh... |
java | public V setValue(final V value) {
V oldValue = this.getValue();
this.values[tree.pageIndex] = value;
return oldValue;
} |
python | def set_observable(self,tseq,qseq):
"""Set the observable sequence data
:param tseq: target sequence (from the homopolymer)
:param qseq: query sequence ( from the homopolymer)
:type tseq: string
:type qseq: string
"""
tnt = None
qnt = None
if len(tseq) > 0: tnt = tseq[0]
if len... |
python | def from_db(cls, db, force=False):
"""Make instance from database.
For performance, this caches the episode types for the database. The
`force` parameter can be used to bypass this.
"""
if force or db not in cls._cache:
cls._cache[db] = cls._new_from_db(db)
... |
python | def update(self, alert_condition_infra_id, policy_id,
name, condition_type, alert_condition_configuration, enabled=True):
"""
This API endpoint allows you to update an alert condition for infrastucture
:type alert_condition_infra_id: int
:param alert_condition_infra_id: A... |
java | private String getDialogTitle() {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
String key = getString(R.string.dialog_title_preference_key);
String defaultValue = getString(R.string.dialog_title_preference_default_value);
... |
java | public PendingCall present() {
logDialogActivity(activity, fragment, getEventName(appCall.getRequestIntent()),
AnalyticsEvents.PARAMETER_DIALOG_OUTCOME_VALUE_COMPLETED);
if (onPresentCallback != null) {
try {
onPresentCallback.onPresent(activity);
... |
java | @Override
public final HeadDocument findByFileAndString(
final String filename, final String string) {
final Query searchQuery = new Query(Criteria.where("string").is(string)
.and("filename").is(filename));
final HeadDocument headDocument =
mongoTemplate.f... |
python | def add_source(name, source_location, username=None, password=None):
'''
Instructs Chocolatey to add a source.
name
The name of the source to be added as a chocolatey repository.
source
Location of the source you want to work with.
username
Provide username for chocolatey ... |
python | def int_imf_dm(m1,m2,m,imf,bywhat='bymass',integral='normal'):
'''
Integrate IMF between m1 and m2.
Parameters
----------
m1 : float
Min mass
m2 : float
Max mass
m : float
Mass array
imf : float
IMF array
bywhat : string, optional
'bymass' in... |
python | def parseFullScan(self, i, modifications=False):
"""
parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml
"""
scanObj = PeptideObject()
peptide = str(i[1])
pid=i[2]
scanObj.acc = self.protein_map.get(i... |
python | def hydrate_input_references(input_, input_schema, hydrate_values=True):
"""Hydrate ``input_`` with linked data.
Find fields with complex data:<...> types in ``input_``.
Assign an output of corresponding data object to those fields.
"""
from .data import Data # prevent circular import
for fi... |
python | def _format_output(content, typ):
"""Tabularize the content according to its type.
Args:
content (str): The content of a metric.
typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv).
Returns:
str: Content in a raw or tabular format.
"""
if "csv" in str(typ):
... |
java | public SDVariable binomial(int nTrials, double p, long... shape) {
return binomial(null, nTrials, p, shape);
} |
java | public final List<T> toSortedList(final Comparator<? super T> comparator) {
return Ordering.from(comparator).immutableSortedCopy(
toCollection(Lists.<T>newArrayListWithCapacity(256)));
} |
java | public IfcExternalSpatialElementTypeEnum createIfcExternalSpatialElementTypeEnumFromString(EDataType eDataType,
String initialValue) {
IfcExternalSpatialElementTypeEnum result = IfcExternalSpatialElementTypeEnum.get(initialValue);
if (result == null)
throw new IllegalArgumentException(
"The value '"... |
java | public static void spawnEjectedItem(World world, BlockPos pos, ItemStack itemStack)
{
if (itemStack == null || world.isRemote)
return;
float rx = world.rand.nextFloat() * 0.8F + 0.1F;
float ry = world.rand.nextFloat() * 0.8F + 0.1F;
float rz = world.rand.nextFloat() * 0.8F + 0.1F;
EntityItem entityItem ... |
python | def block_until_expired(timeout):
""" 阻塞当前程序运行, 直到超时
.. note: 会阻塞当前程序运行
- 如果 ``timeout大于0``, 则当作 ``计时阻塞器`` 来使用
.. code:: python
@run_until(0.1)
def s2():
m = 5
while m:
print('s2: ', m, now())
time.sleep(... |
java | public void marshall(TelemetryRecord telemetryRecord, ProtocolMarshaller protocolMarshaller) {
if (telemetryRecord == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(telemetryRecord.getTimestamp(), TI... |
python | def template(self):
"""Return a method template for this method."""
r = fapi.get_config_template(self.namespace, self.name,
self.snapshot_id, self.api_url)
fapi._check_response_code(r, 200)
return r.json() |
python | def resubmit(self, req, keyspace, req_d, retries):
"""
Push this request to the front of the line, just to be a jerk.
"""
self.log('resubmitting %s request' % (req.method,))
self.pushRequest_really(req, keyspace, req_d, retries)
try:
self.request_queue.pending... |
python | def new_common_diceware_password(self, number_of_words=6, hint=''):
"""
Return a suggested password
:param int number_of_words: number of words generated
:param str hint:
:return tuple: a suggested password and a sentence
>>> GeneratePassword().new_common_diceware_passwo... |
python | def code_constants(self):
"""
All of the constants that are used by this functions's code.
"""
# TODO: remove link register values
return [const.value for block in self.blocks for const in block.vex.constants] |
java | static double clampMetricValue(double value) {
// Leave as is and let the SDK reject it
if (Double.isNaN(value)) {
return value;
}
double magnitude = Math.abs(value);
if (magnitude == 0) {
// Leave zero as zero
return 0;
}
// No... |
python | def log_dictionary(dictionary, msg='', logger=None, level='debug', item_prefix=' '):
""" Writes a log message with key and value for each item in the dictionary.
:param dictionary: the dictionary to be logged
:type dictionary: dict
:param name: An optional message that is logged before the... |
java | public BigInteger getBigIntegerFrom(JsonValue json) {
if (json.isString()) {
return new BigInteger(json.asString());
} else {
return new BigInteger(json.toString());
}
} |
java | @Override
public boolean validate(Field f) throws RuleValidationException
{
boolean checkvalidation = true;
for (Annotation annotate : f.getDeclaredAnnotations())
{
RelationType eruleType = getRuleType(annotate.annotationType().getSimpleName());
if (eruleType !=... |
java | private void processConversationDeliveredAt(String conversationId, int convType, long timestamp) {
AVConversationHolder conversation = session.getConversationHolder(conversationId, convType);
conversation.onConversationDeliveredAtEvent(timestamp);
} |
python | def print_class_histogram(roidbs):
"""
Args:
roidbs (list[dict]): the same format as the output of `load_training_roidbs`.
"""
dataset = DetectionDataset()
hist_bins = np.arange(dataset.num_classes + 1)
# Histogram of ground-truth objects
gt_hist = np.zeros((dataset.num_classes,), d... |
java | public EtcdResult cad(String key, Map<String, String> params) throws EtcdClientException {
URI uri = buildUriWithKeyAndParams(key, params);
HttpDelete httpDelete = new HttpDelete(uri);
return syncExecute(httpDelete, new int[] {200, 412}, 101);
} |
python | def _generate_examples(self, archive, validation_labels=None):
"""Yields examples."""
if validation_labels: # Validation split
for example in self._generate_examples_validation(archive,
validation_labels):
yield example
# Training split.... |
python | def probability_in(self, a, b):
"""
Returns the probability of a random variable falling between the given
values.
"""
if self.mean is None:
return
p1 = normdist(x=a, mu=self.mean, sigma=self.standard_deviation)
p2 = normdist(x=b, mu=self.mean, sigma=s... |
java | public Set<T> getDependents(T element) {
lock.readLock().lock();
try {
Set<T> dependants = this.incomingEdges.get(element);
if (dependants == null || dependants.isEmpty()) {
return new HashSet<>();
}
return Collections.unmodifiableSet(this.incomingEdges.get(el... |
java | public VirtualNetworkLinkInner update(String resourceGroupName, String privateZoneName, String virtualNetworkLinkName, VirtualNetworkLinkInner parameters, String ifMatch) {
return updateWithServiceResponseAsync(resourceGroupName, privateZoneName, virtualNetworkLinkName, parameters, ifMatch).toBlocking().last().... |
python | def get_sequence_alignment_printer_objects(self, pdb_list = [], reversed = True, width = 80, line_separator = '\n'):
'''Takes a list, pdb_list, of pdb names e.g. ['Model', 'Scaffold', ...] with which the object was created.
Using the first element of this list as a base, get the sequence alignments ... |
java | public BigInteger getBigInteger(int index) throws JSONException {
Object object = this.get(index);
try {
return new BigInteger(object.toString());
} catch (Exception e) {
throw new JSONException("JSONArray[" + index +
"] could not convert to BigInteger.");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.