language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public Map<String, Val> nextMap(String expectedName) throws IOException {
boolean ignoreObject = peek() != JsonTokenType.BEGIN_OBJECT && StringUtils.isNullOrBlank(expectedName);
if (!ignoreObject) beginObject(expectedName);
Map<String, Val> map = new HashMap<>();
while (peek() != JsonTokenType.E... |
python | def get_docs(r_session, url, encoder=None, headers=None, **params):
"""
Provides a helper for functions that require GET or POST requests
with a JSON, text, or raw response containing documents.
:param r_session: Authentication session from the client
:param str url: URL containing the endpoint
... |
java | public java.lang.String getProvider() {
java.lang.Object ref = provider_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
provid... |
java | protected static void notifyListener(
EventExecutor eventExecutor, final Future<?> future, final GenericFutureListener<?> listener) {
checkNotNull(eventExecutor, "eventExecutor");
checkNotNull(future, "future");
checkNotNull(listener, "listener");
notifyListenerWithStackOverF... |
python | def _process_query(self, query):
"""Takes a key/val pair and returns the Elasticsearch code for it"""
key, val = query
field_name, field_action = split_field_action(key)
# Boost by name__action overrides boost by name.
boost = self.field_boosts.get(key)
if boost is None:... |
java | public static String encodeEncodedWord(String text, Usage usage) {
return encodeEncodedWord(text, usage, 0, null, null);
} |
python | def diff_compute(self, text1, text2, checklines, deadline):
"""Find the differences between two texts. Assumes that the texts do not
have any common prefix or suffix.
Args:
text1: Old string to be diffed.
text2: New string to be diffed.
checklines: Speedup flag. If false, then don't r... |
java | @Override
protected String getServiceName(final String methodName) {
if (methodName != null) {
int ndx = methodName.indexOf(this.separator);
if (ndx > 0) {
return methodName.substring(0, ndx);
}
}
return methodName;
} |
java | public DateTime withDate(LocalDate date) {
return withDate(
date.getYear(), date.getMonthOfYear(), date.getDayOfMonth());
} |
python | def response(self, status, content_type, content, headers=None):
"""
Send an HTTP response
"""
assert not isinstance(content, (str, bytes)), 'response content cannot be of type str or bytes'
response_headers = [('Content-Type', content_type)]
if headers:
resp... |
java | public static void visitDescendants(Component component, Predicate<Component> handler) {
List<Component> stack = Lists.newArrayList();
stack.add(component);
while (!stack.isEmpty()) {
Component currentComponent = stack.get(stack.size() - 1);
stack.remove(stack.size() - 1... |
python | def address(self):
"The address in big-endian"
_ = struct.pack('L', self.address_num)
return struct.unpack('!L', _)[0] |
java | @Override
public void onFailure(final Throwable caught) {
context.setError(caught);
onError(caught);
abort();
} |
java | public void noChunks() throws MalformedURLException {
URL url = null;
InputStream stream = null;
File file = null;
// tag::no-chunks[]
ok(new RenderableFile(file, false));
ok(new RenderableURL(url, false));
ok(new RenderableStream(stream, false));
// end:... |
python | def sqs(self):
"""
:rtype: SQSConnection
"""
if self.__sqs is None:
self.__sqs = self.__aws_connect(sqs)
return self.__sqs |
java | public List<String> getCustomAttributes() throws OAuthSystemException, OAuthProblemException, URISyntaxException {
cleanError();
prepareToken();
URIBuilder url = new URIBuilder(settings.getURL(Constants.GET_CUSTOM_ATTRIBUTES_URL));
OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient();
... |
java | public static SSLContext sslContext(AbstractConfig config, String key) {
final String trustManagerFactoryType = config.getString(key);
try {
return SSLContext.getInstance(trustManagerFactoryType);
} catch (NoSuchAlgorithmException e) {
ConfigException exception = new ConfigException(
k... |
python | def operator_is(u):
"""operator_is operator."""
global _aux
if np.ndim(u) == 2:
P = _P2
elif np.ndim(u) == 3:
P = _P3
else:
raise ValueError("u has an invalid number of dimensions "
"(should be 2 or 3)")
if u.shape != _aux.shape[1:]:
... |
java | public Map<String, String> pappayapplyBuild() {
Map<String, String> map = new HashMap<String, String>();
map.put("appid", getAppId());
map.put("mch_id", getMchId());
map.put("nonce_str", getNonceStr());
map.put("body", getBody());
map.put("attach", getAttach());
map.put("out_trade_no", getOutTradeNo());
... |
java | private HashMap[] getChainCache() {
HashMap[] _chainCache=new HashMap[Dispatcher.__ERROR+1];
_chainCache[Dispatcher.__REQUEST]=new HashMap();
_chainCache[Dispatcher.__FORWARD]=new HashMap();
_chainCache[Dispatcher.__INCLUDE]=new HashMap();
_chainCache[Dispatcher.__ERROR]=new Has... |
java | @Override
@Deprecated
public void setImageURI(Uri uri) {
init(getContext());
mDraweeHolder.setController(null);
super.setImageURI(uri);
} |
java | public static boolean isValid(
int yearOfWeekdate,
int weekOfYear
) {
if ((yearOfWeekdate < GregorianMath.MIN_YEAR) || (yearOfWeekdate > GregorianMath.MAX_YEAR)) {
return false;
}
return (weekOfYear >= 1) && (weekOfYear <= maximumOfWeek(yearOfWeekdate));
} |
java | @Override
public final void dropTable(ClusterName targetCluster, TableName name) throws UnsupportedException,
ExecutionException {
try {
connectionHandler.startJob(targetCluster.getName());
if (logger.isDebugEnabled()) {
logger.debug("Dropping table [" ... |
python | def set_auth_traps_enabled(status=True):
'''
Manage the sending of authentication traps.
Args:
status (bool): True to enable traps. False to disable.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' win_snmp.set_auth_traps... |
python | def abs_path(rel_path):
"""Convert a path that is relative to the module from which this function is called,
to an absolute path.
Args:
rel_path: str
Path relative to the location of the module file from which this function is called.
Returns:
str : Absolute path to the location ... |
java | public static String fromHex(String string, int minLength, Pattern separator) {
StringBuilder buffer = new StringBuilder();
String[] parts = separator.split(string);
for (String part : parts) {
if (part.length() < minLength) {
throw new IllegalArgumentException("code ... |
java | public Observable<ServiceResponse<Page<IdentifierInner>>> listSiteIdentifiersAssignedToHostNameSinglePageAsync() {
if (this.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.subscriptionId() is required and cannot be null.");
}
if (this.apiVersion() == nu... |
python | def claim_token(self, **params):
"""Claim current token by POSTing 'login' and 'password'.
User's `Authorization` header value is returned in `WWW-Authenticate`
header.
"""
self._json_params.update(params)
success, self.user = self.Model.authenticate_by_password(
... |
java | @Execute
public void process() throws Exception {
if (!concatOr(outTca == null, doReset)) {
return;
}
checkNull(inPit, inFlow);
HashMap<String, Double> regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inPit);
cols = regionMap.get(CoverageUtilities.COL... |
python | def export(self, filepath, encoding="utf-8", gzipped=True):
""" Export the word frequency list for import in the future
Args:
filepath (str): The filepath to the exported dictionary
encoding (str): The encoding of the resulting output
gzipped (bool):... |
java | public static String getMultiBlockJmolString(MultipleAlignment multAln,
List<Atom[]> transformedAtoms, ColorBrewer colorPalette,
boolean colorByBlocks) {
StringWriter jmol = new StringWriter();
jmol.append(DEFAULT_SCRIPT);
jmol.append("select *; color lightgrey; backbone 0.1; ");
int blockNum = multAln.... |
java | @SuppressWarnings("rawtypes")
private static Class<?> getRawClass(Type type) {
if (type instanceof Class) {
return (Class<?>) type;
}
if (type instanceof TypeVariable) {
return getRawClass(((TypeVariable) type).getBounds()[0]);
}
if (type instanceof Pa... |
java | @Override
public int nextTag() throws KriptonRuntimeException, IOException {
next();
if (type == TEXT && isWhitespace) {
next();
}
if (type != END_TAG && type != START_TAG) {
throw new KriptonRuntimeException("unexpected type", true, this.getLineNumber(), this.getColumnNumber(), getPositionDescription()... |
python | def _persist_settings(config_manager):
"""
Write the settings, including the persistent global script Store.
The Store instance might contain arbitrary user data, like function objects, OpenCL contexts, or whatever other
non-serializable objects, both as keys or values.
Try to serialize the data, an... |
python | def stream_list(self, id, listener, run_async=False, timeout=__DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=__DEFAULT_STREAM_RECONNECT_WAIT_SEC):
"""
Stream events for the current user, restricted to accounts on the given
list.
"""
id = self.__unpack_... |
python | def add_policy(self, name, policy_type, cooldown, change=None,
is_percent=False, desired_capacity=None, args=None):
"""
Adds a policy with the given values to this scaling group. The
'change' parameter is treated as an absolute amount, unless
'is_percent' is True, in which ca... |
python | def _set_option_by_index(self, index):
"""
Sets a single option in the Combo by its index, returning True if it was able too.
"""
if index < len(self._options):
self._selected.set(self._options[index])
return True
else:
return False |
java | @SneakyThrows
public Collection<GitObject> getObjectsInRepository(final TreeFilter filter) {
val repository = this.gitInstance.getRepository();
val head = repository.resolve(Constants.HEAD);
try (val walk = new RevWalk(repository)) {
val commit = walk.parseCommit(head);
... |
python | def lf_overlaps(L, normalize_by_coverage=False):
"""Return the **fraction of items each LF labels that are also labeled by at
least one other LF.**
Note that the maximum possible overlap fraction for an LF is the LF's
coverage, unless `normalize_by_coverage=True`, in which case it is 1.
Args:
... |
java | public UIDMeta parseUidMetaV1() {
final String json = query.getContent();
if (json == null || json.isEmpty()) {
throw new BadRequestException(HttpResponseStatus.BAD_REQUEST,
"Missing message content",
"Supply valid JSON formatted data in the body of your request");
}
try {
... |
python | def to_xyz100(self, data, description):
"""Input: J or Q; C, M or s; H or h
"""
# Steps 1-5
rgb_ = compute_to(data, description, self)
# Step 6: Calculate RC, GC and BC
# rgb_c = dot(self.M_cat02, solve(self.M_hpe, rgb_))
#
# Step 7: Calculate R, G and B
... |
python | def __select_text_under_cursor_blocks(self, cursor):
"""
Selects the document text under cursor blocks.
:param cursor: Cursor.
:type cursor: QTextCursor
"""
start_block = self.document().findBlock(cursor.selectionStart()).firstLineNumber()
end_block = self.docum... |
python | async def _on_message(self, channel, body, envelope, properties) -> None:
"""
Fires up when message is received by this consumer.
:param channel: Channel, through which message is received
:param body: Body of the message (serialized).
:param envelope: Envelope object with messa... |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
if hasattr(self, 'part_of_speech') and self.part_of_speech is not None:
_dict['part_of_speech'] = s... |
java | protected void setAutocomplete(final String autocompleteValue) {
final String newValue = Util.empty(autocompleteValue) ? null : autocompleteValue;
if (!Util.equals(newValue, getAutocomplete())) {
getOrCreateComponentModel().autocomplete = newValue;
}
} |
java | public void dump_disk_memory(Writer out)
throws IOException
{
long block_ptr;
long cache_end;
long magic;
int size;
long tail;
out.write("Information stored on disk\n");
seek(STARTOFDATA_LOCATION);
magic = readLong();
out.write("File magi... |
java | public static String toPrettyJson(Object object){
try {
return getMapper().writerWithDefaultPrettyPrinter().writeValueAsString(object);
} catch (Exception e) {
throw new RuntimeException(e);
}
} |
java | public static <T, ID> RuntimeExceptionDao<T, ID> createDao(ConnectionSource connectionSource, Class<T> clazz)
throws SQLException {
@SuppressWarnings("unchecked")
Dao<T, ID> castDao = (Dao<T, ID>) DaoManager.createDao(connectionSource, clazz);
return new RuntimeExceptionDao<T, ID>(castDao);
} |
python | def loop(server, test_loop=None):
"""Run the main loop
server is a limbo Server object
test_loop, if present, is a number of times to run the loop
"""
try:
loops_without_activity = 0
while test_loop is None or test_loop > 0:
start = time.time()
loops_without_... |
python | def env_float(name: str, required: bool=False, default: Union[Type[empty], float]=empty) -> float:
"""Pulls an environment variable out of the environment and casts it to an
float. If the name is not present in the environment and no default is
specified then a ``ValueError`` will be raised. Similarly, if t... |
python | def from_domain(cls, domain, *args, **kwargs):
"""
Try to download the hive file from the domain using the defined
beekeeper spec of domain/api/hive.json.
"""
version = kwargs.pop('version', None)
require = kwargs.pop('require_https', False)
return cls(Hive.from_d... |
python | def weld_element_wise_op(array, weld_type, scalar, operation):
"""Applies operation to each element in the array with scalar.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of each element in the input array.
scalar : {int, float... |
java | private static Class<?> loadClass(String name) throws ClassNotFoundException {
ClassLoader loader =
firstNonNull(
currentThread().getContextClassLoader(), StackTraceCleaner.class.getClassLoader());
return loader.loadClass(name);
} |
python | def set_volumes_tags(tag_maps, authoritative=False, dry_run=False,
region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
tag_maps (list)
List of dicts of filters and tags, where 'filters' is a dict suitable for passing to the
'filters' argumen... |
python | def regex_parse(regex, text, fromstart=True):
r"""
regex_parse
Args:
regex (str):
text (str):
fromstart (bool):
Returns:
dict or None:
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_regex import * # NOQA
>>> regex = r'(?P<string>\'[^\']... |
java | public Collection<String> getNames(Collection<P> properties)
{
Preconditions.checkNotNull(properties);
return Collections2.transform(properties, new Function<P, String>()
{
@Override
public String apply(P property)
{
return converter.convert(property);
}
});
} |
python | def get_list_filter(self, request):
"""
Adds the period filter to the filters list.
:param request: Current request.
:return: Iterable of filters.
"""
original = super(TrackedLiveAdmin, self).get_list_filter(request)
return original + type(original)([PeriodFilter... |
java | public Observable<BlobContainerInner> createAsync(String resourceGroupName, String accountName, String containerName) {
return createWithServiceResponseAsync(resourceGroupName, accountName, containerName).map(new Func1<ServiceResponse<BlobContainerInner>, BlobContainerInner>() {
@Override
... |
python | def ticket_form_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/ticket_forms#delete-ticket-form"
api_path = "/api/v2/ticket_forms/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) |
java | public String createEvent(Event event)
throws ExecutionException, InterruptedException, IOException {
return createEvent(createEventAsFuture(event));
} |
python | def RandomShuffle(a, seed):
"""
Random uniform op.
"""
if seed:
np.random.seed(seed)
r = a.copy()
np.random.shuffle(r)
return r, |
java | public static String threadIdToString(int threadId) {
StringBuffer buffer = new StringBuffer(8);
// pad the HexString ThreadId so that it is always 8 characters long.
for (int shift = 7; shift >= 0; shift--) {
buffer.append(hexChars[(threadId >> (shift << 2)) & 0xF]);
}
... |
python | def pwm_max_score(self):
"""Return the maximum PWM score.
Returns
-------
score : float
Maximum PWM score.
"""
if self.max_score is None:
score = 0
for row in self.pwm:
score += log(max(row) / 0.25 + 0.01)
s... |
java | public Object doGetData()
{
String data = (String)super.doGetData();
FileListener listener = this.getRecord().getListener(PropertiesStringFileListener.class);
if (this.getComponent(0) == null) // Don't convert if this is linked to a screen
if (enableConversion)
... |
python | def init_device(self):
"""
Initializes the device with the proper keymaps and name
"""
try:
product_id = int(self._send_command('_d2', 1))
except ValueError:
product_id = self._send_command('_d2', 1)
if product_id == 0:
self._impl = Re... |
java | public synchronized ConnectionWrapper checkOut() throws SQLException {
final Transaction tx = getTransaction();
if (tx == null && isSuppressLocalTx()) { // rare case
throw new LjtIllegalStateException("Not begun transaction. (not allowed local transaction)");
}
ConnectionWrap... |
java | private MBeanOperationInfo[] getOperationInfo() {
final List<MBeanOperationInfo> infoList = new ArrayList<>();
if (type != null) {
ReflectionUtils.doWithMethods(type, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws Il... |
python | def choicebox(msg="Pick something."
, title=" "
, choices=()
):
"""
Present the user with a list of choices.
return the choice that he selects.
return None if he cancels the selection selection.
@arg msg: the msg to be displayed.
@arg title: the window title
@arg choices: a list... |
python | def get_editor_buffer_for_location(self, location):
"""
Return the `EditorBuffer` for this location.
When this file was not yet loaded, return None
"""
for eb in self.editor_buffers:
if eb.location == location:
return eb |
python | def child_task(self):
'''child process - this holds all the GUI elements'''
from MAVProxy.modules.lib import mp_util
import wx_processguard
from wx_loader import wx
from wxsettings_ui import SettingsDlg
mp_util.child_close_fds()
app = wx.App(False)
... |
python | def check_blank_before_after_class(self, class_, docstring):
"""D20{3,4}: Class docstring should have 1 blank line around them.
Insert a blank line before and after all docstrings (one-line or
multi-line) that document a class -- generally speaking, the class's
methods are separated fro... |
python | def get_projections_by_branches(bs, selection, normalise=None):
"""Returns orbital projections for each branch in a band structure.
Args:
bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`):
The band structure.
selection (list): A list of :obj:`tuple` or :... |
java | public String buildWhere(String field, ColumnValue value) {
String where;
if (value != null) {
if (value.getValue() != null && value.getTolerance() != null) {
if (!(value.getValue() instanceof Number)) {
throw new GeoPackageException(
"Field value is not a number and can not use a tolerance, Fiel... |
python | def extract_kwargs(docstring):
"""Extract keyword argument documentation from a function's docstring.
Parameters
----------
docstring: str
The docstring to extract keyword arguments from.
Returns
-------
list of (str, str, list str)
str
The name of the keyword argument... |
python | def import_or_die(module_name, entrypoint_names):
'''
Import user code; return reference to usercode function.
(str) -> function reference
'''
log_debug("Importing {}".format(module_name))
module_name = os.path.abspath(module_name)
if module_name.endswith('.py'):
module_name,ext = o... |
python | def paths_by_depth(paths):
"""Sort list of paths by number of directories in it
.. todo::
check if a final '/' is consistently given or ommitted.
:param iterable paths: iterable containing paths (str)
:rtype: list
"""
return sorted(
paths,
key=lambda path: path... |
python | def get_vartype(data):
"""Infer the type of a variable (technically a Series).
The types supported are split in standard types and special types.
Standard types:
* Categorical (`TYPE_CAT`): the default type if no other one can be determined
* Numerical (`TYPE_NUM`): if it contains numbers
... |
python | def json_output(self):
"""Toggles json output of libiperf
Turning this off will output the iperf3 instance results to
stdout/stderr
:rtype: bool
"""
enabled = self.lib.iperf_get_test_json_output(self._test)
if enabled:
self._json_output = True
... |
python | def execution_context_from_async(async):
"""Instantiate a new _ExecutionContext and store a reference to it in the
global async context to make later retrieval easier.
"""
local_context = _local.get_local_context()
if local_context._executing_async_context:
raise errors.ContextExistsError
... |
python | def _access_token(self, request: Request=None, page_id: Text=''):
"""
Guess the access token for that specific request.
"""
if not page_id:
msg = request.message # type: FacebookMessage
page_id = msg.get_page_id()
page = self.settings()
if page... |
java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
smtp_server_responses result = (smtp_server_responses) service.get_payload_formatter().string_to_resource(smtp_server_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode =... |
java | public void combine(SpdLong other) {
if (other == null)
return;
if (stat.isEnabled() && other.isEnabled())
stat.combine((CountStatisticImpl) other.getStatistic());
} |
java | private boolean readFormatRegion1(QrCode qr) {
// if( qr.ppRight.get(0).distance(988.8,268.3) < 30 )
// System.out.println("tjere");
// System.out.println(qr.ppRight.get(0));
// set the coordinate system to the closest pp to reduce position errors
gridReader.setSquare(qr.ppRight,(float)qr.threshRight);
bits... |
java | @Override
public void generate(TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, boolean updateMode, SQLiteModelMethod method, TypeName returnType) {
SQLiteDaoDefinition daoDefinition = method.getParent();
SQLiteEntity entity = method.getEntity();
// separate params used for update bean and param... |
python | def create(cls, user_id, github_id=None, name=None, **kwargs):
"""Create the repository."""
with db.session.begin_nested():
obj = cls(user_id=user_id, github_id=github_id, name=name,
**kwargs)
db.session.add(obj)
return obj |
java | private static int getCollectionSize(int[] repetitionLevels, int maxRepetitionLevel, int nextIndex)
{
int size = 1;
while (hasMoreElements(repetitionLevels, nextIndex) && !isCollectionBeginningMarker(repetitionLevels, maxRepetitionLevel, nextIndex)) {
// Collection elements can not only ... |
java | public static void sort(float[] floatArray) {
int index = 0;
float value = 0f;
for(int i = 1; i < floatArray.length; i++) {
index = i;
value = floatArray[index];
while(index > 0 && value < floatArray[index - 1]) {
floatArr... |
python | def publish(self, topic="/controller", qos=0, payload=None):
"""
publish(self, topic, payload=None, qos=0, retain=False)
Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to
indicate success or MQTT_ERR_NO_CONN if the client is not currently
connected. mid is the m... |
python | def getActors(self):
"""Unpack a list of ``vtkActor`` objects from a ``vtkAssembly``."""
cl = vtk.vtkPropCollection()
self.GetActors(cl)
self.actors = []
cl.InitTraversal()
for i in range(self.GetNumberOfPaths()):
act = vtk.vtkActor.SafeDownCast(cl.GetNextProp... |
java | private String _serializeList(List list, Map<Object, String> done, String id) throws ConverterException {
// <ARRAY ID="1" SIZE="1"><ITEM INDEX="1" TYPE="STRING">hello world</ITEM></ARRAY>
StringBuilder sb = new StringBuilder(goIn() + "<ARRAY ID=\"" + id + "\" SIZE=" + del + list.size() + del + ">");
int index;
Lis... |
python | def plot_heat_map(z, include_values=False,
cmap=matplotlib.cm.Reds,
ax=None,
xlabel='auto', ylabel='auto',
xtick_labels='auto', ytick_labels='auto',
xtick_locs=None, ytick_locs=None,
xtick_kwargs={}, ytick_kwargs... |
python | def _load_manifest_from_file(manifest, path):
""" load manifest from file """
path = os.path.abspath(os.path.expanduser(path))
if not os.path.exists(path):
raise ManifestException("Manifest does not exist at {0}!".format(path))
manifest.read(path)
if not manifest.has_option('config', 'source... |
python | def create(self, did, service_definition_id, agreement_id,
service_agreement_signature, consumer_address, account):
"""
Execute the service agreement on-chain using keeper's ServiceAgreement contract.
The on-chain executeAgreement method requires the following arguments:
... |
java | private List<Object> loadDataFromDocuments(Yaml yaml, InputStream inputStream) {
logger.entering(new Object[] { yaml, inputStream });
Iterator<?> documents = yaml.loadAll(inputStream).iterator();
List<Object> objList = new ArrayList<>();
while (documents.hasNext()) {
objList... |
python | def get_resource(self, uri, resource_type=None, response_format=None):
'''
Retrieve resource:
- Issues an initial GET request
- If 200, continues, 404, returns False, otherwise raises Exception
- Parse resource type
- If custom resource type parser provided, this fires
- Else, or if custom parser ... |
python | def geometric2geopotential(z: float, latitude: float) -> float:
"""Converts geometric height to geopoential height
Parameters
----------
z : float
Geometric height (meters)
latitude : float
Latitude (degrees)
Returns
-------
h : float
Geopotential Height (meters... |
java | private static void checkParityBlocks(final Path filePath,
final Map<Integer, Integer>
corruptBlocksPerStripe,
final long blockSize,
final long startStripeIdx,
... |
python | def fit_model(ts, sc=None):
"""
Fits an AR(1) + GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a AR+GARCH model as a Numpy array
Returns an ARGARCH model
"""
assert sc != None, "Missing SparkContext"
... |
python | def circle_intersection_area(r, R, d):
'''
Formula from: http://mathworld.wolfram.com/Circle-CircleIntersection.html
Does not make sense for negative r, R or d
>>> circle_intersection_area(0.0, 0.0, 0.0)
0.0
>>> circle_intersection_area(1.0, 1.0, 0.0)
3.1415...
>>> circle_intersection_a... |
python | def get_strain_label(entry, viral=False):
"""Try to extract a strain from an assemly summary entry.
First this checks 'infraspecific_name', then 'isolate', then
it tries to get it from 'organism_name'. If all fails, it
falls back to just returning the assembly accesion number.
"""
def get_strai... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.