language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public String readLine() throws IOException {
ensureOpen();
StringBuilder sb = null;
start = tempStart;
firstRead = true;
while (true) {
tempLen = 0;
ok = false;
readString();
// if (tempLen != 0)
// System.out.pr... |
java | private boolean pathExists(T u, T v, boolean includeAdjacent) {
if (!nodes.contains(u) || !nodes.contains(v)) {
return false;
}
if (includeAdjacent && isAdjacent(u, v)) {
return true;
}
Deque<T> stack = new LinkedList<>();
Set<T> visited = new Hash... |
java | private List getEntityObjects(Class clazz, final EntityMetadata entityMetadata, EntityType entityType,
SearchHits hits)
{
List results = new ArrayList();
Object entity = null;
for (SearchHit hit : hits.getHits())
{
entity = KunderaCoreUtils.createNewInstance(... |
python | def get_bios(self):
"""
Gets the list of BIOS/UEFI values currently set on the physical server.
Returns:
dict: Dictionary of BIOS/UEFI values.
"""
uri = "{}/bios".format(self.data["uri"])
return self._helper.do_get(uri) |
python | def circle(radius=None, center=None, **kwargs):
"""
Create a Path2D containing a single or multiple rectangles
with the specified bounds.
Parameters
--------------
bounds : (2, 2) float, or (m, 2, 2) float
Minimum XY, Maximum XY
Returns
-------------
rect : Path2D
Path ... |
java | public CircuitBreakerBuilder counterUpdateInterval(Duration counterUpdateInterval) {
requireNonNull(counterUpdateInterval, "counterUpdateInterval");
if (counterUpdateInterval.isNegative() || counterUpdateInterval.isZero()) {
throw new IllegalArgumentException(
"counterUpd... |
java | @Execute
public HtmlResponse index(final SearchForm form) {
validate(form, messages -> {}, () -> asDictIndexHtml());
stemmerOverridePager.clear();
return asHtml(path_AdminDictStemmeroverride_AdminDictStemmeroverrideJsp).renderWith(data -> {
searchPaging(data, form);
});
... |
java | @Override
public SqlAgentFactory setQueryTimeout(final int queryTimeout) {
getDefaultProps().put(PROPS_KEY_QUERY_TIMEOUT, String.valueOf(queryTimeout));
return this;
} |
python | def fetchall(self):
"""
As in DBAPI2.0 (except the fact rows are not tuples but
lists so if you try to modify them, you will succeed instead of
the correct behavior that would be that an exception would have
been raised)
Additionally every row returned by this class is ad... |
java | private static <P extends GISPrimitive, N extends AbstractGISTreeSetNode<P, N>>
N rearrangeTree(AbstractGISTreeSet<P, N> tree, N node, Rectangle2afp<?, ?, ?, ?, ?, ?> desiredBounds,
GISTreeSetNodeFactory<P, N> builder) {
// Search for the node that completely contains the desired area
N topNode = node.getPare... |
python | def profileit(path=None):
"""cProfile decorator to profile a function
:param path: output file path
:type path: str
:return: Function
"""
def inner(func):
@wraps(func)
def wrapper(*args, **kwargs):
prof = cProfile.Profile()
retval = prof.runcall(func, *a... |
python | def _concrete_acl(self, acl_doc):
"""Concretize an ACL document.
:param dict acl_doc: A document describing an ACL entry. Should come from the API.
:returns: An :py:class:`Acl`, or None.
:rtype: :py:class:`bases.BaseInstance`
"""
if not isinstance(acl_doc, dict):
... |
java | public VirtualMachine findByDatastorePath(Datacenter datacenter, String dPath) throws InvalidDatastore, RuntimeFault, RemoteException {
if (datacenter == null) {
throw new IllegalArgumentException("datacenter must not be null.");
}
ManagedObjectReference mor = getVimService().f... |
java | @PostMapping(value = "/attributeMapping/semanticsearch", consumes = APPLICATION_JSON_VALUE)
@ResponseBody
public List<ExplainedAttributeDto> getSemanticSearchAttributeMapping(
@RequestBody Map<String, String> requestBody) {
String mappingProjectId = requestBody.get("mappingProjectId");
String target =... |
java | public static snmp_alarm_config update(nitro_service client, snmp_alarm_config resource) throws Exception
{
resource.validate("modify");
return ((snmp_alarm_config[]) resource.update_resource(client))[0];
} |
python | def resample(self, data, cache_dir=None, mask_area=None, **kwargs):
"""Resample `data` by calling `precompute` and `compute` methods.
Only certain resampling classes may use `cache_dir` and the `mask`
provided when `mask_area` is True. The return value of calling the
`precompute` method... |
python | def select_locale_by_request(self, request, locales=()):
"""Choose an user's locales by request."""
default_locale = locales and locales[0] or self.cfg.default_locale
if len(locales) == 1 or 'ACCEPT-LANGUAGE' not in request.headers:
return default_locale
ulocales = [
... |
java | protected XmlElement transformElement(org.dom4j.Element node) {
XmlElement xe = new XmlElement(node.getName());
// 设置元素的属性
@SuppressWarnings("unchecked")
Iterator<org.dom4j.Attribute> iterator = node.attributeIterator();
while (iterator.hasNext()) {
org.dom4j.Attribute ab = iterator.next();
... |
python | def get_fd_waveform(template=None, **kwargs):
"""Return a frequency domain gravitational waveform.
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.
{p... |
java | public CmsXmlGroupContainer getCacheGroupContainer(String key, boolean online) {
try {
m_lock.readLock().lock();
CmsXmlGroupContainer retValue;
if (online) {
retValue = m_groupContainersOnline.get(key);
if (LOG.isDebugEnabled()) {
... |
java | public static Entry namedObject(String name, Dn baseDn) {
Dn dn = LdapUtils.concatDn(SchemaConstants.CN_ATTRIBUTE, name, baseDn);
Entry entry = new DefaultEntry(dn);
try {
entry.add(SchemaConstants.OBJECT_CLASS_ATTRIBUTE, SchemaConstants.NAMED_OBJECT_OC);
entry.add(Schema... |
python | def fromFile(cls, person, inputFile, format):
"""
Create a L{Mugshot} item for C{person} out of the image data in
C{inputFile}, or update C{person}'s existing L{Mugshot} item to
reflect the new images.
@param inputFile: An image of a person.
@type inputFile: C{file}
... |
java | public Object getParamKeyValue(HttpServletRequest request, ModelHandler modelHandler) {
Object keyValue = null;
try {
ModelMapping modelMapping = modelHandler.getModelMapping();
String keyName = modelMapping.getKeyName();
Debug.logVerbose("[JdonFramework] the keyName is " + keyName, module);
St... |
java | public String getString(ByteBuffer bytes)
{
TypeSerializer<T> serializer = getSerializer();
serializer.validate(bytes);
return serializer.toString(serializer.deserialize(bytes));
} |
python | def get_style_code(self, label):
"""Returns code for given label string
Inverse of get_code
Parameters
----------
label: String
\tLlabel string, field 0 of style tuple
"""
for style in self.styles:
if style[0] == label:
retu... |
java | public final BELScriptParser.define_namespace_return define_namespace() throws RecognitionException {
BELScriptParser.define_namespace_return retval = new BELScriptParser.define_namespace_return();
retval.start = input.LT(1);
Object root_0 = null;
Token string_literal33=null;
T... |
python | def get_class_recipes(class_url, max_page=20, sleep=0.1):
"""获取某个菜谱分类url下的所有菜谱url"""
class_url = class_url + "?page={page}"
recipes = dict()
# 暴力爬取方案,每个菜谱分类请求100页
for page in range(1, max_page):
time.sleep(sleep)
url = class_url.format(page=page)
print("current url: ", url)
... |
java | @Override
public int read() throws IOException {
if (newLineWasRead) {
line += 1;
column = 1;
newLineWasRead = false;
}
int charRead = super.read();
if (charRead > -1) {
char c = (char)charRead;
// found a \r or \n, like on... |
java | public void addTrainingInstance(String label, List<String> features) {
maxent.addInstance(label,features);
} |
python | def query_single_page(query, lang, pos, retry=50, from_user=False):
"""
Returns tweets from the given URL.
:param query: The query parameter of the query url
:param lang: The language parameter of the query url
:param pos: The query url parameter that determines where to start looking
:param re... |
python | def _apply(self, func, name, window=None, center=None,
check_minp=None, **kwargs):
"""
Dispatch to apply; we are stripping all of the _apply kwargs and
performing the original function call on the grouped object.
"""
def f(x, name=name, *args):
x = sel... |
java | public static List<Instant> instantsInRange(Instant firstInstant, Instant lastInstant,
Schedule schedule) {
Preconditions.checkArgument(
isAligned(firstInstant, schedule) && isAligned(lastInstant, schedule),
"unaligned instant");
Preconditions.checkA... |
java | public static List<Long> createTimestampList(final long startUnixTimestamp,
final long endUnixTimestamp) {
if (startUnixTimestamp > endUnixTimestamp) {
return Collections.emptyList();
}
// normalize the start and end (next day's start... |
python | def field_cache_to_index_pattern(self, field_cache):
"""Return a .kibana index-pattern doc_type"""
mapping_dict = {}
mapping_dict['customFormats'] = "{}"
mapping_dict['title'] = self.index_pattern
# now post the data into .kibana
mapping_dict['fields'] = json.dumps(field_... |
java | public void setDevices(java.util.Collection<DeviceSummary> devices) {
if (devices == null) {
this.devices = null;
return;
}
this.devices = new java.util.ArrayList<DeviceSummary>(devices);
} |
java | public static ipsecparameter get(nitro_service service) throws Exception{
ipsecparameter obj = new ipsecparameter();
ipsecparameter[] response = (ipsecparameter[])obj.get_resources(service);
return response[0];
} |
java | public Vector4d fma(Vector4dc a, Vector4dc b, Vector4d dest) {
dest.x = x + a.x() * b.x();
dest.y = y + a.y() * b.y();
dest.z = z + a.z() * b.z();
dest.w = w + a.w() * b.w();
return dest;
} |
java | @Override
public void beginDefinitionList(Map<String, String> parameters)
{
if (getBlockState().getDefinitionListDepth() == 1 && !getBlockState().isInList()) {
printEmptyLine();
} else {
getPrinter().print(NL);
}
} |
python | def set_postmortem_debugger(cls, cmdline,
auto = None, hotkey = None, bits = None):
"""
Sets the postmortem debugging settings in the Registry.
@warning: This method requires administrative rights.
@see: L{get_postmortem_debugger}
@type cmdline... |
python | def published(self, request=None):
"""
Returns the published documents in the current language.
:param request: A Request instance.
"""
language = getattr(request, 'LANGUAGE_CODE', get_language())
if not language:
return self.model.objects.none()
qs... |
python | def xmlGenBinaryDataArrayList(binaryDataInfo, binaryDataDict,
compression='zlib', arrayTypes=None):
""" #TODO: docstring
:params binaryDataInfo: #TODO: docstring
:params binaryDataDict: #TODO: docstring
:params compression: #TODO: docstring
:params arrayTypes: #TODO: d... |
python | def fnmatch(name, pat):
"""Test whether FILENAME matches PATTERN.
Patterns are Unix shell style:
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
An initial period in FILENAME is not special.
Both ... |
python | def get_for_model(self, model):
"""
Returns tuple (Entry instance, created) for specified
model instance.
:rtype: wagtailplus.wagtailrelations.models.Entry.
"""
return self.get_or_create(
content_type = ContentType.objects.get_for_model(model),
... |
java | public static CommerceAddressRestriction findByCommerceCountryId_First(
long commerceCountryId,
OrderByComparator<CommerceAddressRestriction> orderByComparator)
throws com.liferay.commerce.exception.NoSuchAddressRestrictionException {
return getPersistence()
.findByCommerceCountryId_First(commerceCountry... |
java | public static void sendEmail(String email, String subject, String emailBody) {
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
... |
java | public boolean masterStarted() {
if (objectMapper == null)
objectMapper = new ObjectMapper();
try {
String type = objectMapper.readValue(
Unirest.get(String.format("http://%s:%d/opType", masterStatusHost, masterStatusPort)).asJson()
... |
python | def as_html(self, table_class='code-difftable', line_class='line',
new_lineno_class='lineno old', old_lineno_class='lineno new',
code_class='code'):
"""
Return udiff as html table with customized css classes
"""
def _link_to_if(condition, label, url):
... |
java | public void invalidate() {
this.appToken = null;
this.appDBID = null;
this.authorizer = null;
this.intuitServiceType = null;
this.realmID = null;
} |
python | def cli(ctx, config_file, profile, endpoint_url, output, color, debug):
"""
Alerta client unified command-line tool.
"""
config = Config(config_file)
config.get_config_for_profle(profile)
config.get_remote_config(endpoint_url)
ctx.obj = config.options
# override current options with co... |
java | public final void mFLOAT() throws RecognitionException {
try {
int _type = FLOAT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// src/riemann/Query.g:92:5: ( ( '-' )? ( '0' .. '9' )+ ( '.' ( '0' .. '9' )* )? ( EXPONENT )? )
// src/riemann/Query.g:92:9: ( '-' )? ( '0' .. ... |
java | @SuppressWarnings("checkstyle:all")
protected StringConcatenationClient generateMembers(boolean forInterface, boolean forAppender) {
final CodeElementExtractor.ElementDescription parameter = getCodeElementExtractor().getFormalParameter();
final FormalParameterDescription exparameter = new FormalParameterDescriptio... |
python | def main():
"""
NAME
common_mean.py
DESCRIPTION
calculates bootstrap statistics to test for common mean
INPUT FORMAT
takes dec/inc as first two columns in two space delimited files
SYNTAX
common_mean.py [command line options]
OPTIONS
-h prints help m... |
python | def find(self, path, resolved=True):
"""
Get the definition object for the schema type located at the specified
path.
The path may contain (.) dot notation to specify nested types.
Actually, the path separator is usually a (.) but can be redefined
during contruction.
... |
python | def datasets(self):
"""
Return all datasets
:return:
"""
return self.session.query(Dataset).filter(Dataset.vid != ROOT_CONFIG_NAME_V).all() |
java | public static <E extends Comparable<E>> void sortDescending(E[] intArray) {
Quicksort.sort(intArray, 0, intArray.length - 1 , true);
} |
python | def clean_lprof_file(input_fname, output_fname=None):
""" Reads a .lprof file and cleans it """
# Read the raw .lprof text dump
text = ut.read_from(input_fname)
# Sort and clean the text
output_text = clean_line_profile_text(text)
return output_text |
java | @Nonnull
public JSVar var (@Nonnull @Nonempty final String sName,
@Nullable final String sInitValue) throws JSNameAlreadyExistsException
{
return var (sName, sInitValue == null ? JSExpr.NULL : JSExpr.lit (sInitValue));
} |
python | def _updateWordSet(self):
"""Make a set of words, which shall be completed, from text
"""
self._wordSet = set(self._keywords) | set(self._customCompletions)
start = time.time()
for line in self._qpart.lines:
for match in _wordRegExp.findall(line):
se... |
python | def get_cached_token(self):
''' Gets a cached auth token
'''
token_info = None
if self.cache_path:
try:
f = open(self.cache_path)
token_info_string = f.read()
f.close()
token_info = json.loads(token_info_string)
... |
python | def detached(name):
'''
Ensure zone is detached
name : string
name of the zone
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
zones = __salt__['zoneadm.list'](installed=True, configured=True)
if name in zones:
if zon... |
java | public DatanodeInfo chooseTargetNodes(Set<DatanodeInfo> excludedNodes)
throws IOException {
DatanodeInfo target = cluster.getNodeOnDifferentRack(excludedNodes);
if (target == null) {
throw new IOException ("Error choose datanode");
}
return target;
} |
python | def DviPsStrFunction(target = None, source= None, env=None):
"""A strfunction for dvipdf that returns the appropriate
command string for the no_exec options."""
if env.GetOption("no_exec"):
result = env.subst('$PSCOM',0,target,source)
else:
result = ''
return result |
java | public static MemberSummaryBuilder getInstance(
ClassWriter classWriter, Context context)
throws Exception {
MemberSummaryBuilder builder = new MemberSummaryBuilder(context,
classWriter.getClassDoc());
builder.memberSummaryWriters =
new MemberSumma... |
java | public <K, V> Optional<KafkaProducer<K, V>> getProducer(
@NotNull final Serializer<K> keySerializer,
@NotNull final Serializer<V> valueSerializer) {
try {
return partialConfigs.map(
input -> new KafkaProducer<>(input, keySerializer, valueSerializer));
} catch (final Exception e) {
... |
python | def add(self, *widgets):
'''
Place @widgets under the blitting hand of the Container(). Each arg
must be a Widget(), a fellow Container(), or an iterable. Else, things
get ugly...
'''
for w in widgets:
if is_widget(w):
if w not in self.widget... |
python | def showLipds(D=None):
"""
Display the dataset names of a given LiPD data
| Example
| lipd.showLipds(D)
:pararm dict D: LiPD data
:return none:
"""
if not D:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
print(json.dumps(D.keys(), ... |
python | async def query(cls, query: str,
variables: Optional[Mapping[str, Any]] = None,
) -> Any:
'''
Sends the GraphQL query and returns the response.
:param query: The GraphQL query string.
:param variables: An optional key-value dictionary
... |
python | def publish(self, body, routing_key, exchange='amq.default',
virtual_host='/', properties=None, payload_encoding='string'):
"""Publish a Message.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange ... |
python | def ethernet_interfaces(self):
"""Provide reference to EthernetInterfacesCollection instance"""
return ethernet_interface.EthernetInterfaceCollection(
self._conn,
self._get_hpe_sub_resource_collection_path('EthernetInterfaces'),
redfish_version=self.redfish_version) |
python | def get_local_tzone():
"""Get the current time zone on the local host"""
if localtime().tm_isdst:
if altzone < 0:
tzone = '+' + \
str(int(float(altzone) / 60 // 60)).rjust(2,
'0') + \
str(int(float(
... |
python | def filter_primary(bam_file, data):
"""Filter reads to primary only BAM.
Removes:
- not primary alignment (0x100) 256
- supplementary alignment (0x800) 2048
"""
stem, ext = os.path.splitext(bam_file)
out_file = stem + ".primary" + ext
if not utils.file_exists(out_file):
with... |
python | def get_template_names(self):
"""
Returns a list of template names for the view.
:rtype: list.
"""
#noinspection PyUnresolvedReferences
if self.request.is_ajax():
template_name = '/results.html'
else:
template_name = '/index.html'
... |
python | def init_from_class_batches(self, class_batches, num_shards=None):
"""Initializes work pieces from classification batches.
Args:
class_batches: dict with classification batches, could be obtained
as ClassificationBatches.data
num_shards: number of shards to split data into,
if None ... |
java | protected String getHttpAddress(String httpAddress) {
Matcher resolvedMatcher = INETSOCKETADDRESS_PATTERN.matcher(httpAddress);
if (resolvedMatcher.matches()) {
return defaultScheme + resolvedMatcher.group(1) + ":" + resolvedMatcher.group(2);
}
return null;
} |
java | @Override
public Object visitSizeCommand(InvocationContext ctx, SizeCommand command) throws Throwable {
try {
return (doBeforeCall(ctx, command)) ? handleSizeCommand(ctx, command) : null;
}
finally {
doAfterCall(ctx, command);
}
} |
python | def getmembers(obj, *predicates):
""" Return all the members of an object as a list of `(key, value)` tuples, sorted by name.
The optional list of predicates can be used to filter the members.
The default predicate drops members whose name starts with '_'. To disable it, pass `None` as the first predicate... |
python | def deriv2(self, p):
"""Second derivative of the link function g''(p)
implemented through numerical differentiation
"""
from statsmodels.tools.numdiff import approx_fprime_cs
# TODO: workaround proplem with numdiff for 1d
return np.diag(approx_fprime_cs(p, self.deriv)) |
python | def events(self):
# type: () -> Generator[Event, None, None]
"""
Return a generator that provides any events that have been generated
by protocol activity.
:returns: generator of :class:`Event <wsproto.events.Event>` subclasses
"""
while self._events:
... |
python | def cg_prolongation_smoothing(A, T, B, BtBinv, Sparsity_Pattern, maxiter, tol,
weighting='local', Cpt_params=None):
"""Use CG to smooth T by solving A T = 0, subject to nullspace and sparsity constraints.
Parameters
----------
A : csr_matrix, bsr_matrix
SPD sparse ... |
python | def _folder_item_remarks(self, analysis_brain, item):
"""Renders the Remarks field for the passed in analysis
If the edition of the analysis is permitted, adds the field into the
list of editable fields.
:param analysis_brain: Brain that represents an analysis
:param item: anal... |
python | def capture_exceptions(self, f=None, exceptions=None): # TODO: Ash fix kwargs in base
"""
Wrap a function or code block in try/except and automatically call
``.captureException`` if it raises an exception, then the exception
is reraised.
By default, it will capture ``Exception`... |
java | public static double[] doubleArrayCopyOf(CollectionNumber coll) {
double[] data = new double[coll.size()];
IteratorNumber iter = coll.iterator();
int index = 0;
while (iter.hasNext()) {
data[index] = iter.nextDouble();
index++;
}
return dat... |
java | public void retrieveCurrentCustomer(@NonNull CustomerRetrievalListener listener) {
final Customer cachedCustomer = getCachedCustomer();
if (cachedCustomer != null) {
listener.onCustomerRetrieved(cachedCustomer);
} else {
mCustomer = null;
final String operati... |
java | public ServiceFuture<ServerSecurityAlertPolicyInner> getAsync(String resourceGroupName, String serverName, final ServiceCallback<ServerSecurityAlertPolicyInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, serverName), serviceCallback);
} |
python | def hdmbrcheck(disk_mbr, sector_count, bootable):
# type: (bytes, int, bool) -> int
'''
A function to sanity check an El Torito Hard Drive Master Boot Record (HDMBR).
On success, it returns the system_type (also known as the partition type) that
should be fed into the rest of the El Torito methods. ... |
python | def delete_track(self, href=None):
"""Delete a track.
'href' the relative index of the track. May not be none.
Returns nothing.
If the response status is not 204, throws and APIException."""
# Argument error checking.
assert href is not None
raw_result = self... |
java | private void watchPath() {
for (;;) {
//監視キーの送信を待機
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
log.debug("WatchService catched InterruptedException.");
break;
} catch (Throwable ex) {
log.error("Unexpected exception occured.", ex);
break;
}
f... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case TypesPackage.JVM_EXECUTABLE__TYPE_PARAMETERS:
return getTypeParameters();
case TypesPackage.JVM_EXECUTABLE__PARAMETERS:
return getParameters();
case TypesPackage.JVM_EXECUTABLE__EXCEPTIONS:
... |
java | public int originalFrame() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.entry(this, tc, "originalFrame");
int result;
synchronized (getMessageLockArtefact()) {
if ((contents == null) || reallocated) {
result = -1;
}
else {
result = length;
... |
java | public String apply(final String stringValue, CacheScope cacheScope) {
if (stringValue != null && (lengthLimit < 0 || stringValue.length() <= lengthLimit)) {
return (String) (cacheScope == CacheScope.GLOBAL_SCOPE ? globalCache : applicationCache)
.computeIfAbsent(CharBuffer.wrap(... |
java | public boolean read(DataInputStream daIn, boolean bFixedLength) // Fixed length = false
{
try {
float fData = daIn.readFloat();
Float flData = null;
if (!Float.isNaN(fData))
flData = new Float(fData);
int errorCode = this.setData(flData, DBCo... |
java | public static boolean isSymmetric(DMatrixRMaj m , double tol ) {
if( m.numCols != m.numRows )
return false;
double max = CommonOps_DDRM.elementMaxAbs(m);
for( int i = 0; i < m.numRows; i++ ) {
for( int j = 0; j < i; j++ ) {
double a = m.get(i,j)/max;
... |
java | public JobTargetGroupInner get(String resourceGroupName, String serverName, String jobAgentName, String targetGroupName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName, targetGroupName).toBlocking().single().body();
} |
python | def populate_items(self, request):
'''populate and returns filtered items'''
self._items = self.get_items(request)
return self.items |
java | public CompositeEntityExtractor getCompositeEntity(UUID appId, String versionId, UUID cEntityId) {
return getCompositeEntityWithServiceResponseAsync(appId, versionId, cEntityId).toBlocking().single().body();
} |
java | public static void main(String[] args) throws Exception {
String indexLocation = args[0];
int numTrainVectors = Integer.parseInt(args[1]);
int vectorLength = Integer.parseInt(args[2]);
int numPrincipalComponents = Integer.parseInt(args[3]);
boolean whitening = true;
boolean compact = false;
PCA... |
python | def compute_score(self):
"""Calculate the overall test score using the configuration."""
# LOGGER.info("Begin scoring")
cases = self.get_configured_tests() | set(self.result.cases)
scores = DataFrame({"score": 0.0, "max": 1.0},
index=sorted(cases))
self... |
python | def _error(self, exc_info):
""" Retrieves the error info """
if self._exc_info:
if self._traceback:
return exc_info
return exc_info[:2]
return exc_info[1] |
python | def shuffled_batches(self, batch_size):
""" Generate randomized batches of data """
if batch_size >= self.size:
yield self
else:
batch_splits = math_util.divide_ceiling(self.size, batch_size)
indices = list(range(self.size))
np.random.shuffle(indic... |
python | def create_predictable_zip(path):
"""
Create a zip file with predictable sort order and metadata so that MD5 will
stay consistent if zipping the same content twice.
Args:
path (str): absolute path either to a directory to zip up, or an existing zip file to convert.
Returns: path (str) to the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.