language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public void onSaveItems(ItemStateChangesLog itemStates)
{
try
{
ChangesItem changesItem = new ChangesItem();
for (ItemState state : itemStates.getAllStates())
{
if (!state.getData().isNode())
{
String nodePath = getPath(state.getData().ge... |
python | def calc_requiredrelease_v2(self):
"""Calculate the water release (immediately downstream) required for
reducing drought events.
Required control parameter:
|NearDischargeMinimumThreshold|
Required derived parameter:
|dam_derived.TOY|
Calculated flux sequence:
|RequiredRelease|
... |
python | def get_output(self, worker_metadatas):
"""
Build the output entry of the metadata.
:return: list, containing dicts of partial metadata
"""
outputs = []
has_pulp_pull = PLUGIN_PULP_PULL_KEY in self.workflow.exit_results
try:
pulp_sync_results = self.w... |
python | def check_deleted_nodes(self):
""" delete imported nodes that are not present in the old database """
imported_nodes = Node.objects.filter(data__contains=['imported'])
deleted_nodes = []
for node in imported_nodes:
if OldNode.objects.filter(pk=node.pk).count() == 0:
... |
java | protected boolean isBNodeReferenced(BNode object) {
Collection<HashMap<QualifiedName, List<Statement>>> contexts = collators.values();
for (HashMap<QualifiedName, List<Statement>> context : contexts) {
for (QualifiedName subject : context.keySet()) {
List<Statement> statements = context.get(subject);
for (St... |
java | public static double universalThreshold(ImageGray image , double noiseSigma ) {
int w = image.width;
int h = image.height;
return noiseSigma*Math.sqrt(2*Math.log(Math.max(w,h)));
} |
java | public static <E> void pipe(Iterable<E> iterable, OutputIterator<E> outputIterator) {
dbc.precondition(iterable != null, "cannot call pipe with a null iterable");
new ConsumeIntoOutputIterator<>(outputIterator).apply(iterable.iterator());
} |
python | def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5):
'''
Waits wrapper that'll wait for the condition to become true, but will
not error if the condition isn't met.
Args:
condition (lambda) - Lambda expression to wait for to evaluate to True.
Kwargs:
time... |
python | def init():
"""Initialize the pipeline in maya so everything works
Init environment and load plugins.
This also creates the initial Jukebox Menu entry.
:returns: None
:rtype: None
:raises: None
"""
main.init_environment()
pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN... |
java | public HttpResponse doHttpCall(final String urlString,
final String stringToSend) throws IOException {
return this.doHttpCall(urlString, stringToSend, "", "", "", 0,
Collections.<String, String> emptyMap());
} |
python | def _touch_checkpoint(self, check_file):
"""
Alternative way for a pipeline to designate a checkpoint.
:param str check_file: Name or path of file to use as checkpoint.
:return bool: Whether a file was written (equivalent to whether the
checkpoint file already existed).
... |
java | private static Class<?>[] convert(Class<?>[] classes) {
Class<?>[] types = new Class<?>[classes.length];
for (int i = 0; i < types.length; i++) {
types[i] = convert(classes[i]);
}
return types;
} |
python | def load_images(self, search_file, source_file):
"""ๅ ่ฝฝๅพ
ๅน้
ๅพ็."""
self.search_file, self.source_file = search_file, source_file
self.im_search, self.im_source = imread(self.search_file), imread(self.source_file)
# ๅๅงๅๅฏน่ฑก
self.check_macthing_object = CheckKeypointResult(self.im_searc... |
java | @SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case TypesPackage.JVM_SHORT_ANNOTATION_VALUE__VALUES:
getValues().clear();
getValues().addAll((Collection<? extends Short>)newValue);
return;
}
super.eSet(featureID, newValue);
} |
java | protected final String renderTagId(HttpServletRequest request, String tagId, AbstractHtmlState state)
{
assert(_trs.tagId != null);
state.id = getIdForTagId(tagId);
String script = renderDefaultJavaScript(request, state.id);
return script;
} |
java | @Override
public ResultSet getExportedKeys( String catalog,
String schema,
String table ) throws SQLException {
return getImportedKeys(catalog, schema, table); // empty, but same resultsetmetadata
} |
java | public boolean isCallerInRole(String roleName, Object bean)
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
{
Tr.entry(tc, "isCallerInRole, role = " + roleName
+ " EJB = " + bean); //182011
}... |
java | public void marshall(StartFlowRequest startFlowRequest, ProtocolMarshaller protocolMarshaller) {
if (startFlowRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(startFlowRequest.getFlowArn(), ... |
java | public ResourceFormatParser getParserForFormat(final String format) throws UnsupportedFormatException {
try {
return providerOfType(format);
} catch (ExecutionServiceException e) {
throw new UnsupportedFormatException("No provider available to parse format: " + format,e);
... |
java | public Waiter<DescribeKeyPairsRequest> keyPairExists() {
return new WaiterBuilder<DescribeKeyPairsRequest, DescribeKeyPairsResult>().withSdkFunction(new DescribeKeyPairsFunction(client))
.withAcceptors(new KeyPairExists.IsTrueMatcher(), new KeyPairExists.IsInvalidKeyPairNotFoundMatcher())
... |
java | public void start() {
if(this.isActive)
return;
if (clock == null) {
throw new IllegalStateException("Clock is not set");
}
this.isActive = true;
logger.info("Starting ");
coreThread.activate();
criticalThread.activate();
... |
python | def learning_curve(train_scores, test_scores, train_sizes, ax=None):
"""Plot a learning curve
Plot a metric vs number of examples for the training and test set
Parameters
----------
train_scores : array-like
Scores for the training set
test_scores : array-like
Scores for the te... |
python | def get_nodes(self, request, *args, **kwargs):
""" this method might be overridden by other modules (eg: nodeshot.interop.sync) """
# ListSerializerMixin.list returns a serializer object
return (self.list(request, *args, **kwargs)).data |
java | public static int priorityOf(Class<?> someClass) {
while (someClass != null) {
Priority annotation = someClass.getAnnotation(Priority.class);
if (annotation != null) {
return annotation.value();
}
someClass = someClass.getSuperclass();
}
... |
java | public Attribute removeAttributeByLocalName(CharSequence name) {
for (Iterator<Attribute> it = event.attributes.iterator(); it.hasNext(); ) {
Attribute attr = it.next();
if (attr.localName.equals(name)) {
it.remove();
return attr;
}
}
return null;
} |
python | def getBalance(self, CorpNum):
""" ํ๋น ํ์ ์์ฌํฌ์ธํธ ํ์ธ
args
CorpNum : ํ์ธํ๊ณ ์ ํ๋ ํ์ ์ฌ์
์๋ฒํธ
return
์์ฌํฌ์ธํธ by float
raise
PopbillException
"""
try:
return linkhub.getBalance(self._getToken(CorpNum))
exce... |
java | private void addExtraHeaders(final ByteBuffer bb,
final Object... extraHeaders) {
for (Object o : extraHeaders) {
if (o instanceof Integer) {
bb.putInt((Integer) o);
} else if (o instanceof byte[]) {
bb.put((byte[]) o);
} else if (o instanceof Long) {
bb.putLong((Long) ... |
java | private boolean isNewStep(RouteProgress routeProgress) {
boolean isNewStep = currentStep == null || !currentStep.equals(routeProgress.currentLegProgress().currentStep());
currentStep = routeProgress.currentLegProgress().currentStep();
resetAlertLevels(isNewStep);
return isNewStep;
} |
java | static DeploymentContent of(final URL url) {
return new DeploymentContent() {
@Override
void addContentToOperation(final OperationBuilder builder, final ModelNode op) {
final ModelNode contentNode = op.get(CONTENT);
final ModelNode contentItem = contentNod... |
python | def comb_jit(N, k):
"""
Numba jitted function that computes N choose k. Return `0` if the
outcome exceeds the maximum value of `np.intp` or if N < 0, k < 0,
or k > N.
Parameters
----------
N : scalar(int)
k : scalar(int)
Returns
-------
val : scalar(int)
"""
# Fro... |
python | def value(self):
"""
Returns the current load average as a value between 0.0 (representing
the *min_load_average* value) and 1.0 (representing the
*max_load_average* value). These default to 0.0 and 1.0 respectively.
"""
load_average_range = self.max_load_average - self.m... |
java | public static String getParamTypesString(Class<?>... paramTypes) {
StringBuilder paramTypesList = new StringBuilder("(");
for (int i = 0; i < paramTypes.length; i++) {
paramTypesList.append(paramTypes[i].getSimpleName());
if (i + 1 < paramTypes.length) {
paramTypesList.append(", ");
}
}
return para... |
python | def get_unit(unit_id, **kwargs):
"""
Returns a single unit
"""
try:
unit = db.DBSession.query(Unit).filter(Unit.id==unit_id).one()
return JSONObject(unit)
except NoResultFound:
# The dimension does not exist
raise ResourceNotFoundError("Unit %s not found"%(unit_id... |
java | @Override
protected void searchStep() {
// more solutions to generate ?
if(solutionIterator.hasNext()){
// generate next solution
SolutionType sol = solutionIterator.next();
// update best solution
updateBestSolution(sol);
} else {
... |
python | def login(credentials=None, app_name=None, services=None, client_id=None, make_clients=True,
clear_old_tokens=False, token_dir=DEFAULT_CRED_PATH, **kwargs):
"""Log in to Globus services
Arguments:
credentials (str or dict): A string filename, string JSON, or dictionary
with cr... |
java | protected static SQLEnum value(Class<? extends SQLEnum> clazz,String value) {
if (value == null) {
return null;
}
value=value.trim();
if (valuesCache.containsKey(clazz)){
Map<String,SQLEnum> map2=valuesCache.get(clazz);
if (map2.containsKey(value)){
return map2.get(value);
}
}
ret... |
java | public synchronized ArrayList<MapTaskStatistics>
getMapTaskList(Enum mapTaskSortKey, KeyDataType dataType) {
/*
* If mapTaskSortKey is null then use the task id as a key.
*/
if (mapTaskSortKey == null) {
mapTaskSortKey = MapTaskKeys.TASK_ID;
}
if (this._sortedMapTas... |
python | def find(cls, device=None):
"""
Factory method that returns the requested :py:class:`USBDevice` device, or the
first device.
:param device: Tuple describing the USB device to open, as returned
by find_all().
:type device: tuple
:returns: :py:class... |
java | public <E> E get(PartitionKey key, EntityMapper<E> entityMapper) {
return get(key, null, entityMapper);
} |
java | @Override
protected void openConnectionInternal() throws ConnectionException, AuthenticationException {
if (checkoutDirectory == null) {
checkoutDirectory = createCheckoutDirectory();
}
if (checkoutDirectory.exists() && safeCheckout) {
removeCheckoutDirectory();
}
checkoutDirectory.mkdirs();
} |
java | public Observable<ServiceResponse<OcrResult>> recognizePrintedTextWithServiceResponseAsync(boolean detectOrientation, String url, RecognizePrintedTextOptionalParameter recognizePrintedTextOptionalParameter) {
if (this.client.endpoint() == null) {
throw new IllegalArgumentException("Parameter this.cl... |
java | public void setSize(int width, int height) {
final float r = width * 0.75f / SIN;
final float y = COS * r;
final float h = r - y;
final float or = height * 0.75f / SIN;
final float oy = COS * or;
final float oh = or - oy;
mRadius = r;
mBaseGlowScale = h >... |
java | private void getMatchingEECerts(ForwardState currentState,
List<CertStore> certStores,
Collection<X509Certificate> eeCerts)
throws IOException
{
if (debug != null) {
debug.println("ForwardBuilder.getMatchingEECerts()... |
python | def run_command_async(self, msg):
'''
:type message_generator: generator of dict
:param message_generator: Generates messages from slack that should be run
:type fire_all: bool
:param fire_all: Whether to also fire messages to the event bus
:type tag: str
:para... |
java | public V remove(Object key) {
clean();
ValueRef<K, V> valueRef = mValues.remove(key);
V value;
if (valueRef != null && (value = valueRef.get()) != null) {
valueRef.clear();
return value;
}
return null;
} |
python | def splitstring(string, splitcharacter=' ', part=None):
"""
Split a string based on a character and get the parts as a list.
:type string: string
:param string: The string to split.
:type splitcharacter: string
:param splitcharacter: The character to split for the string.
:type part: inte... |
python | def _get_named_patterns():
"""Returns list of (pattern-name, pattern) tuples"""
resolver = urlresolvers.get_resolver(None)
patterns = sorted([(key, value[0][0][0])
for key, value in resolver.reverse_dict.items()
if isinstance(key, string_types)
... |
python | def structure_results(res):
"""Format Elasticsearch result as Python dictionary"""
out = {'hits': {'hits': []}}
keys = [u'admin1_code', u'admin2_code', u'admin3_code', u'admin4_code',
u'alternativenames', u'asciiname', u'cc2', u'coordinates',
u'country_code2', u'country_code3', u'dem... |
python | def main():
"""The main function."""
# Prepare and run cmdline-parser.
cmdlineParser = argparse.ArgumentParser(
description="Fixes the input files used for pre-processing of Boost.MPL headers.")
cmdlineParser.add_argument("-v", "--verbose", dest='verbose', action='store_true',
... |
java | @Override
public String getTrimmedPath(String path)
{
if (path == null)
{
return "/";
}
if (!path.startsWith("/"))
{
try
{
path = new URL(path).getPath();
}
catch (MalformedURLException ex)
{
// ignore
... |
java | public static void writeHtmlImagePreloadJavaScript(String url, Appendable out) throws IOException {
out.append("<script type='text/javascript'>\n"
+ " var img=new Image();\n"
+ " img.src=\"");
// Escape for javascript
StringBuilder javascript = new StringBuilder(url.length());
encodeTextInJavaScript(u... |
java | public String getSQLColumn(String tabalis, String fieldname) {
return this.aliasmap == null ? (tabalis == null ? fieldname : (tabalis + '.' + fieldname))
: (tabalis == null ? aliasmap.getOrDefault(fieldname, fieldname) : (tabalis + '.' + aliasmap.getOrDefault(fieldname, fieldname)));
} |
java | public static void channelOperationFactory(AbstractBootstrap<?, ?> b,
ChannelOperations.OnSetup opsFactory) {
Objects.requireNonNull(b, "bootstrap");
Objects.requireNonNull(opsFactory, "opsFactory");
b.option(OPS_OPTION, opsFactory);
} |
python | def sample(self, sampling_period, start=None, end=None,
interpolate='previous'):
"""Sampling at regular time periods.
"""
start, end, mask = self._check_boundaries(start, end)
sampling_period = \
self._check_regularization(start, end, sampling_period)
... |
python | def request_data(cls, time, site_id, derived=False):
"""Retreive IGRA version 2 data for one station.
Parameters
--------
site_id : str
11-character IGRA2 station identifier.
time : datetime
The date and time of the desired observation. If list of two tim... |
java | public TableRow getRow(final String pos) throws FastOdsException, IOException {
return this.builder.getRow(this, this.appender, pos);
} |
python | def from_file(cls, fn, *args, **kwargs):
"""Constructor to build an AmiraHeader object from a file
:param str fn: Amira file
:return ah: object of class ``AmiraHeader`` containing header metadata
:rtype: ah: :py:class:`ahds.header.AmiraHeader`
"""
return AmiraHea... |
java | @Override
public String getConnectedMEName() {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "getConnectedMEName");
String meName = coreConnection.getMeName();
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
Si... |
java | public void updateRowId(int columnIndex, RowId x) throws SQLException {
try {
rsetImpl.updateRowId(columnIndex, x);
} catch (SQLException sqlX) {
FFDCFilter.processException(
sqlX, getClass().getName() + ".updateRowId", "5064", this);
... |
python | def get_for(self, query_type, value):
"""
Create a query and run it for the given arg if it doesn't exist, and
return the tweets for the query.
"""
from yacms.twitter.models import Query
lookup = {"type": query_type, "value": value}
query, created = Query.objects.... |
java | public static String toHexString(byte[] bytes, boolean isHNF) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
String hex =
String.format("%2s", Integer.toHexString(b & 0xFF)).replace(' ', '0');
if (isHNF)
sb.append(hex);
else
sb.append(new StringBuild... |
java | @Subscribe
public void onFailure(Throwable t) {
Toast.makeText(this, t.getMessage(), LENGTH_LONG).show();
} |
python | def clientConnectionFailed(self, connector, reason):
"""Called when the client has failed to connect to the broker.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details.
"""
_legacy_twisted_log.msg(
"Connection to the AMQP broker... |
java | public Observable<AppServiceCertificateOrderInner> createOrUpdateAsync(String resourceGroupName, String certificateOrderName, AppServiceCertificateOrderInner certificateDistinguishedName) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).map(n... |
python | def region_interface_areas(regions, areas, voxel_size=1, strel=None):
r"""
Calculates the interfacial area between all pairs of adjecent regions
Parameters
----------
regions : ND-array
An image of the pore space partitioned into individual pore regions.
Note that zeros in the image... |
java | @Override
@FFDCIgnore(value = { RejectedExecutionException.class })
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, PolicyTaskCallback[] callbacks) throws InterruptedException, ExecutionException {
int taskCount = tasks.size();
// Special case to run a single task on the current... |
java | public void deleteSnapshot(DeleteSnapshotRequest request) {
checkNotNull(request, "request should not be null.");
checkStringNotEmpty(request.getSnapshotId(), "request snapshotId should no be empty.");
InternalRequest internalRequest =
this.createRequest(request, HttpMethodName.D... |
python | def supports_heading_type(self, heading_type):
"""Tests if the given heading type is supported.
arg: heading_type (osid.type.Type): a heading Type
return: (boolean) - ``true`` if the type is supported, ``false``
otherwise
raise: IllegalState - syntax is not a ``HEADI... |
java | public static boolean isSupportedJDKType(TypeName typeName) {
if (typeName.isPrimitive()) {
return getPrimitiveTransform(typeName) != null;
}
String name = typeName.toString();
if (name.startsWith("java.lang")) {
return getLanguageTransform(typeName) != null;
}
if (name.startsWith("java.util")) {
... |
java | private void readMbean() {
if (clazz == null) {
return;
}
try {
if (isUnixOS) {
long openFiles = getValue("OpenFileDescriptorCount");
long maxOpenFiles = getValue("MaxFileDescriptorCount");
long freePhysicalMemorySize = getValue("FreePhysicalMemorySize");
long totalPhysicalMemorySize = getV... |
python | def performance_measure(y_true, y_pred):
"""
Compute the performance metrics: TP, FP, FN, TN
Args:
y_true : 2d array. Ground truth (correct) target values.
y_pred : 2d array. Estimated targets as returned by a tagger.
Returns:
performance_dict : dict
Example:
>>> f... |
java | public static String deidentifyRight(String str, int size) {
int end = str.length();
int repeat;
if (size > str.length()) {
repeat = str.length();
} else {
repeat = size;
}
return StringUtils.overlay(str, StringUtils.repeat('*', repeat), end - size, end);
} |
python | def _to_power_basis_degree8(nodes1, nodes2):
r"""Compute the coefficients of an **intersection polynomial**.
Helper for :func:`to_power_basis` in the case that B |eacute| zout's
`theorem`_ tells us the **intersection polynomial** is degree
:math:`8`. This happens if the two curves have degrees one and ... |
python | def set_tag(self, key, value):
"""
:param key:
:param value:
"""
with self.update_lock:
if key == ext_tags.SAMPLING_PRIORITY and not self._set_sampling_priority(value):
return self
if self.is_sampled():
tag = thrift.make_tag... |
python | def get_algorithm(algorithm):
"""Returns the wire format string and the hash module to use for the
specified TSIG algorithm
@rtype: (string, hash constructor)
@raises NotImplementedError: I{algorithm} is not supported
"""
global _hashes
if _hashes is None:
_setup_hashes()
if i... |
java | public void choosePathString(String path, boolean resetCallstack, Object[] arguments) throws Exception {
ifAsyncWeCant("call ChoosePathString right now");
if (resetCallstack) {
resetCallstack();
} else {
// ChoosePathString is potentially dangerous since you can call it when the
// stack is
// pretty... |
python | def is_static(*p):
""" A static value (does not change at runtime)
which is known at compile time
"""
return all(is_CONST(x) or
is_number(x) or
is_const(x)
for x in p) |
python | def restart_with_reloader():
"""Create a new process and a subprocess in it with the same arguments as
this one.
"""
cwd = os.getcwd()
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ["SANIC_SERVER_RUNNING"] = "true"
cmd = " ".join(args)
worker_process = P... |
python | def bench_report(results):
"""Print a report for given benchmark results to the console."""
table = Table(names=['function', 'nest', 'nside', 'size',
'time_healpy', 'time_self', 'ratio'],
dtype=['S20', bool, int, int, float, float, float], masked=True)
for row in ... |
python | def _check_cpd_inputs(X, rank):
"""Checks that inputs to optimization function are appropriate.
Parameters
----------
X : ndarray
Tensor used for fitting CP decomposition.
rank : int
Rank of low rank decomposition.
Raises
------
ValueError: If inputs are not suited for ... |
python | def to_rst_(self) -> str:
"""Convert the main dataframe to restructured text
:return: rst data
:rtype: str
:example: ``ds.to_rst_()``
"""
try:
renderer = pytablewriter.RstGridTableWriter
data = self._build_export(renderer)
return data... |
java | @SuppressWarnings("unused")
public static void initialize(Class<?> type, int identification) throws Exception {
Object typeInitializer = TYPE_INITIALIZERS.remove(new Nexus(type, identification));
if (typeInitializer != null) {
typeInitializer.getClass().getMethod("onLoad", Class.class).i... |
python | def add_task(self, task, parent_task_result):
"""
Add a task to run with the specified result from this tasks parent(can be None)
:param task: Task: task that should be run
:param parent_task_result: object: value to be passed to task for setup
"""
self.tasks.append((task... |
java | public ServiceFuture<VirtualMachineScaleSetInner> updateAsync(String resourceGroupName, String vmScaleSetName, VirtualMachineScaleSetUpdate parameters, final ServiceCallback<VirtualMachineScaleSetInner> serviceCallback) {
return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, vmScal... |
java | public Pixel[][] patches(int patchWidth, int patchHeight) {
Pixel[][] patches = new Pixel[(height - patchHeight) * (width - patchWidth)][];
int k = 0;
for (int row = 0; row < height - patchHeight; row++) {
for (int col = 0; col < width - patchWidth; col++) {
patches[k... |
java | protected void setProcessor(final Processor processor) throws BuildException, NullPointerException {
if (processor == null) {
throw new NullPointerException("processor");
}
if (isReference()) {
throw super.tooManyAttributes();
}
if (this.env == null && !this.newEnvironment) {
this.... |
python | def send(sms_to, sms_body, **kwargs):
"""
Site: http://iqsms.ru/
API: http://iqsms.ru/api/
"""
headers = {
"User-Agent": "DBMail/%s" % get_version(),
'Authorization': 'Basic %s' % b64encode(
"%s:%s" % (
settings.IQSMS_API_LOGIN, settings.IQSMS_API_PASSWORD... |
python | def access_labels(self):
"""List of labels used to access the Port
Returns
-------
list of str
Strings that can be used to access this Port relative to self.root
"""
access_labels = []
for referrer in self.referrers:
referrer_labels = [key... |
java | public Audio getOgg(String ref) throws IOException {
return getOgg(ref, ResourceLoader.getResourceAsStream(ref));
} |
python | def get_section(file_name, section, separator='='):
'''
Retrieve a section from an ini file. Returns the section as dictionary. If
the section is not found, an empty dictionary is returned.
API Example:
.. code-block:: python
import salt
sc = salt.client.get_local_client()
... |
python | def bwar_pitch(return_all=False):
"""
Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats.
To get all fields from this table, supply argument return_all=True.
"""
url = "http://www.baseball-reference.com/data/war_daily_pitch.txt"
s = requests.get(url... |
java | public static void d(String msg, Throwable tr) {
assertInitialization();
sLogger.d(msg, tr);
} |
python | def decorate_cls_with_validation(cls,
field_name, # type: str
*validation_func, # type: ValidationFuncs
**kwargs):
# type: (...) -> Type[Any]
"""
This method is equivalent to decorating a class with th... |
java | public static void verifySnapshots(
final List<String> directories, final Set<String> snapshotNames) {
FileFilter filter = new SnapshotFilter();
if (!snapshotNames.isEmpty()) {
filter = new SpecificSnapshotFilter(snapshotNames);
}
Map<String, Snapshot> snapshots... |
java | public static AbstractExpression eliminateDuplicates(Collection<AbstractExpression> exprList) {
// Eliminate duplicates by building the map of expression's ids, values.
Map<String, AbstractExpression> subExprMap = new HashMap<String, AbstractExpression>();
for (AbstractExpression subExpr : exprL... |
python | def safe_split_text(text: str, length: int = MAX_MESSAGE_LENGTH) -> typing.List[str]:
"""
Split long text
:param text:
:param length:
:return:
"""
# TODO: More informative description
temp_text = text
parts = []
while temp_text:
if len(temp_text) > length:
t... |
java | public static <T, E> MultiKindFeedParser<T> create(HttpResponse response,
XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E>... entryClasses)
throws IOException, XmlPullParserException {
InputStream content = response.getContent();
try {
Atom.checkContentType(response.get... |
python | def get_status(self):
"""Returns a dictionary containing all relevant status information to be
broadcast across the network."""
return {
"host": self.__hostid,
"status": self._service_status_announced,
"statustext": CommonService.human_readable_state.get(
... |
java | private static List<DiscoveryIncomingMessage> collectIncomingMessages(int pTimeout, List<Future<List<DiscoveryIncomingMessage>>> pFutures, LogHandler pLogHandler) throws UnknownHostException {
List<DiscoveryIncomingMessage> ret = new ArrayList<DiscoveryIncomingMessage>();
Set<String> seen = new HashSet<... |
python | def set_server(self, wsgi_app, fnc_serve=None):
"""
figures out how the wsgi application is to be served
according to config
"""
self.set_wsgi_app(wsgi_app)
ssl_config = self.get_config("ssl")
ssl_context = {}
if self.get_config("server") == "gevent":
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.