language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static Trade adaptTrade(CexIOTrade trade, CurrencyPair currencyPair) {
BigDecimal amount = trade.getAmount();
BigDecimal price = trade.getPrice();
Date date = DateUtils.fromMillisUtc(trade.getDate() * 1000L);
OrderType type = trade.getType().equals(ORDER_TYPE_BUY) ? OrderType.BID : OrderType.ASK... |
python | def __calculate_audio_frames(self):
""" Aligns audio with video.
This should be called for instance after a seeking operation or resuming
from a pause. """
if self.audioformat is None:
return
start_frame = self.clock.current_frame
totalsize = int(self.clip.audio.fps*self.clip.audio.duration)
self.au... |
java | protected void invoke(String serviceName, Operation operation, int partitionId) {
try {
operationCount++;
operationService
.invokeOnPartition(serviceName, operation, partitionId)
.andThen(mergeCallback);
} catch (Throwable t) {
... |
python | def get_left_child(self, n):
'''
API: get_left_child(self, n)
Description:
Returns left child of node n. n can be Node() instance or string
(name of node).
Pre:
Node n should be present in the tree.
Input:
n: Node name or Node() ins... |
python | def make_anchor(file_path: pathlib.Path,
offset: int,
width: int,
context_width: int,
metadata,
encoding: str = 'utf-8',
handle=None):
"""Construct a new `Anchor`.
Args:
file_path: The absolute path to the t... |
python | def tls_feature(self):
"""The :py:class:`~django_ca.extensions.TLSFeature` extension, or ``None`` if it doesn't exist."""
try:
ext = self.x509.extensions.get_extension_for_oid(ExtensionOID.TLS_FEATURE)
except x509.ExtensionNotFound:
return None
return TLSFeature(e... |
python | def _start_selecting(self, event):
"""Comienza con el proceso de seleccion."""
self._selecting = True
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
self._sstart = (x, y)
if not self._sobject:
self._sobject = canvas.creat... |
java | private static void getDateTimeSkeleton(String skeleton,
StringBuilder dateSkeleton,
StringBuilder normalizedDateSkeleton,
StringBuilder timeSkeleton,
... |
java | private boolean itemIsObscuredByHeader(RecyclerView parent, View item, View header, int orientation) {
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) item.getLayoutParams();
mDimensionCalculator.initMargins(mTempRect1, header);
int adapterPosition = parent.getChildAdapterPosition(item... |
java | @BetaApi
public final HttpsHealthCheck2 getHttpsHealthCheck(
ProjectGlobalHttpsHealthCheckName httpsHealthCheck) {
GetHttpsHealthCheckHttpRequest request =
GetHttpsHealthCheckHttpRequest.newBuilder()
.setHttpsHealthCheck(httpsHealthCheck == null ? null : httpsHealthCheck.toString())
... |
python | def _resolve(self):
"""resolve the type symbol from name by doing a lookup"""
self.__is_resolved = True
if self.is_complex:
type = self.nested if self.nested else self
type.__reference = self.module.lookup(type.name) |
python | def get_access_key(self):
"""
Gets the application secret key.
The value can be stored in parameters "access_key", "client_key" or "secret_key".
:return: the application secret key.
"""
access_key = self.get_as_nullable_string("access_key")
access_key = access_ke... |
java | public OHLCSeries updateOHLCSeries(
String seriesName,
double[] newXData,
double[] newOpenData,
double[] newHighData,
double[] newLowData,
double[] newCloseData) {
sanityCheck(seriesName, newOpenData, newHighData, newLowData, newCloseData);
Map<String, OHLCSeries> seriesMap... |
python | def calculate_fee(self, input_values):
'''
Tx, list(int) -> int
Inputs don't know their value without the whole chain.
'''
return \
sum(input_values) \
- sum([utils.le2i(o.value) for o in self.tx_outs]) |
python | def encode(self,
data: mx.sym.Symbol,
data_length: mx.sym.Symbol,
seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]:
"""
Encodes data given sequence lengths of individual examples and maximum sequence length.
:param data: Input data.
... |
python | def Idelchik(dp, voidage, vs, rho, mu, L=1):
r'''Calculates pressure drop across a packed bed of spheres as in [2]_,
originally in [1]_.
.. math::
\frac{\Delta P}{L\rho v_s^2} d_p = \frac{0.765}{\epsilon^{4.2}}
\left(\frac{30}{Re_l} + \frac{3}{Re_l^{0.7}} + 0.3\right)
.. math::
... |
java | public static List<CommerceWishList> toModels(
CommerceWishListSoap[] soapModels) {
if (soapModels == null) {
return null;
}
List<CommerceWishList> models = new ArrayList<CommerceWishList>(soapModels.length);
for (CommerceWishListSoap soapModel : soapModels) {
models.add(toModel(soapModel));
}
re... |
java | protected void appendElements(RendersnakeHtmlCanvas html,
List<SubtitleItem.Inner> elements) throws IOException {
for (SubtitleItem.Inner element : elements) {
String kanji = element.getKanji();
if (kanji != null) {
html.spanKanji(kanji);
} else {
html.write(element.getText());
}
}
... |
python | def text_entry(self):
""" Relay literal text entry from user to Roku until
<Enter> or <Esc> pressed. """
allowed_sequences = set(['KEY_ENTER', 'KEY_ESCAPE', 'KEY_DELETE'])
sys.stdout.write('Enter text (<Esc> to abort) : ')
sys.stdout.flush()
# Track start column to ens... |
java | @Override
public com.liferay.commerce.shipping.engine.fixed.model.CommerceShippingFixedOption deleteCommerceShippingFixedOption(
com.liferay.commerce.shipping.engine.fixed.model.CommerceShippingFixedOption commerceShippingFixedOption) {
return _commerceShippingFixedOptionLocalService.deleteCommerceShippingFixedOpt... |
python | def train_async(train_dataset,
eval_dataset,
analysis_dir,
output_dir,
features,
model_type,
max_steps=5000,
num_epochs=None,
train_batch_size=100,
eval_batch_size=16,
... |
java | public static byte[] marshallTxnEntry(TxnHeader hdr, Record txn)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputArchive boa = BinaryOutputArchive.getArchive(baos);
hdr.serialize(boa, "hdr");
if (txn != null) {
txn.serialize(b... |
python | def plot_dos(self, sigma=0.05):
"""
plot dos
Args:
sigma: a smearing
Returns:
a matplotlib object
"""
plotter = DosPlotter(sigma=sigma)
plotter.add_dos("t", self._bz.dos)
return plotter.get_plot() |
python | def return_obj(cols, df, return_cols=False):
"""Construct a DataFrameHolder and then return either that or the DataFrame."""
df_holder = DataFrameHolder(cols=cols, df=df)
return df_holder.return_self(return_cols=return_cols) |
java | public final double estimatedLatitude(long et)
{
et = correctedTime(et);
lock.lock();
try
{
calc();
if (rateOfTurn == 0)
{
double dist = calcDist(et);
return latitude+deltaLatitude(dist, bearing);
... |
python | def to_bytes(self, exclude=tuple(), disable=None, **kwargs):
"""Serialize the current state to a binary string.
exclude (list): Names of components or serialization fields to exclude.
RETURNS (bytes): The serialized form of the `Language` object.
DOCS: https://spacy.io/api/language#to_... |
python | def readSheet(self, sheet):
"""Reads a sheet in the sheet dictionary
Stores each sheet as an array (rows) of arrays (columns)
"""
name = sheet.getAttribute("name")
rows = sheet.getElementsByType(TableRow)
arrRows = []
# for each row
for row in rows:
... |
python | def buildDefaultRefWCS(self):
""" Generate a default reference WCS for this image. """
self.default_refWCS = None
if self.use_wcs:
wcslist = []
for scichip in self.chip_catalogs:
wcslist.append(self.chip_catalogs[scichip]['wcs'])
self.default_r... |
java | public static CommerceSubscriptionEntry remove(
long commerceSubscriptionEntryId)
throws com.liferay.commerce.exception.NoSuchSubscriptionEntryException {
return getPersistence().remove(commerceSubscriptionEntryId);
} |
java | @Override
public ModifyVolumeAttributeResult modifyVolumeAttribute(ModifyVolumeAttributeRequest request) {
request = beforeClientExecution(request);
return executeModifyVolumeAttribute(request);
} |
python | def sort(iterable):
"""
Given an IP address list, this function sorts the list.
:type iterable: Iterator
:param iterable: An IP address list.
:rtype: list
:return: The sorted IP address list.
"""
ips = sorted(normalize_ip(ip) for ip in iterable)
return [clean_ip(ip) for ip in ips] |
java | @Nonnull
public final LBiCharFunction<R> build() {
final LBiCharFunction<R> eventuallyFinal = this.eventually;
LBiCharFunction<R> retval;
final Case<LBiCharPredicate, LBiCharFunction<R>>[] casesArray = cases.toArray(new Case[cases.size()]);
retval = LBiCharFunction.<R> biCharFunc((a1, a2) -> {
try {
... |
java | public static InputStream getStream(String string) {
try {
return new ByteArrayInputStream(string.getBytes("UTF-8"));
} catch (UnsupportedEncodingException wontHappen) {
throw new FaultException(wontHappen);
}
} |
python | def text_justification(words, max_width):
'''
:type words: list
:type max_width: int
:rtype: list
'''
ret = [] # return value
row_len = 0 # current length of strs in a row
row_words = [] # current words in a row
index = 0 # the index of current word in words
is_first_word = T... |
java | public int compare(BuildableItem lhs, BuildableItem rhs) {
return compare(lhs.buildableStartMilliseconds,rhs.buildableStartMilliseconds);
} |
python | def limits(self,variable):
"""Return minimum and maximum of variable across all rows of data."""
(vmin,vmax), = self.SELECT('min(%(variable)s), max(%(variable)s)' % vars())
return vmin,vmax |
python | def get_login_redirect_url(self, request):
"""
Returns the default URL to redirect to after logging in. Note
that URLs passed explicitly (e.g. by passing along a `next`
GET parameter) take precedence over the value returned here.
"""
assert request.user.is_authenticated
... |
java | public static <V> Map<V, V> convertListToMap(List<V> list) {
Map<V, V> map = new HashMap<V, V>();
if(list.size() % 2 != 0)
throw new VoldemortException("Failed to convert list to map.");
for(int i = 0; i < list.size(); i += 2) {
map.put(list.get(i), list.get(i + 1));
... |
java | public static IMolecularFormula removeElement(IMolecularFormula formula, IElement element) {
for (IIsotope isotope : getIsotopes(formula, element)) {
formula.removeIsotope(isotope);
}
return formula;
} |
python | def output(self, _in, out, **kwargs):
"""Wrap translation in Angular module."""
out.write(
'angular.module("{0}", ["gettext"]).run('
'["gettextCatalog", function (gettextCatalog) {{'.format(
self.catalog_name
)
)
out.write(_in.read())
... |
java | public long get() throws MemcachedException, InterruptedException, TimeoutException {
Object result = this.memcachedClient.get(this.key);
if (result == null) {
throw new MemcachedClientException("key is not existed.");
} else {
if (result instanceof Long)
return (Long) result;
else... |
python | def absent(name, profile='grafana'):
'''
Ensure that a org is present.
name
Name of the org to remove.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
'''
if isinstance(profile, string_types):
profile = __salt__['conf... |
java | public InternalTimersSnapshot<K, N> snapshotTimersForKeyGroup(int keyGroupIdx) {
return new InternalTimersSnapshot<>(
keySerializer,
namespaceSerializer,
eventTimeTimersQueue.getSubsetForKeyGroup(keyGroupIdx),
processingTimeTimersQueue.getSubsetForKeyGroup(keyGroupIdx));
} |
java | @Override
public JSONObject toJSON() throws JSONException {
JSONObject json = super.toJSON();
JSONArray geometries = new JSONArray();
for (Geometry geometry : this.mGeometries) {
geometries.put(geometry.toJSON());
}
json.put(JSON_GEOMETRIES, geometries);
... |
java | public static <A extends ModelAdapter<Model, Item>, Model, Item extends IItem> A set(final A adapter, final List<Item> items, final DiffCallback<Item> callback) {
return set(adapter, items, callback, true);
} |
java | public static BufferedImage convertImageToGrayscale(BufferedImage image) {
BufferedImage tmp = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g2 = tmp.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
return tm... |
java | private int indexSingleKey(InputStream input, long entryOffset, KeyUpdateCollection keyUpdateCollection) throws IOException {
// Retrieve the next entry, get its Key and hash it.
val e = AsyncTableEntryReader.readEntryComponents(input, entryOffset, this.connector.getSerializer());
HashedArray ke... |
java | @CheckResult @NonNull
public Preference<String> getString(@NonNull String key) {
return getString(key, DEFAULT_STRING);
} |
java | static <T> T doWithMainClasses(File rootFolder, MainClassCallback<T> callback)
throws IOException {
if (!rootFolder.exists()) {
return null; // nothing to do
}
if (!rootFolder.isDirectory()) {
throw new IllegalArgumentException(
"Invalid root folder '" + rootFolder + "'");
}
String prefix = root... |
java | private void onSetSubComparator(CfDef cfDef, Properties cfProperties, StringBuilder builder)
{
String subComparatorType = cfProperties.getProperty(CassandraConstants.SUBCOMPARATOR_TYPE);
if (subComparatorType != null && ColumnFamilyType.valueOf(cfDef.getColumn_type()) == ColumnFamilyType.Super)
... |
python | def agreement_weighted(ci, wts):
'''
D = AGREEMENT_WEIGHTED(CI,WTS) is identical to AGREEMENT, with the
exception that each partitions contribution is weighted according to
the corresponding scalar value stored in the vector WTS. As an example,
suppose CI contained partitions obtained using some heu... |
java | @Override
public void setRadii(float[] radii) {
if (radii == null) {
Arrays.fill(mCornerRadii, 0);
mRadiiNonZero = false;
} else {
Preconditions.checkArgument(radii.length == 8, "radii should have exactly 8 values");
System.arraycopy(radii, 0, mCornerRadii, 0, 8);
mRadiiNonZero =... |
java | public static int Mode( int[] values ){
int mode = 0, curMax = 0;
for ( int i = 0, length = values.length; i < length; i++ )
{
if ( values[i] > curMax )
{
curMax = values[i];
mode = i;
}
}
return mode;
} |
python | def read_toml(self, encoding=None, errors=None, newline=None, **kwargs):
"""Read this path as a TOML document.
The `TOML <https://github.com/toml-lang/toml>`_ parsing is done with
the :mod:`pytoml` module. The *encoding*, *errors*, and *newline*
keywords are passed to :meth:`open`. The ... |
python | def handle_stderr(stderr_pipe):
"""
Takes stderr from the command's output and displays it AFTER the stdout
is printed by run_command().
"""
stderr_output = stderr_pipe.read()
if len(stderr_output) > 0:
click.secho("\n__ Error Output {0}".format('_'*62), fg='white',
... |
python | def detach_model(vmssvm_model, lun):
'''Detach a data disk from a VMSS VM model'''
data_disks = vmssvm_model['properties']['storageProfile']['dataDisks']
data_disks[:] = [disk for disk in data_disks if disk.get('lun') != lun]
vmssvm_model['properties']['storageProfile']['dataDisks'] = data_disks
ret... |
python | def _process_attachments(self, attachments):
"""
Create attachments suitable for delivery to Hectane from the provided
list of attachments.
Each attachment may be either a local filename, a file object, or a
dict describing the content (in the same format as Hectane). Note that
... |
java | @Pure
@Inline(value = "Math.abs($1) < Math.ulp($1)", imported = Math.class)
public static boolean isEpsilonZero(double value) {
return Math.abs(value) < Math.ulp(value);
} |
python | def calculate_sources(self, targets):
"""Generate a set of source files from the given targets."""
sources = set()
for target in targets:
sources.update(
source for source in target.sources_relative_to_buildroot()
if source.endswith(self._PYTHON_SOURCE_EXTENSION)
)
return sou... |
java | private boolean shouldMergeTo(Address thisAddress, Address targetAddress) {
String thisAddressStr = "[" + thisAddress.getHost() + "]:" + thisAddress.getPort();
String targetAddressStr = "[" + targetAddress.getHost() + "]:" + targetAddress.getPort();
if (thisAddressStr.equals(targetAddressStr)) ... |
java | protected SMailPostalPersonnel createPostalPersonnel() {
final SMailDogmaticPostalPersonnel personnel = createDogmaticPostalPersonnel();
return fessConfig.isMailSendMock() ? personnel.asTraining() : personnel;
} |
python | def calculate_mag_calibration(self, mag_samples):
"""Performs magnetometer calibration. Assumes mag_samples contains samples
in order [+x, -x, +y, -y, +z, -z]. Calculates per-axis scale/offset values"""
max_vals = [mag_samples[0][0], mag_samples[2][1], mag_samples[3][2]]
min_vals = [mag... |
java | public @CheckForNull <U extends T> U get(@Nonnull Class<U> type) {
for (T ext : this)
if(ext.getClass()==type)
return type.cast(ext);
return null;
} |
java | private boolean goToNextStartPosition() throws IOException {
int nextSpans1StartPosition;
while ((nextSpans1StartPosition = spans1.spans
.nextStartPosition()) != NO_MORE_POSITIONS) {
if (nextSpans1StartPosition == lastSpans2EndPosition) {
return true;
} else {
// clean up
... |
python | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(ExampleCollector, self).get_default_config()
config.update({
'path': 'example'
})
return config |
python | def filetypes_info_to_rows_header(infos, attrnames=None, header=None, flag_wrap_description=False,
description_width=40):
"""
Converts filetype information to a (multiline_rows, header) tuple that can be more easily be tabulated
**Attention** uses ReST syntax, using a "|br... |
python | def plot_vs_mass(dataset, vars, filename, bins=60):
""" Plot 2D marginalised posteriors of the 'vars' vs the dark matter mass.
We plot the one sigma, and two sigma filled contours. More contours can be plotted
which produces something more akin to a heatmap.
If one require more complicated plotting, it... |
java | @Override
public void cacheResult(CPDisplayLayout cpDisplayLayout) {
entityCache.putResult(CPDisplayLayoutModelImpl.ENTITY_CACHE_ENABLED,
CPDisplayLayoutImpl.class, cpDisplayLayout.getPrimaryKey(),
cpDisplayLayout);
finderCache.putResult(FINDER_PATH_FETCH_BY_UUID_G,
new Object[] { cpDisplayLayout.getUuid... |
python | def zoom_in_area(self, area):
""" zoom in area"""
x = area[0]
y = area[1]
level = x[2]
logger.debug("x = {}".format(x))
logger.debug("y = {}".format(y))
logger.debug("level = {}".format(level))
if level == y[2] and level > 0:
new_level = level ... |
java | public void open() throws IOException, ServerException {
if (hasBeenOpened()) {
throw new IOException("Attempt to open an already opened connection");
}
InetAddress allIPs[];
//depending on constructor used, we may already have streams
if (!have... |
python | def get_texts_box(texts, fs):
"""Approximation of multiple texts bounds"""
max_len = max(map(len, texts))
return (fs, text_len(max_len, fs)) |
java | private void restoreCoords(IntStack stack, Point2d[] src) {
for (int i = 0; i < stack.len; i++) {
int v = stack.xs[i];
atoms[v].getPoint2d().x = src[v].x;
atoms[v].getPoint2d().y = src[v].y;
}
} |
java | protected TypedParams<IncludedFieldsParams> parseIncludedFieldsParameters(final QueryParamsParserContext context) {
String sparseKey = RestrictedQueryParamsMembers.fields.name();
Map<String, Set<String>> sparse = filterQueryParamsByKey(context, sparseKey);
Map<String, Set<String>> temporarySpar... |
python | def discover_group(group, separator="/", exclude=None):
"""Produce a list of all services and their addresses in a group
A group is an optional form of namespace within the discovery mechanism.
If an advertised name has the form <group><sep><name> it is deemed to
belong to <group>. Note that the se... |
java | private void applyInstallExtension(DefaultInstalledExtension installedExtension, String namespace,
boolean dependency, Map<String, Object> properties, Map<String, ExtensionDependency> managedDependencies)
throws InstallException
{
// INSTALLED
installedExtension.setInstalled(true, na... |
python | def html_print_single_text(self, catalog, cdli_number, destination):
"""
Prints text_file in html.
:param catalog: CDLICorpus().catalog
:param cdli_number: which text you want printed
:param destination: where you wish to save the HTML data
:return: output in html_file.ht... |
java | public static Function getBuiltinFunction(final String name) {
if (name.equals("sin")) {
return builtinFunctions[INDEX_SIN];
} else if (name.equals("cos")) {
return builtinFunctions[INDEX_COS];
} else if (name.equals("tan")) {
return builtinFunctions[INDEX_TA... |
java | void dump(java.io.PrintStream out) {
if (fFTable.length == 0) {
// There is no table. Fail early for testing purposes.
throw new NullPointerException();
}
out.println("RBBI Data Wrapper dump ...");
out.println();
out.println("Forward State Table");
... |
python | def get_vnetwork_dvs_output_vnetwork_dvs_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_dvs = ET.Element("get_vnetwork_dvs")
config = get_vnetwork_dvs
output = ET.SubElement(get_vnetwork_dvs, "output")
vnetwor... |
java | public synchronized double getAverageMS()
{
double result = 0.0;
for( Double d : m_times.m_values )
{
result += d;
}
return result / m_times.size();
} |
java | private String getCertFromHeader(final HttpServletRequest request) {
val certHeaderValue = request.getHeader(sslClientCertHeader);
if (StringUtils.isBlank(certHeaderValue)) {
return null;
}
if ("(null)".equalsIgnoreCase(certHeaderValue)) {
return null;
}
... |
java | public static Path getWindupHome()
{
String windupHome = System.getProperty(WINDUP_HOME);
if (windupHome == null)
{
Path path = new File("").toPath();
LOG.warning("$WINDUP_HOME not set, using [" + path.toAbsolutePath().toString() + "] instead.");
return pa... |
python | def to_dict(self, include_null=True):
"""
Convert to dict.
"""
if include_null:
return dict(self.items())
else:
return {
attr: value
for attr, value in self.__dict__.items()
if not attr.startswith("_sa_")
... |
java | public ValidationWarning withWarnings(String... warnings) {
if (this.warnings == null) {
setWarnings(new com.amazonaws.internal.SdkInternalList<String>(warnings.length));
}
for (String ele : warnings) {
this.warnings.add(ele);
}
return this;
} |
java | public final void mDURATION() throws RecognitionException {
try {
int _type = DURATION;
int _channel = DEFAULT_TOKEN_CHANNEL;
// druidG.g:616:9: ( ( 'DURATION' ) )
// druidG.g:616:11: ( 'DURATION' )
{
// druidG.g:616:11: ( 'DURATION' )
// druidG.g:616:12: 'DURATION'
{
match("DURATION");
... |
java | @Deprecated
public static int normalize(char[] src,int srcStart, int srcLimit,
char[] dest,int destStart, int destLimit,
Mode mode, int options) {
CharBuffer srcBuffer = CharBuffer.wrap(src, srcStart, srcLimit - srcStart);
CharsAppenda... |
python | def createCluster(self, clusterName, machineNames="", tcpClusterPort=""):
"""
Creating a new cluster involves defining a clustering protocol that
will be shared by all server machines participating in the cluster.
All server machines that are added to the cluster must be
register... |
java | public static int compare(int char32a, String str2, int options) {
return internalCompare(UTF16.valueOf(char32a), str2, options);
} |
java | public static Optional<SoyRuntimeType> getUnboxedType(SoyType soyType) {
// Optional is immutable so Optional<Subclass> can always be safely cast to Optional<SuperClass>
@SuppressWarnings({"unchecked", "rawtypes"})
Optional<SoyRuntimeType> typed = (Optional) primitiveTypeCache.getUnchecked(soyType);
ret... |
java | static long durationInNanos(long duration, @Nullable TimeUnit unit) {
return (unit == null) ? UNSET_INT : unit.toNanos(duration);
} |
python | def filter_by_status(weather_list, status, weather_code_registry):
"""
Filters out from the provided list of *Weather* objects a sublist of items
having a status corresponding to the provided one. The lookup is performed
against the provided *WeatherCodeRegistry* object.
:param weathers: a list of ... |
python | def get_text(self, position_from, position_to):
"""
Return text between *position_from* and *position_to*
Positions may be positions or 'sol', 'eol', 'sof', 'eof' or 'cursor'
"""
cursor = self.__select_text(position_from, position_to)
text = to_text_string(cursor.se... |
java | @Override
public final void setStringProperty(String name, String value) throws JMSException
{
setProperty(name,value);
} |
python | def _setProperty(self, _type, data, win=None, mask=None):
"""
Send a ClientMessage event to the root window
"""
if not win:
win = self.root
if type(data) is str:
dataSize = 8
else:
data = (data+[0]*(5-len(data)))[:5]
dataSiz... |
python | def from_bytes(cls, bitstream):
r'''
Parse the given packet and update properties accordingly
>>> data_hex = ('80000000'
... '6e000000004811402a0086400001ffff'
... '000000000000000a2a02000000000000'
... '0000000000000000'
... ... |
java | protected PExp patternToExp(PPattern pattern, IPogAssistantFactory af,
UniqueNameGenerator unq)
{
PatternToExpVisitor visitor = new PatternToExpVisitor(unq, af);
try
{
return pattern.apply(visitor);
} catch (AnalysisException e)
{
return null;
}
} |
python | def datasets_create_new(self, dataset_new_request, **kwargs): # noqa: E501
"""Create a new dataset # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_create_new(dataset_new_re... |
python | def __execute_bsh(self, instr):
"""Execute BSH instruction.
"""
op0_val = self.read_operand(instr.operands[0])
op1_val = self.read_operand(instr.operands[1])
op1_size = instr.operands[1].size
# Check sign bit.
if extract_sign_bit(op1_val, op1_size) == 0:
... |
java | public static Object invokeGroovyObjectInvoker(MissingMethodException e, Object receiver, String name, Object[] args) {
if (e instanceof MissingMethodExecutionFailed) {
throw (MissingMethodException)e.getCause();
} else if (receiver.getClass() == e.getType() && e.getMethod().equals(name)) {
... |
python | def deprecated(will_be=None, on_version=None, name=None):
"""
Function decorator that warns about deprecation upon function invocation.
:param will_be: str representing the target action on the deprecated function
:param on_version: tuple representing a SW version
:param name: name of the entity to ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.