language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def _Operations(self, rule, line):
"""Operators on the data record.
Operators come in two parts and are a '.' separated pair:
Operators that effect the input line or the current state (line_op).
'Next' Get next input line and restart parsing (default).
'Continue' Keep current input... |
java | @Activate
protected void activate(ComponentContext context, Map<String, Object> props) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(this, tc, "MongoDBService activate: jndiName=" + props.get(JNDI_NAME) + ", database=" + props.get(DATABASE_NAME));
// Regist... |
python | def get_functions(self, dbName, pattern):
"""
Parameters:
- dbName
- pattern
"""
self.send_get_functions(dbName, pattern)
return self.recv_get_functions() |
java | public static Address create(Map<String, Object> params) throws EasyPostException {
return create(params, null);
} |
python | def train(self, text, className):
"""
enhances trained data using the given text and class
"""
self.data.increaseClass(className)
tokens = self.tokenizer.tokenize(text)
for token in tokens:
token = self.tokenizer.remove_stop_words(token)
token = s... |
java | @Override
public Parameter visitParameter(Context context, Parameter p) {
visitor.visitParameter(context, p);
return p;
} |
java | public static ORule.ResourceGeneric getResourceGeneric(String name)
{
String shortName = Strings.beforeFirst(name, '.');
if(Strings.isEmpty(shortName)) shortName = name;
ORule.ResourceGeneric value = ORule.ResourceGeneric.valueOf(shortName);
if(value==null) value = ORule.mapLegacyResourceToGenericResource(name... |
java | public static ntp_server[] get(nitro_service client) throws Exception
{
ntp_server resource = new ntp_server();
resource.validate("get");
return (ntp_server[]) resource.get_resources(client);
} |
python | def _zerosamestates(self, A):
"""
zeros out states that should be identical
REQUIRED ARGUMENTS
A: the matrix whose entries are to be zeroed.
"""
for pair in self.samestates:
A[pair[0], pair[1]] = 0
A[pair[1], pair[0]] = 0 |
java | @Nonnull
public ELoginResult loginUser (@Nullable final String sLoginName,
@Nullable final String sPlainTextPassword,
@Nullable final Iterable <String> aRequiredRoleIDs)
{
// Try to resolve the user
final IUser aUser = PhotonSecurityManager.g... |
python | def interface_endpoints(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>`
"""
api_version = self._get_api_version('interface_endpoints')
if api_version == ... |
java | public static Object generate(Object service, String groupName, Map<String, String> commands, String suffix) throws Exception {
// generate class with unique name
CtClass ctClass = POOL.makeClass(AbstractEquinoxCommandProvider.class.getName() + suffix);
try {
Set<String> commandHelps... |
java | public static DefaultYamlNodeFactory create(DecimalPrecision precision) {
Objects.requireNonNull(precision);
DefaultYamlNodeFactory fac = FACTORIES.get(precision);
if (fac == null) {
FACTORIES.put(precision, fac
= new DefaultYamlNodeFactory(precision));
}
... |
java | protected void addValidators() {
//Target file ComboBox
m_target.removeAllValidators();
m_target.addValidator(new TargetValidator());
for (I_CmsEditableGroupRow row : m_resourcesGroup.getRows()) {
FormLayout layout = (FormLayout)(row.getComponent());
CmsPathSele... |
python | def download(self, path, file):
"""Download remote file to disk."""
resp = self._sendRequest("GET", path)
if resp.status_code == 200:
with open(file, "wb") as f:
f.write(resp.content)
else:
raise YaDiskException(resp.status_code, resp.content) |
java | public final ListNotificationChannelDescriptorsPagedResponse listNotificationChannelDescriptors(
ProjectName name) {
ListNotificationChannelDescriptorsRequest request =
ListNotificationChannelDescriptorsRequest.newBuilder()
.setName(name == null ? null : name.toString())
.build... |
python | def copyTo(self, screen):
""" Creates a new point with the same offset on the target screen as this point has on the
current screen """
from .RegionMatching import Screen
if not isinstance(screen, Screen):
screen = RegionMatching.Screen(screen)
return screen.getTopLef... |
java | private List<Data> loadAndGet(List<Data> keys) {
try {
Map entries = mapDataStore.loadAll(keys);
return getKeyValueSequence(entries);
} catch (Throwable t) {
logger.warning("Could not load keys from map store", t);
throw ExceptionUtil.rethrow(t);
}... |
python | def create_resource(self, resource_type=None, uri=None):
'''
Convenience method for creating a new resource
Note: A Resource is instantiated, but is not yet created. Still requires resource.create().
Args:
uri (rdflib.term.URIRef, str): uri of resource to create
resource_type (NonRDFSource (Binary), B... |
python | def terminate(self):
"""Terminate all the :attr:`initialized_providers`."""
logger.debug('Terminating initialized providers')
for name in list(self.initialized_providers):
del self[name] |
java | public final Iterator<String> keyIterator() {
return new Iterator<String>() {
private final Iterator<Property> it = props.iterator();
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public S... |
java | public void createControlAdapter()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "createControlAdapter");
DestinationHandler dh = null;
try
{
ItemStream is = getItemStream();
// TODO - This method is using the wrong itemstream
... |
python | def grok_filter_name(element):
"""Extracts the name, which may be embedded, for a Jinja2
filter node"""
e_name = None
if element.name == 'default':
if isinstance(element.node, jinja2.nodes.Getattr):
e_name = element.node.node.name
else:
e_name = element.node.name
... |
java | public void union(IntArray newArray)
{
for (int i = 0; i < newArray._size; i++) {
if (! contains(newArray._data[i]))
add(newArray._data[i]);
}
} |
java | @Nullable
private String getPackageName(@NonNull ComponentName resolveActivity, @NonNull List<Intent> initialIntents) {
String packageName = resolveActivity.getPackageName();
if (packageName.equals("android")) {
//multiple activities support the intent and no default is set
i... |
python | def _set_wikidata(self):
"""
set attributes derived from Wikidata (action=wbentities)
"""
self.data['labels'] = {}
self.data['wikidata'] = {}
data = self._load_response('wikidata')
entities = data.get('entities')
item = entities.get(next(iter(entities)))
... |
java | @Override
public void create(int tileWidth, int tileHeight, int widthInTile, int heightInTile)
{
Check.superiorStrict(tileWidth, 0);
Check.superiorStrict(tileHeight, 0);
Check.superiorStrict(widthInTile, 0);
Check.superiorStrict(heightInTile, 0);
clear();
this.t... |
java | @Internal
public static Interceptor[] resolveIntroductionInterceptors(BeanContext beanContext, ExecutableMethod<?, ?> method, Interceptor... interceptors) {
instrumentAnnotationMetadata(beanContext, method);
Interceptor[] aroundInterceptors = resolveAroundInterceptors(beanContext, method, intercepto... |
java | public T intern(T o) {
WeakReference<T> ref = map.get(o);
if (ref == null) {
ref = Generics.newWeakReference(o);
map.put(o, ref);
}
// else {
// System.err.println("Found dup for " + o);
// }
return ref.get();
} |
java | public SignatureRequest getSignatureRequest(String id) throws HelloSignException {
String url = BASE_URI + SIGNATURE_REQUEST_URI + "/" + id;
return new SignatureRequest(httpClient.withAuth(auth).get(url).asJson());
} |
java | protected <V> V awaitResult(ListenableFuture<V> future, int time, TimeUnit unit) {
try {
return future.get(time, unit);
} catch (ExecutionException e) {
LOG.log(Level.WARNING, "Exception processing future: " + e.getMessage());
future.cancel(true);
return null;
} catch (InterruptedExc... |
python | def metric(self):
"""
The metric of the parameter space.
This is a Dictionary of numpy.matrix
Each entry in the dictionary is as described under evals.
Each numpy.matrix contains the metric of the parameter space in the
Lambda_i coordinate system.
"""
if s... |
python | def set_auth_service(self, auth_service: BaseAuthService):
"""
Sets the authentication service
:param auth_service: BaseAuthService Authentication service
:raises: TypeError If the auth_service object is not a subclass of rinzler.auth.BaseAuthService
:rtype: Rinzler
"""
... |
java | public Broadcast stopBroadcast(String broadcastId) throws OpenTokException {
if (StringUtils.isEmpty(broadcastId)) {
throw new InvalidArgumentException("Broadcast id is null or empty");
}
String broadcast = this.client.stopBroadcast(broadcastId);
try {
return broa... |
java | protected int[] batch(StatementHandler stmtHandler, String sql, QueryParameters[] params) throws SQLException {
Connection conn = this.transactionHandler.getConnection();
if (sql == null) {
this.transactionHandler.rollback();
this.transactionHandler.closeConnection();
... |
python | def _init_catalog(self, proxy=None, runtime=None):
"""Initialize this session as an OsidCatalog based session."""
self._init_proxy_and_runtime(proxy, runtime)
osid_name = self._session_namespace.split('.')[0]
try:
config = self._runtime.get_configuration()
paramet... |
java | protected void errorIfStatusEqualTo(ClientResponse response,
ClientResponse.Status... status) throws ClientException {
errorIf(response, status, true);
} |
java | public boolean matches(GHCommitPointer commit) {
final GHUser user;
try {
user = commit.getUser();
} catch (IOException ex) {
LOGGER.debug("Failed to extract user from commit " + commit, ex);
return false;
}
return userName.equals(user.getLogi... |
python | def filters(im, detail=False, sharpen=False, **kwargs):
"""
Pass the source image through post-processing filters.
sharpen
Sharpen the thumbnail image (using the PIL sharpen filter)
detail
Add detail to the image, like a mild *sharpen* (using the PIL
``detail`` filter).
""... |
python | def composition(mol):
"""Molecular composition in dict format
(ex. Glucose {'C': 6, 'H': 12, 'O': 6}).
"""
mol.require("Valence")
c = Counter()
for _, a in mol.atoms_iter():
c += a.composition()
return c |
python | def un_comment(s, comment='#', strip=True):
"""Uncomment a string or list of strings
truncate s at first occurrence of a non-escaped comment character
remove escapes from escaped comment characters
Parameters:
s - string to uncomment
comment - comment character (de... |
python | def bfx(value, msb, lsb):
"""! @brief Extract a value from a bitfield."""
mask = bitmask((msb, lsb))
return (value & mask) >> lsb |
java | public void writeComment(final String comment) throws IOException {
lineNumber++; // we're not catering for embedded newlines (must be a single-line comment)
if( comment == null ) {
throw new NullPointerException(String.format("comment to write should not be null on line %d", lineNumber));
}
writer.... |
java | public Observable<Page<LabAccountInner>> listByResourceGroupNextAsync(final String nextPageLink) {
return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<LabAccountInner>>, Page<LabAccountInner>>() {
@Override
public P... |
python | def validate(self):
""" Parse XML data """
if not self.id or len(self.id) == 0:
raise ValidationError('No <id> tag')
if not self.name or len(self.name) == 0:
raise ValidationError('No <name> tag')
if not self.summary or len(self.summary) == 0:
raise Va... |
java | static Node getBestLValueRoot(@Nullable Node lValue) {
if (lValue == null) {
return null;
}
switch (lValue.getToken()) {
case STRING_KEY:
// NOTE: beware of getBestLValue returning null (or be null-permissive?)
return getBestLValueRoot(NodeUtil.getBestLValue(lValue.getParent()));... |
java | protected void reconnect() {
disconnect().then(ok -> {
logger.info("Trying to reconnect...");
scheduler.schedule(this::connect, 5, TimeUnit.SECONDS);
}).catchError(cause -> {
logger.warn("Unable to disconnect from Redis server!", cause);
scheduler.schedule(this::connect, 5, TimeUnit.SECONDS);
}... |
java | static AjaxOperation registerContainer(final String triggerId, final String containerId,
final List<String> containerContentIds) {
AjaxOperation operation = new AjaxOperation(triggerId, containerContentIds);
operation.setTargetContainerId(containerId);
operation.setAction(AjaxOperation.AjaxAction.REPLACE_CONTE... |
python | def remove_obsolete_folders(states, path):
"""Removes obsolete state machine folders
This function removes all folders in the file system folder `path` that do not belong to the states given by
`states`.
:param list states: the states that should reside in this very folder
:param str path: the... |
java | public void process(Hashtable<String, CodeSigner[]> signers,
List manifestDigests)
throws IOException, SignatureException, NoSuchAlgorithmException,
JarException, CertificateException
{
// calls Signature.getInstance() and MessageDigest.getInstance()
// need to use lo... |
java | public ArrayList<OvhBill> project_serviceName_bill_GET(String serviceName, Date from, Date to) throws IOException {
String qPath = "/cloud/project/{serviceName}/bill";
StringBuilder sb = path(qPath, serviceName);
query(sb, "from", from);
query(sb, "to", to);
String resp = exec(qPath, "GET", sb.toString(), nul... |
python | def write_index_labels(self, targets, output_path):
"""Write the mappings between vertex indices and labels(target vs. not) to a file.
:param list targets: List of known targets.
:param str output_path: Path to the output file.
"""
label_mappings = self.get_index_labels(targets)... |
java | public void setBinaryMediaTypes(List<MediaType> binaryMediaTypes) {
requestMessageConverters.stream()
.filter(converter -> converter instanceof ByteArrayHttpMessageConverter)
.map(ByteArrayHttpMessageConverter.class::cast)
... |
python | def run_benchmarks(dir, models, wav, alphabet, lm_binary=None, trie=None, iters=-1):
r'''
Core of the running of the benchmarks. We will run on all of models, against
the WAV file provided as wav, and the provided alphabet.
'''
assert_valid_dir(dir)
inference_times = [ ]
for model in mode... |
java | public HttpClient get() {
final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager();
cm.setMaxTotal(nrOfThreads);
cm.setDefaultMaxPerRoute(maxToRoute);
final DefaultHttpClient client = HTTPSFaker.getClientThatAllowAnyHTTPS(cm);
client.getParams().setParameter("http.socket.timeout", s... |
java | public Map<?, ?> getByContainer() {
if (m_byContainer == null) {
m_byContainer = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {
public Object transform(Object arg0) {
String key = (String)arg0;
CmsContainerBean container = m_... |
python | def update_grammar_with_untyped_entities(grammar_dictionary: Dict[str, List[str]]) -> None:
"""
Variables can be treated as numbers or strings if their type can be inferred -
however, that can be difficult, so instead, we can just treat them all as values
and be a bit looser on the typing we allow in ou... |
python | def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render the HTML for the browsable API representation.
"""
self.accepted_media_type = accepted_media_type or ''
self.renderer_context = renderer_context or {}
template = loader.get_template(self.... |
java | public Map<String,String> getResourceBundleMap() {
if (null == resourceBundleMap) {
// See if there is a ResourceBundle under the FQCN for this class
String className = this.getClass().getName();
Locale currentLocale = null;
FacesContext context = null;
... |
python | def _getBusVoltageLambdaSensor(self):
""" Returns an array of length nb where each value is the sum of the
Lagrangian multipliers on the upper and the negative of the Lagrangian
multipliers on the lower voltage limits. """
muVmin = array([b.mu_vmin for b in self.market.case.connected_bus... |
java | public String toURLQueryString() {
StringJoiner joiner = new StringJoiner("&");
if (releaseIdFilter.getGroupId() != null) {
joiner.add("groupId=" + releaseIdFilter.getGroupId());
}
if (releaseIdFilter.getArtifactId() != null) {
joiner.add("artifactId=" + releaseId... |
python | def plot_ellipsoid(hessian, center, lattice=None, rescale=1.0, ax=None,
coords_are_cartesian=False, arrows=False, **kwargs):
"""
Plots a 3D ellipsoid rappresenting the Hessian matrix in input.
Useful to get a graphical visualization of the effective mass
of a band in a single k-point.... |
python | def get_vault_ids_by_authorization(self, authorization_id):
"""Gets the list of ``Vault`` ``Ids`` mapped to an ``Authorization``.
arg: authorization_id (osid.id.Id): ``Id`` of an
``Authorization``
return: (osid.id.IdList) - list of vault ``Ids``
raise: NotFound - ``... |
java | private static Raster getRaster(final RenderedImage image) {
return image instanceof BufferedImage
? ((BufferedImage) image).getRaster()
: image.getNumXTiles() == 1 && image.getNumYTiles() == 1
? image.getTile(0, 0)
: image.getData();
} |
java | @Override
public int getLocationY() throws WidgetException {
try {
Point p = findElement().getLocation();
return p.getY();
} catch (Exception e) {
throw new WidgetException("Error while fetching Y location", locator, e);
}
} |
python | def dropDuplicates(self, subset=None):
"""Return a new :class:`DataFrame` with duplicate rows removed,
optionally only considering certain columns.
For a static batch :class:`DataFrame`, it just drops duplicate rows. For a streaming
:class:`DataFrame`, it will keep all data across trigg... |
python | def find_position(edges, prow, bstart, bend, total=5):
"""Find a EMIR CSU bar position in a edge image.
Parameters
==========
edges; ndarray,
a 2d image with 1 where is a border, 0 otherwise
prow: int,
reference 'row' of the bars
bstart: int,
minimum 'x' position of a ba... |
python | def fill(self, color):
"""Colors all pixels the given ***color***."""
auto_write = self.auto_write
self.auto_write = False
for i, _ in enumerate(self):
self[i] = color
if auto_write:
self.show()
self.auto_write = auto_write |
java | public final FieldTextInfo createFieldInfo(@NotNull final Field field, @NotNull final Locale locale,
@NotNull final Class<? extends Annotation> annotationClasz) {
Contract.requireArgNotNull("field", field);
Contract.requireArgNotNull("locale", locale);
Contract.requireArgNotNul... |
python | def getImage(path, dockerfile, tag):
'''Check if an image with a given tag exists. If not, build an image from
using a given dockerfile in a given path, tagging it with a given tag.
No extra side effects. Handles and reraises BuildError, TypeError, and
APIError exceptions.
'''
image = getImageBy... |
java | @Override
public void setStyleName(String styleName) {
super.setStyleName(styleName);
memberLayout.setStyleName(styleName + "Body");
titleLabel.setStyleName(styleName + "Title");
buttonBaseStyle = styleName.substring(0, styleName.length() - 5) + "Button";
for (RibbonColumn column : columns) {
column.setBu... |
python | def _add_flaky_report(self, stream):
"""
Baseclass override. Write details about flaky tests to the test report.
:param stream:
The test stream to which the report can be written.
:type stream:
`file`
"""
value = self._stream.getvalue()
#... |
python | def make_multisig_segwit_wallet( m, n ):
"""
Create a bundle of information
that can be used to generate an
m-of-n multisig witness script.
"""
pks = []
for i in xrange(0, n):
pk = BitcoinPrivateKey(compressed=True).to_wif()
pks.append(pk)
return make_multisig_segwit_inf... |
python | def get_rotation_and_scale(header, skew_threshold=0.001):
"""Calculate rotation and CDELT."""
((xrot, yrot),
(cdelt1, cdelt2)) = get_xy_rotation_and_scale(header)
if math.fabs(xrot) - math.fabs(yrot) > skew_threshold:
raise ValueError("Skew detected: xrot=%.4f yrot=%.4f" % (
xrot, ... |
python | def prune_cached(values):
"""Remove the items that have already been cached."""
import os
config_path = os.path.expanduser('~/.config/blockade')
file_path = os.path.join(config_path, 'cache.txt')
if not os.path.isfile(file_path):
return values
cached = [x.strip() for x in open(file_path,... |
python | def _notify_load_dll(self, event):
"""
Notify the load of a new module.
@warning: This method is meant to be used internally by the debugger.
@type event: L{LoadDLLEvent}
@param event: Load DLL event.
@rtype: bool
@return: C{True} to call the user-defined han... |
java | private void finishKbMode(boolean updateDisplays) {
mInKbMode = false;
if (!mTypedTimes.isEmpty()) {
int values[] = getEnteredTime(null);
mTimePicker.setTime(values[0], values[1]);
if (!mIs24HourMode) {
mTimePicker.setAmOrPm(values[2]);
}
... |
java | public void addListener(ValidationObject object, String name, SetterListener listener) {
m_validationEngine.addListener(object, name, this, listener);
} |
python | def rel_argmax(rel_probs, length, ensure_tree=True):
"""Fix the relation prediction by heuristic rules
Parameters
----------
rel_probs : NDArray
seq_len x rel_size
length :
real sentence length
ensure_tree :
whether to apply rules
Returns
-------
rel_preds : ... |
python | def create_integration_alert_and_call_send(alert, configured_integration):
"""Create an IntegrationAlert object and send it to Integration."""
integration_alert = IntegrationAlert(
alert=alert,
configured_integration=configured_integration,
status=IntegrationAlertStatuses.PENDING.name,
... |
java | public void setXPOS0(Integer newXPOS0) {
Integer oldXPOS0 = xpos0;
xpos0 = newXPOS0;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.GBOX__XPOS0, oldXPOS0, xpos0));
} |
python | def trim_docstring(docstring):
"""Taken from http://www.python.org/dev/peps/pep-0257/"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentatio... |
java | public static byte[] readBytesFromStream(InputStream source, int bufferSize) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
copyContentIntoOutputStream(source, buffer, bufferSize, true);
return buffer.toByteArray();
} |
java | public final SrvNumberToString lazyGetSrvNumberToString() throws Exception {
String beanName = getSrvNumberToStringName();
SrvNumberToString srvDate = (SrvNumberToString) this.beansMap.get(beanName);
if (srvDate == null) {
srvDate = new SrvNumberToString();
this.beansMap.put(beanName, srvDate);
... |
java | public boolean declaresInterface(ClassNode classNode) {
ClassNode[] interfaces = redirect().getInterfaces();
for (ClassNode cn : interfaces) {
if (cn.equals(classNode)) return true;
}
for (ClassNode cn : interfaces) {
if (cn.declaresInterface(classNode)) return tr... |
python | def update(self, query, attributes, upsert=False):
"""
Updates data in the table.
:Parameters:
- query(dict), specify the WHERE clause
- attributes(dict), specify the SET clause
- upsert: boolean. If True, then when there's no row matches the query, insert the ... |
python | def matches(self, verb, params):
""" Test if the method matches the provided set of arguments
:param verb: HTTP verb. Uppercase
:type verb: str
:param params: Existing route parameters
:type params: set
:returns: Whether this view matches
:rtype: bool
"""... |
python | def possible_import_patterns(modname):
"""
does not support from x import *
does not support from x import z, y
Example:
>>> # DISABLE_DOCTEST
>>> import utool as ut
>>> modname = 'package.submod.submod2.module'
>>> result = ut.repr3(ut.possible_import_patterns(modname))... |
python | def _upload(self, project_id, updating, file_path, language_code=None,
overwrite=False, sync_terms=False, tags=None, fuzzy_trigger=None):
"""
Internal: updates terms / translations
File uploads are limited to one every 30 seconds
"""
options = [
self.... |
python | def cached(f):
"""Decorator for functions evaluated only once."""
def memoized(*args, **kwargs):
if hasattr(memoized, '__cache__'):
return memoized.__cache__
result = f(*args, **kwargs)
memoized.__cache__ = result
return result
return memoized |
python | def _nested_fcn(f: Callable, filters: List):
""" Distribute binary function f across list L
:param f: Binary function
:param filters: function arguments
:return: chain of binary filters
"""
return None if len(filters) == 0 \
else filters[0] if len(filters) ==... |
java | public void setFile(String file) {
if (file != null) {
m_file = file.toLowerCase();
} else {
m_file = null;
}
} |
java | public ApiResponse<ApiSuccessResponse> getStandardResponseFavoritesWithHttpInfo(GetFavoritesData getFavoritesData) throws ApiException {
com.squareup.okhttp.Call call = getStandardResponseFavoritesValidateBeforeCall(getFavoritesData, null, null);
Type localVarReturnType = new TypeToken<ApiSuccessRespons... |
python | def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb |
java | public static void sort(float[] floatArray) {
boolean swapped = true;
while(swapped) {
swapped = false;
for(int i = 0; i < (floatArray.length - 1 ); i++) {
if(floatArray[i] > floatArray[i + 1]) {
TrivialSwap.swap(floatArra... |
python | def _add_metadata_as_attrs(data, units, description, dtype_out_vert):
"""Add metadata attributes to Dataset or DataArray"""
if isinstance(data, xr.DataArray):
return _add_metadata_as_attrs_da(data, units, description,
dtype_out_vert)
else:
for name, a... |
python | def dump_session_params(path):
"""
Dump value of all TRAINABLE + MODEL variables to a dict, and save as
npz format (loadable by :func:`sessinit.get_model_loader`).
Args:
path(str): the file name to save the parameters. Must ends with npz.
"""
# save variables that are GLOBAL, and either... |
python | def json_2_location(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 Location object
"""
LOGGER.debug("Location.json_2_location")
return Location(locid=json_obj['loca... |
java | @Override
public PendingTaskCount countPendingDecisionTasks(CountPendingDecisionTasksRequest request) {
request = beforeClientExecution(request);
return executeCountPendingDecisionTasks(request);
} |
java | private boolean hasOperationOfType(SQLiteDatabaseSchema schema, MethodSpec.Builder methodBuilder, JQLType jqlType) {
boolean hasOperation = false;
for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {
if (daoDefinition.getElement().getAnnotation(BindContentProviderPath.class) == null)
continue;... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.