language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private ObjectNode createResponseSuccess(String jsonRpc, Object id, JsonNode result) {
ObjectNode response = mapper.createObjectNode();
response.put(JSONRPC, jsonRpc);
if (Integer.class.isInstance(id)) {
response.put(ID, Integer.class.cast(id).intValue());
} else if (Long.class.isInstance(id)) {
response.... |
python | def fastgapfill(model_extended, core, solver, weights={}, epsilon=1e-5):
"""Run FastGapFill gap-filling algorithm by calling
:func:`psamm.fastcore.fastcore`.
FastGapFill will try to find a minimum subset of reactions that includes
the core reactions and it also has no blocked reactions.
Return the ... |
python | def compute_tab_title(self, vte):
"""Abbreviate and cut vte terminal title when necessary
"""
vte_title = vte.get_window_title() or _("Terminal")
try:
current_directory = vte.get_current_directory()
if self.abbreviate and vte_title.endswith(current_directory):
... |
java | private void reportError(StorageDirectory sd) {
if (storage instanceof NNStorage) {
// pass null, since we handle the disable here
((NNStorage)storage).reportErrorsOnDirectory(sd, null);
} else {
LOG.error("Failed direcory: " + sd.getCurrentDir());
}
} |
java | public final void usage(String commandName, StringBuilder out, String indent) {
String description = getCommandDescription(commandName);
JCommander jc = commander.findCommandByAlias(commandName);
if (description != null) {
out.append(indent).append(description);
out.appe... |
java | @DefaultVisibilityForTesting
static TagsComponent loadTagsComponent(@Nullable ClassLoader classLoader) {
try {
// Call Class.forName with literal string name of the class to help shading tools.
return Provider.createInstance(
Class.forName(
"io.opencensus.impl.tags.TagsComponen... |
java | public <T> MutateInBuilder insert(String path, T fragment, SubdocOptionsBuilder optionsBuilder) {
asyncBuilder.insert(path, fragment, optionsBuilder);
return this;
} |
java | @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jTextField... |
java | @Override
protected void visitFunctionNode(FunctionNode node) {
// Cannot simplify nonplugin functions.
// TODO(brndn): we can actually simplify checkNotNull.
if (node.getSoyFunction() instanceof BuiltinFunction) {
return;
}
if (node.getSoyFunction() instanceof LoggingFunction) {
retu... |
python | def is_series(data):
"""
Checks whether the supplied data is of Series type.
"""
dd = None
if 'dask' in sys.modules:
import dask.dataframe as dd
return((pd is not None and isinstance(data, pd.Series)) or
(dd is not None and isinstance(data, dd.Series))) |
java | public static JwtClaims getDefaultJwtClaims() {
JwtClaims claims = new JwtClaims();
claims.setIssuer(jwtConfig.getIssuer());
claims.setAudience(jwtConfig.getAudience());
claims.setExpirationTimeMinutesInTheFuture(jwtConfig.getExpiredInMinutes());
claims.setGeneratedJwtId(); // ... |
java | public void writeOverSet(int which, List<Point2D_I32> points) {
BlockIndexLength set = sets.get(which);
if( set.length != points.size() )
throw new IllegalArgumentException("points and set don't have the same length");
for (int i = 0; i < set.length; i++) {
int index = set.start + i*2;
int blockIndex = ... |
python | def rescale(curves, values):
"""
Multiply the losses in each curve of kind (losses, poes) by the
corresponding value.
:param curves: an array of shape (A, 2, C)
:param values: an array of shape (A,)
"""
A, _, C = curves.shape
assert A == len(values), (A, len(values))
array = numpy.z... |
python | def _fill_text(self, text, width, indent):
"""Wraps text like HelpFormatter, but doesn't squash lines
This makes it easier to do lists and paragraphs.
"""
parts = text.split('\n\n')
for i, part in enumerate(parts):
# Check to see if it's a bulleted list--if so, then... |
java | @Override
public final void setLang(final Languages pLang) {
this.lang = pLang;
if (this.itsId == null) {
this.itsId = new IdI18nCurrency();
}
this.itsId.setLang(this.lang);
} |
java | private static boolean valueConstantsMatch(AbstractExpression e1, AbstractExpression e2) {
return (e1 instanceof ParameterValueExpression && e2 instanceof ConstantValueExpression ||
e1 instanceof ConstantValueExpression && e2 instanceof ParameterValueExpression) &&
equalsAsCVE(e1... |
java | protected IObjectPickler getCustomPickler(Class<?> t) {
IObjectPickler pickler = customPicklers.get(t);
if(pickler!=null) {
return pickler; // exact match
}
// check if there's a custom pickler registered for an interface or abstract base class
// that this object implements or inherits from.
for(Entry... |
java | public static HttpResponse execute(HttpRequestBase request) throws IOException {
Assert.notNull(request, "Missing request!");
HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new DefaultRedirectStrategy()).build();
return client.execute(request);
} |
python | def prev_this_next(it, sentinel=None):
"""Utility to return (prev, this, next) tuples from an iterator"""
i1, i2, i3 = tee(it, 3)
next(i3, None)
return zip(chain([sentinel], i1), i2, chain(i3, [sentinel])) |
java | final Entry<K, V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key);
for (Entry<K, V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
if (e.hash == hash && ((e.key) == key || (key != null && key.equals(e.key)))) return e;
}
return null;
} |
python | def _init_request_logging(self, app):
"""
Sets up request logging unless ``APPINSIGHTS_DISABLE_REQUEST_LOGGING``
is set in the Flask config.
Args:
app (flask.Flask). the Flask application for which to initialize the extension.
"""
enabled = not app.config.get... |
python | def WalkChildren(elem):
"""
Walk the XML tree of children below elem, returning each in order.
"""
for child in elem.childNodes:
yield child
for elem in WalkChildren(child):
yield elem |
java | @Deprecated
public static void setIntHeader(HttpMessage message, String name, int value) {
message.headers().setInt(name, value);
} |
python | def prox_max(X, step, thresh=0):
"""Projection onto numbers below `thresh`
"""
thresh_ = _step_gamma(step, thresh)
above = X - thresh_ > 0
X[above] = thresh_
return X |
java | final public void setOffset(Integer start, Integer end) {
if ((start == null) || (end == null)) {
// do nothing
} else if (start > end) {
throw new IllegalArgumentException("Start offset after end offset");
} else {
tokenOffset = new MtasOffset(start, end);
}
} |
python | def _prepare_find(cls, *args, **kw):
"""Execute a find and return the resulting queryset using combined plain and parametric query generation.
Additionally, performs argument case normalization, refer to the `_prepare_query` method's docstring.
"""
cls, collection, query, options = cls._prepare_query(
... |
python | def _getDevMajorMinor(self, devpath):
"""Return major and minor device number for block device path devpath.
@param devpath: Full path for block device.
@return: Tuple (major, minor).
"""
fstat = os.stat(devpath)
if stat.S_ISBLK(fstat.st_mode):
... |
python | def render_none(self, context, result):
"""Render empty responses."""
context.response.body = b''
del context.response.content_length
return True |
java | public static void assertEquals(JSONArray expected, JSONArray actual, JSONCompareMode compareMode)
throws JSONException {
assertEquals("", expected, actual, compareMode);
} |
java | public ModifyVpcEndpointConnectionNotificationRequest withConnectionEvents(String... connectionEvents) {
if (this.connectionEvents == null) {
setConnectionEvents(new com.amazonaws.internal.SdkInternalList<String>(connectionEvents.length));
}
for (String ele : connectionEvents) {
... |
java | @Override
public String hget(String key, long field) {
return this.hget(key, Long.toString(field));
} |
python | def tensors_blocked_by_false(ops):
""" Follows a set of ops assuming their value is False and find blocked Switch paths.
This is used to prune away parts of the model graph that are only used during the training
phase (like dropout, batch norm, etc.).
"""
blocked = []
def recurse(op):
i... |
python | def fetch_twitter_lists_for_user_ids_generator(twitter_app_key,
twitter_app_secret,
user_id_list):
"""
Collects at most 500 Twitter lists for each user from an input list of Twitter user ids.
Inputs: - twitter_app... |
python | def timestamp_to_str(t, datetime_format=DATETIME_FORMAT, *, inverse=False):
"""
Given a POSIX timestamp (integer) ``t``,
format it as a datetime string in the given format.
If ``inverse``, then do the inverse, that is, assume ``t`` is
a datetime string in the given format and return its correspondin... |
java | public EsiVerifyResponse getVerify(String userAgent, String xUserAgent, String datasource, String token,
String authorization) throws ApiException {
ApiResponse<EsiVerifyResponse> resp = getVerifyWithHttpInfo(userAgent, xUserAgent, datasource, token,
authorization);
return re... |
python | def repr_return(func):
"""
This is a decorator to give the return value a pretty print repr
"""
def repr_return_decorator(*args, **kwargs):
ret = func(*args, **kwargs)
if isinstance(ret, basestring):
return ret
if type(ret) in repr_map:
return repr_map[t... |
java | public void logMapTaskFinished(TaskAttemptID taskAttemptId,
long finishTime,
String hostName,
String taskType,
String stateString,
Counters counter) {
... |
java | public static final KeyPressHandler getPercentKeyPressHandler() { // NOPMD it's thread save!
if (HandlerFactory.percentKeyPressHandler == null) {
synchronized (PercentKeyPressHandler.class) {
if (HandlerFactory.percentKeyPressHandler == null) {
HandlerFactory.percentKeyPressHandler = new Per... |
python | def format_heading(self, heading):
"""
This translates any heading of "options" or "Options" into
"SCons Options." Unfortunately, we have to do this here,
because those titles are hard-coded in the optparse calls.
"""
if heading == 'Options':
heading = "SCons... |
java | public boolean isDescendant(DataDescriptor other) {
if (other == null)
return false;
if (type == TYPE_INVALID || other.getType() == TYPE_INVALID)
return false;
String[] otherPath = other.getPath();
if (otherPath.length >= dataPath.length)
return fals... |
python | def download(self):
"""
MLBAM dataset download
"""
p = Pool()
p.map(self._download, self.days) |
python | def save_named_query(self, alias, querystring, afterwards=None):
"""
add an alias for a query string.
These are stored in the notmuch database and can be used as part of
more complex queries using the syntax "query:alias".
See :manpage:`notmuch-search-terms(7)` for more info.
... |
python | def endBy1(p, sep):
'''`endBy1(p, sep) parses one or more occurrences of `p`, separated and
ended by `sep`. Returns a list of values returned by `p`.'''
return separated(p, sep, 1, maxt=float('inf'), end=True) |
python | def AsDict(self, dt=True):
"""
A dict representation of this User instance.
The return value uses the same key names as the JSON representation.
Args:
dt (bool): If True, return dates as python datetime objects. If
False, return dates as ISO strings.
Re... |
python | def compose_info(root_dir, files, hash_fn, aleph_record, urn_nbn=None):
"""
Compose `info` XML file.
Info example::
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<info>
<created>2014-07-31T10:58:53</created>
<metadataversion>1.0</metadataversion>
... |
java | public final void sendCombinedMessage(Message combinedMessage) {
outValue.f1 = Either.Right(combinedMessage);
out.collect(outValue);
} |
python | def _versions_from_changelog(changelog):
"""
Return all released versions from given ``changelog``, sorted.
:param dict changelog:
A changelog dict as returned by ``releases.util.parse_changelog``.
:returns: A sorted list of `semantic_version.Version` objects.
"""
versions = [Version(x... |
java | private static void roundAndAdd(Collection<Integer> result, double value)
{
int roundedValue = (int) Math.round(value);
if (!result.contains(roundedValue))
{
result.add(roundedValue);
}
} |
java | public static String generateRandomCodeVerifier(SecureRandom entropySource, int entropyBytes) {
byte[] randomBytes = new byte[entropyBytes];
entropySource.nextBytes(randomBytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(randomBytes);
} |
java | @Override
protected void parse() {
confirmDropMessage = getBoolean(PARAM_CONFIRM_DROP_MESSAGE_KEY, false);
buttonMode = getInt(PARAM_UI_BUTTON_MODE, BUTTON_MODE_SIMPLE);
alwaysOnTop = getConfig().getBoolean(PARAM_BRK_ALWAYS_ON_TOP, null);
inScopeOnly = getBoolean(PARAM_BRK_IN_SCOPE_O... |
java | public MapBuilder<KEY, VALUE> putIfAbsent(KEY key, VALUE value) {
getMap().putIfAbsent(key, value);
return this;
} |
java | @Override
public UpdateFieldLevelEncryptionProfileResult updateFieldLevelEncryptionProfile(UpdateFieldLevelEncryptionProfileRequest request) {
request = beforeClientExecution(request);
return executeUpdateFieldLevelEncryptionProfile(request);
} |
java | public static byte[] toByteArray(final long l)
{
final byte[] bytes = new byte[8];
bytes[0] = (byte) ((l >>> 56) & 0xff);
bytes[1] = (byte) ((l >>> 48) & 0xff);
bytes[2] = (byte) ((l >>> 40) & 0xff);
bytes[3] = (byte) ((l >>> 32) & 0xff);
bytes[4] = (byte) ((l >>>... |
python | def listStoredSms(self, status=Sms.STATUS_ALL, memory=None, delete=False):
""" Returns SMS messages currently stored on the device/SIM card.
The messages are read from the memory set by the "memory" parameter.
:param status: Filter messages based on this read status; must be 0-... |
java | protected int getNextIndex(final int currentIndex) {
if (!isPaused()) {
return currentIndex + 1;
}
int ret = currentIndex;
while (isPaused()) {
sendStepPausing(ret + 1);
try {
Thread.sleep(getPauseSpan());
... |
python | def sink(wrapped):
"""Creates an SPL operator with a single input port.
A SPL operator with a single input port and no output ports.
For each tuple on the input port the decorated function
is called passing the contents of the tuple.
.. deprecated:: 1.8
Recommended to use :py:class:`@spl.f... |
python | def _uri_split(uri):
"""Splits up an URI or IRI."""
scheme, netloc, path, query, fragment = _safe_urlsplit(uri)
auth = None
port = None
if '@' in netloc:
auth, netloc = netloc.split('@', 1)
if netloc.startswith('['):
host, port_part = netloc[1:].split(']', 1)
if port_p... |
java | public void reconnect(final JobID jobId) {
Preconditions.checkNotNull(jobId, "JobID must not be null.");
final Tuple2<LeaderRetrievalService, JobManagerLeaderListener> jobLeaderService = jobLeaderServices.get(jobId);
if (jobLeaderService != null) {
jobLeaderService.f1.reconnect();
} else {
LOG.info("Can... |
java | protected void createInitialAuthenticationRequestValidationCheckAction(final Flow flow) {
val action = createActionState(flow, CasWebflowConstants.STATE_ID_INITIAL_AUTHN_REQUEST_VALIDATION_CHECK,
CasWebflowConstants.ACTION_ID_INITIAL_AUTHN_REQUEST_VALIDATION);
createTransitionForState(action... |
java | @Override
public void initializeParts() {
super.initializeParts();
node = new ListView<>();
node.getStyleClass().add("simple-listview-control");
fieldLabel = new Label(field.labelProperty().getValue());
node.setItems(field.getItems());
node.getSelectionModel().setSelectionMode(SelectionMode... |
python | def String(length=None, **kwargs):
"""A string valued property with max. `length`."""
return Property(
length=length,
types=stringy_types,
convert=to_string,
**kwargs
) |
java | @Override
public Collection<V> put(K key, Collection<V> value) {
throw new UnsupportedOperationException();
} |
java | public ResourceBundle getResourceBundle(FacesContext ctx, String name) throws FacesException, NullPointerException
{
Application application = getMyfacesApplicationInstance(ctx);
if (application != null)
{
return application.getResourceBundle(ctx, name);
}
throw n... |
java | private void overrideViolationMessageIfNecessary(List<Violation> violations) {
if (violationMessage != null && violations != null) {
for (Violation violation : violations) {
violation.setMessage(violationMessage);
}
}
} |
java | protected Double getBilinearInterpolationValue(GriddedTile griddedTile,
TImage image, Double[][] leftLastColumns, Double[][] topLeftRows,
Double[][] topRows, int y, int x, float widthRatio,
float heightRatio, float destTop, float destLeft, float srcTop,
float srcLeft) {
// Determine which source pixel to... |
java | private int getNewReconnectIvl()
{
// The new interval is the current interval + random value.
int interval = currentReconnectIvl + (Utils.randomInt() % options.reconnectIvl);
// Only change the current reconnect interval if the maximum reconnect
// interval was set and if it's ... |
python | def delete_group(self, group):
""" Group was deleted. """
try:
lgroup = self._get_group(group.name)
delete(lgroup, database=self._database)
except ObjectDoesNotExist:
# it doesn't matter if it doesn't exist
pass |
java | public <CTX> HtmlSanitizer.Policy build(
HtmlStreamEventReceiver out,
@Nullable HtmlChangeListener<? super CTX> listener,
@Nullable CTX context) {
return toFactory().apply(out, listener, context);
} |
java | public static Map<InetAddress, UUID> loadHostIds()
{
Map<InetAddress, UUID> hostIdMap = new HashMap<InetAddress, UUID>();
for (UntypedResultSet.Row row : executeInternal("SELECT peer, host_id FROM system." + PEERS_CF))
{
InetAddress peer = row.getInetAddress("peer");
... |
python | def applyTuple(self, tuple, right, env):
"""Apply a tuple to something else."""
if len(right) != 1:
raise exceptions.EvaluationError('Tuple (%r) can only be applied to one argument, got %r' % (self.left, self.right))
right = right[0]
return tuple(right) |
java | public DynamicType.Builder<T> merge(Collection<? extends ModifierContributor.ForType> modifierContributors) {
throw new UnsupportedOperationException("Cannot change modifiers of decorated type: " + instrumentedType);
} |
python | async def make_default_options_response(self) -> Response:
"""This is the default route function for OPTIONS requests."""
methods = _request_ctx_stack.top.url_adapter.allowed_methods()
return self.response_class('', headers={'Allow': ', '.join(methods)}) |
java | public long getFreeSpace() {
try {
StructStatVfs sb = Libcore.os.statvfs(path);
return sb.f_bfree * sb.f_bsize; // free block count * block size in bytes.
} catch (ErrnoException errnoException) {
return 0;
}
} |
java | @Pure
public static Element getElementFromPath(Node document, boolean caseSensitive, String... path) {
assert document != null : AssertMessages.notNullParameter(0);
return getElementFromPath(document, caseSensitive, 0, path);
} |
java | private EConvResult transConv(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags, Ptr resultPositionPtr) {
// null check
if (elements[0].lastResult == EConvResult.AfterOutput) elements[0].lastResult = EConvResult.SourceBufferEmpty;
for (int i = numTranscoders... |
java | public <A extends Annotation> A findAnnotationOnBean(Class<A> annotationType) {
return applicationContext.findAnnotationOnBean(beanName, annotationType);
} |
python | def bothify(self, text='## ??', letters=string.ascii_letters):
"""
Replaces all placeholders with random numbers and letters.
:param text: string to be parsed
:returns: string with all numerical and letter placeholders filled in
"""
return self.lexify(self.numerify(text)... |
python | def from_json_str(cls, json_str):
"""Convert json string representation into class instance.
Args:
json_str: json representation as string.
Returns:
New instance of the class with data loaded from json string.
"""
return cls.from_json(json.loads(json_str, cls=JsonDecoder)) |
python | def iteritems(self):
"""Present the email headers"""
for n,v in self.msgobj.__dict__["_headers"]:
yield n.lower(), v
return |
java | public static String getGeometryTypeNameFromConstraint(String constraint, int numericPrecision) {
int geometryTypeCode = GeometryTypeFromConstraint.geometryTypeFromConstraint(constraint, numericPrecision);
return SFSUtilities.getGeometryTypeNameFromCode(geometryTypeCode);
} |
java | @Override
public void groupingValue(String collateName) {
// collationName is ignored for now
if (groupBy == null) {
groupBy = new ArrayList<>(ARRAY_INITIAL_LENGTH);
}
groupBy.add(resolveAlias(propertyPath));
} |
java | private void checkTenantApps(Tenant tenant) {
m_logger.info(" Tenant: {}", tenant.getName());
try {
Iterator<DRow> rowIter =
DBService.instance(tenant).getAllRows(SchemaService.APPS_STORE_NAME).iterator();
if (!rowIter.hasNext()) {
m_logger... |
python | def dnld_gaf(species_txt, prt=sys.stdout, loading_bar=True):
"""Download GAF file if necessary."""
return dnld_gafs([species_txt], prt, loading_bar)[0] |
python | def parse(self, target):
""" Parse nested rulesets
and save it in cache.
"""
if isinstance(target, ContentNode):
if target.name:
self.parent = target
self.name.parse(self)
self.name += target.name
target.ruleset.... |
python | def site(self, **params):
"""Stream site
Accepted params found at:
https://dev.twitter.com/docs/api/1.1/get/site
"""
url = 'https://sitestream.twitter.com/%s/site.json' \
% self.streamer.api_version
self.streamer._request(url, params=params) |
java | public boolean userHasLock(String username) {
Objects.requireNonNull(username, Required.USERNAME.toString());
boolean lock = false;
Config config = Application.getInstance(Config.class);
Cache cache = Application.getInstance(CacheProvider.class).getCache(CacheName.AUTH);
... |
java | public TextMessageBuilder addQuickLocationReply(String locationMessage) {
if (this.quickReplies == null) {
this.quickReplies = new ArrayList<QuickReply>();
}
this.quickReplies.add(new QuickReply(locationMessage));
return this;
} |
python | def validate(self):
""" validate: Makes sure audio is valid
Args: None
Returns: boolean indicating if audio is valid
"""
from .files import AudioFile
try:
assert self.kind == content_kinds.AUDIO, "Assumption Failed: Node should be audio"
as... |
python | def _group_chunks_by_entities(self, chunks, entities):
"""Groups chunks by entities retrieved from NL API Entity Analysis.
Args:
chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed.
entities (:obj:`list` of :obj:`dict`): List of entities.
Returns:
A chunk list. (:obj:`b... |
python | def _namify_arguments(mapping):
"""
Ensure that a mapping of names to parameters has the parameters set to the
correct name.
"""
result = []
for name, parameter in mapping.iteritems():
parameter.name = name
result.append(parameter)
return result |
python | def gradings(gradingScheme):
''' Determine the list of gradings in this scheme as rendered string.
TODO: Use nice little icons instead of (p) / (f) marking.
'''
result = []
for grading in gradingScheme.gradings.all():
if grading.means_passed:
result.append(str(grading) + " (p... |
java | @Override
public Object evaluate(DeferredObject[] arguments) throws HiveException {
if ((arguments==null) || (arguments.length!=1)) {
return null;
}
BitcoinTransaction bitcoinTransaction;
if (arguments[0].get() instanceof HiveBitcoinTransaction) { // this happens if the table is in the original file format
bi... |
python | def calculate_lvgd_voltage_current_stats(nw):
"""
LV Voltage and Current Statistics for an arbitrary network
Note
----
Aggregated Load Areas are excluded.
Parameters
----------
nw: :any:`list` of NetworkDing0
The MV grid(s) to be studied
Returns
-------
pandas.Data... |
python | def _parse_custom_mpi_options(custom_mpi_options):
# type: (str) -> Tuple[argparse.Namespace, List[str]]
"""Parse custom MPI options provided by user. Known options default value will be overridden
and unknown options would be identified separately."""
parser = argparse.ArgumentParser()
parser.add_... |
python | def parabola(xy, amplitude, x0, y0, sx, sy, theta):
"""Evaluate a 2D parabola given by:
f(x,y) = f_0 - (1/2) * \delta^T * R * \Sigma * R^T * \delta
where
\delta = [(x - x_0), (y - y_0)]
and R is the matrix for a 2D rotation by angle \theta and \Sigma
is the covariance matrix:
\Sigma = [... |
java | static DateTime determineRotationPeriodAnchor(@Nullable DateTime lastAnchor, Period period) {
final Period normalized = period.normalizedStandard();
int years = normalized.getYears();
int months = normalized.getMonths();
int weeks = normalized.getWeeks();
int days = normalized.ge... |
python | def get_box_folder_location():
"""
Try to locate the Box folder.
Returns:
(str) Full path to the current Box folder
"""
box_prefs_path = ('Library/Application Support/Box/Box Sync/'
'sync_root_folder.txt')
box_home = None
box_prefs = os.path.join(os.environ['H... |
python | def inference(self, kern, X, Z, likelihood, Y, indexD, output_dim, Y_metadata=None, Lm=None, dL_dKmm=None, Kuu_sigma=None):
"""
The first phase of inference:
Compute: log-likelihood, dL_dKmm
Cached intermediate results: Kmm, KmmInv,
"""
input_dim = Z.shape[0]
u... |
python | def check_labels_file_header(filename):
"""Validate that filename corresponds to labels for the MNIST dataset."""
with tf.gfile.Open(filename, 'rb') as f:
magic = read32(f)
read32(f) # num_items, unused
if magic != 2049:
raise ValueError('Invalid magic number %d in MNIST file %s' % (magic,
... |
python | def export(self, image_path, tmptar=None):
'''export will export an image, sudo must be used.
Parameters
==========
image_path: full path to image
tmptar: if defined, use custom temporary path for tar export
'''
from spython.utils import check_install
check_install()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.