language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def finish_init(environment, start_web, create_sysadmin, log_syslog=False,
do_install=True, quiet=False, site_url=None, interactive=False,
init_db=True):
"""
Common parts of create and init: Install, init db, start site, sysadmin
"""
if not init_db:
start_web = Fa... |
python | def add (self, defn):
"""Adds the given Command Definition to this Command Dictionary."""
self[defn.name] = defn
self.colnames[defn.name] = defn |
python | def register_model_converter(model, name=None, field='pk', base=IntConverter, queryset=None):
"""
Registers a custom path converter for a model.
:param model: a Django model
:param str name: name to register the converter as
:param str field: name of the lookup field
:param base: base path conv... |
java | OutputStream writeChannel(int channel)
throws IOException
{
while (os != null) {
boolean canWrite = false;
synchronized (WRITE_LOCK) {
if (!isWriteLocked) {
isWriteLocked = true;
canWrite = true;
}
... |
java | public static void parkUntil(Object blocker, long deadline) {
Thread t = Thread.currentThread();
setBlocker(t, blocker);
U.park(true, deadline);
setBlocker(t, null);
} |
java | public static double[][] circleEndForLineVectorAlgebra(double x1, double y1,
double x2, double y2, double radius) {
double[][] result = new double[2][];
result[0] = new double[2];
result[1] = new double[2];
double [] baseVector = {x2-x1, y2-y1};
double baseVectorLenght = Math.sqrt(baseVector[... |
python | def decode_index_value(self, index, value):
"""
Decodes a secondary index value into the correct Python type.
:param index: the name of the index
:type index: str
:param value: the value of the index entry
:type value: str
:rtype str or int
"""
if... |
java | public static void sendAttachmentFile(final String uri) {
dispatchConversationTask(new ConversationDispatchTask() {
@Override
protected boolean execute(Conversation conversation) {
if (TextUtils.isEmpty(uri)) {
return false; // TODO: add error message
}
CompoundMessage message = new CompoundMes... |
python | def plat_specific_errors(*errnames):
"""Return error numbers for all errors in errnames on this platform.
The 'errno' module contains different global constants depending on
the specific platform (OS). This function will return the list of
numeric values for a given list of potential names.
"""
... |
python | def clear_step_handler_by_chat_id(self, chat_id):
"""
Clears all callback functions registered by register_next_step_handler().
:param chat_id: The chat for which we want to clear next step handlers
"""
self.next_step_handlers[chat_id] = []
if self.next_step_saver is no... |
java | @Nullable
public static URL getAsURL (@Nullable final String sURL, final boolean bWhine)
{
if (StringHelper.hasText (sURL))
try
{
return new URL (sURL);
}
catch (final MalformedURLException ex)
{
// fall-through
if (bWhine && GlobalDebug.isDebugMode ())
... |
python | def get_all_counters(obj, instance_list=None):
'''
Get the values for all counters available to a Counter object
Args:
obj (str):
The name of the counter object. You can get a list of valid names
using the ``list_objects`` function
instance_list (list):
... |
python | def filter_t(func):
"""
Transformation for Sequence.filter
:param func: filter function
:return: transformation
"""
return Transformation('filter({0})'.format(name(func)),
partial(filter, func),
{ExecutionStrategies.PARALLEL}) |
java | public void throwDOMException(short code, String msg)
{
String themsg = XSLMessages.createMessage(msg, null);
throw new DOMException(code, themsg);
} |
java | public static <T> T newInstance(Settings settings, Key<String> key) throws ServiceLocationException
{
// Workaround for compiler bug (#6302954)
return Factories.<T>newInstance(settings, key, Thread.currentThread().getContextClassLoader());
} |
python | def get_renderers(self):
"""Optionally block Browsable API rendering. """
renderers = super(WithDynamicViewSetMixin, self).get_renderers()
if settings.ENABLE_BROWSABLE_API is False:
return [
r for r in renderers if not isinstance(r, BrowsableAPIRenderer)
]... |
java | public static BoundedOverlay getBoundedOverlay(TileDao tileDao, float density) {
BoundedOverlay overlay = null;
if (tileDao.isGoogleTiles()) {
overlay = new GoogleAPIGeoPackageOverlay(tileDao);
} else {
overlay = new GeoPackageOverlay(tileDao, density);
}
... |
java | public Period plusYears(int years) {
if (years == 0) {
return this;
}
int[] values = getValues(); // cloned
getPeriodType().addIndexedField(this, PeriodType.YEAR_INDEX, values, years);
return new Period(values, getPeriodType());
} |
java | public void pauseJob(JobKey jobKey, T jedis) throws JobPersistenceException {
for (OperableTrigger trigger : getTriggersForJob(jobKey, jedis)) {
pauseTrigger(trigger.getKey(), jedis);
}
} |
python | def backtrack(self, source):
"""Given a unique key in the store, recreate original source"""
key = self.get_tok(source)
s = self[key]()
meta = s.metadata['original_source']
cls = meta['cls']
args = meta['args']
kwargs = meta['kwargs']
cls = import_name(cls... |
java | public static <K, V> Map<K, V> checkNotNullOrEmpty(Map<K, V> arg, String argName) throws NullPointerException,
IllegalArgumentException {
Preconditions.checkNotNull(arg, argName);
checkArgument(!arg.isEmpty(), argName,... |
python | def drop(self):
"""Drop the table from the database.
Deletes both the schema and all the contents within it.
"""
with self.db.lock:
if self.exists:
self._threading_warn()
self.table.drop(self.db.executable, checkfirst=True)
sel... |
python | def assign_to_series(self, name, series_type, item):
"""Assign name to item converted to the given series_type."""
if series_type == "(":
self.add_def(name + " = _coconut.tuple(" + item + ")")
elif series_type == "[":
self.add_def(name + " = _coconut.list(" + item + ")")
... |
java | public DConnection findByRefreshToken(java.lang.String refreshToken) {
return queryUniqueByField(null, DConnectionMapper.Field.REFRESHTOKEN.getFieldName(), refreshToken);
} |
python | def to_table_data(self):
"""
:raises ValueError:
:raises pytablereader.error.ValidationError:
"""
self._validate_source_data()
header_list = []
for json_record in self._buffer:
for key in json_record:
if key not in header_list:
... |
java | public static Interval invert(Interval i) {
byte iLabel = (byte) (OCTAVE - (i.getLabel()%OCTAVE));
byte iQuality = (byte) -i.getQuality();
byte iOrder = (byte) -i.getDirection();
return new Interval(iLabel, iQuality, iOrder);
} |
java | public static Color[] redblue(int n, float alpha) {
Color[] palette = new Color[n];
for (int i = 0; i < n; i++) {
palette[i] = new Color((float) Math.sqrt((i + 1.0f) / n), 0.0f, (float) Math.sqrt(1 - (i + 1.0f) / n), alpha);
}
return palette;
} |
python | def fft(a, n=None, axis=-1, norm=None):
"""
Compute the one-dimensional discrete Fourier Transform.
This function computes the one-dimensional *n*-point discrete Fourier
Transform (DFT) with the efficient Fast Fourier Transform (FFT)
algorithm [CT].
Parameters
----------
a : array_like... |
python | def find_n75(contig_lengths_dict, genome_length_dict):
"""
Calculate the N75 for each strain. N75 is defined as the largest contig such that at least 3/4 of the total
genome size is contained in contigs equal to or larger than this contig
:param contig_lengths_dict: dictionary of strain name: reverse-so... |
python | def __crawler_start(self):
"""Spawn the first X queued request, where X is the max threads option.
Note:
The main thread will sleep until the crawler is finished. This enables
quiting the application using sigints (see http://stackoverflow.com/a/11816038/2491049).
Note:... |
python | def get_all_usb_devices(idVendor, idProduct):
""" Returns a list of all the usb devices matching the provided vendor ID and product ID."""
all_dev = list(usb.core.find(find_all = True, idVendor = idVendor, idProduct = idProduct))
for dev in all_dev:
try:
dev.detach_ke... |
python | def _parse_query_key(self, key, val, is_escaped):
"""
Strips query modifier from key and call's the appropriate value modifier.
Args:
key (str): Query key
val: Query value
Returns:
Parsed query key and value.
"""
if key.endswith('__co... |
python | def receive(self, **kwargs):
"""
A decorator for connecting receivers to this signal. Used by passing in the
keyword arguments to connect::
@post_save.receive(sender=MyModel)
def signal_receiver(sender, **kwargs):
...
"""
def _decorator(f... |
python | def order_market_buy(self, **params):
"""Send in a new market buy order
:param symbol: required
:type symbol: str
:param quantity: required
:type quantity: decimal
:param newClientOrderId: A unique id for the order. Automatically generated if not sent.
:type newC... |
python | def setup_ci():
# type: () -> None
""" Setup AppEngine SDK on CircleCI """
gcloud_path = shell.run('which gcloud', capture=True).stdout.strip()
sdk_path = normpath(join(gcloud_path, '../../platform/google_appengine'))
gcloud_cmd = gcloud_path + ' --quiet'
if not exists(sdk_path):
log.in... |
java | private void load(final String key, final String value, final String location) {
// Recursive bit
if (INCLUDE.equals(key)) {
load(parseStringArray(value));
} else {
backing.put(key, value);
if ("yes".equals(value) || "true".equals(value)) {
booleanBacking.add(key);
} else {
booleanBacking.rem... |
python | def encoding_and_executable(notebook, metadata, ext):
"""Return encoding and executable lines for a notebook, if applicable"""
lines = []
comment = _SCRIPT_EXTENSIONS.get(ext, {}).get('comment')
jupytext_metadata = metadata.get('jupytext', {})
if ext not in ['.Rmd', '.md'] and 'executable' in jupyt... |
java | @NullSafe
@SuppressWarnings("unchecked")
public static <T> T[] asArray(Iterable<T> iterable, Class<T> componentType) {
List<T> arrayList = new ArrayList<>();
for (T element : CollectionUtils.nullSafeIterable(iterable)) {
arrayList.add(element);
}
return arrayList.toArray((T[]) Array.newInst... |
python | def _do_cron():
"""Handles the cron request to github to check for new pull requests. If
any are found, they are run *sequentially* until they are all completed.
"""
if not args["cron"]:
return
if ("enabled" in db and not db["enabled"]) or "enabled" not in db:
warn("The CI serve... |
java | protected String buildUrl(AbstractBaseRequest request) throws AbstractCosException {
String endPoint = this.config.getCosEndPoint();
int appId = this.cred.getAppId();
String bucketName = request.getBucketName();
String cosPath = request.getCosPath();
cosPath = CommonPathUtils.encodeRemotePath(cosPath);
retu... |
python | def make_parts_for(self, field_name, field_data):
"""Create the relevant parts for this field
Args:
field_name (str): Short field name, e.g. VAL
field_data (FieldData): Field data object
"""
typ = field_data.field_type
subtyp = field_data.field_subtype
... |
java | public <T> T findEntity(Class<T> clazz, Object... id) {
String executeSql = MirageUtil.buildSelectSQL(null, beanDescFactory, entityOperator, clazz, nameConverter);
return sqlExecutor.getSingleResult(clazz, executeSql, id);
} |
java | public static Vector2i convert(Tuple2D<?> tuple) {
if (tuple instanceof Vector2i) {
return (Vector2i) tuple;
}
return new Vector2i(tuple.getX(), tuple.getY());
} |
java | public void release()
{
for(String name : all)
{
allColumnFamilyMetrics.get(name).remove(Metrics.defaultRegistry().allMetrics().get(factory.createMetricName(name)));
Metrics.defaultRegistry().removeMetric(factory.createMetricName(name));
}
readLatency.release(... |
java | public boolean stopCriterionSatisfied(){
int i = 0;
while (i < stopCriteria.size() && !stopCriteria.get(i).searchShouldStop(search)) {
i++;
}
return i < stopCriteria.size();
} |
python | def init_report(self, reporter=None):
"""Initialize the report instance."""
self.options.report = (reporter or self.options.reporter)(self.options)
return self.options.report |
python | def fraction_visited(source, sink, waypoint, msm):
"""
Calculate the fraction of times a walker on `tprob` going from `sources`
to `sinks` will travel through the set of states `waypoints` en route.
Computes the conditional committors q^{ABC^+} and uses them to find the
fraction of paths mentioned ... |
python | def issorted(list_, op=operator.le):
"""
Determines if a list is sorted
Args:
list_ (list):
op (func): sorted operation (default=operator.le)
Returns:
bool : True if the list is sorted
"""
return all(op(list_[ix], list_[ix + 1]) for ix in range(len(list_) - 1)) |
python | def validate_target(self, target):
"""Make sure that the specified target only contains architectures that we know about."""
archs = target.split('/')
for arch in archs:
if not arch in self.archs:
return False
return True |
java | public Long rankReverse(final String member) {
return doWithJedis(new JedisCallable<Long>() {
@Override
public Long call(Jedis jedis) {
return jedis.zrevrank(getKey(), member);
}
});
} |
java | public void put(String url, HttpResponse response, Map<String, Object> headers, File file) {
HttpPut methodPut = new HttpPut(url);
HttpEntity multipart = buildBodyWithFile(file);
methodPut.setEntity(multipart);
getResponse(url, response, methodPut, headers);
} |
java | @Override
public int getRemoteTeamId() {
int penalty = Timing.getInstance().REMOTE_ACCESS_PENALTY;
log.trace("[getRemoteTeamId] Waiting {} cycles", penalty);
turnsControl.waitTurns(penalty, "Get Remote Team Id");
Robot neighbour = world.getNeighbour(this.robot);
if (neighbour != null) {
return neighbour.g... |
java | public static CommerceSubscriptionEntry findByG_U_Last(long groupId,
long userId,
OrderByComparator<CommerceSubscriptionEntry> orderByComparator)
throws com.liferay.commerce.exception.NoSuchSubscriptionEntryException {
return getPersistence()
.findByG_U_Last(groupId, userId, orderByComparator);
} |
java | private static void generateProtobufDefinedForField(StringBuilder code, FieldElement field, Set<String> enumNames) {
code.append("@").append(Protobuf.class.getSimpleName()).append("(");
String fieldType = fieldTypeMapping.get(getTypeName(field));
if (fieldType == null) {
if (en... |
python | def moveTab(self, fromIndex, toIndex):
"""
Moves the tab from the inputed index to the given index.
:param fromIndex | <int>
toIndex | <int>
"""
try:
item = self.layout().itemAt(fromIndex)
self.layout().insertItem(toIndex, item.... |
java | void updateInternal() {
// HSuperColumnImpl needs a refactor, this construction is lame.
// the value serializer is not used in HSuperColumnImpl, so this is safe for name
if ( !subColumns.isEmpty() ) {
log.debug("Adding column {} for key {} and cols {}", new Object[]{getCurrentSuperColumn(), getCu... |
python | def server_inspect_exception(self, req_event, rep_event, task_ctx, exc_info):
"""Called when an exception has been raised in the code run by ZeroRPC"""
# Hide the zerorpc internal frames for readability, for a REQ/REP or
# REQ/STREAM server the frames to hide are:
# - core.ServerBase._a... |
java | public FindingFilter withAutoScalingGroups(String... autoScalingGroups) {
if (this.autoScalingGroups == null) {
setAutoScalingGroups(new java.util.ArrayList<String>(autoScalingGroups.length));
}
for (String ele : autoScalingGroups) {
this.autoScalingGroups.add(ele);
... |
java | static double computeDynamicTimeWarpingDistance(
DoubleTuple u, DoubleTuple v)
{
int m = u.getSize();
int n = v.getSize();
double matrix[][] = threadLocalMatrix.get();
if (matrix.length < m || matrix[0].length < n)
{
matrix = new double[m][n];
... |
python | def ces(subsystem, mechanisms=False, purviews=False, cause_purviews=False,
effect_purviews=False, parallel=False):
"""Return the conceptual structure of this subsystem, optionally restricted
to concepts with the mechanisms and purviews given in keyword arguments.
If you don't need the full |CauseEf... |
java | public static long longVal(String val, long defaultValue) {
try {
return NumberUtils.createNumber(val).longValue();
} catch (Exception e) {
log.warn("longVal(String, int) throw {}, return defaultValue = {}", e, defaultValue);
return defaultValue;
}
} |
java | private void findMatches(Match match, int n) throws IOException {
if (n > 0) {
int largestMatchingEndPosition = match.endPosition();
Set<Integer> list = ignoreItem.getFullEndPositionList(spans.docID(),
match.endPosition());
// try to find matches with existing queue
if (!queueSpans... |
python | def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
content_lifecycle_environments
/capsules/<id>/content/lifecycle_environments
content_sync
/capsules/<id>/content/sync
... |
python | def pct_decode(s):
"""
Return the percent-decoded version of string s.
>>> pct_decode('%43%6F%75%63%6F%75%2C%20%6A%65%20%73%75%69%73%20%63%6F%6E%76%69%76%69%61%6C')
'Coucou, je suis convivial'
>>> pct_decode('')
''
>>> pct_decode('%2525')
'%25'
"""
if s is None:
return N... |
python | def set_light_state_raw(self, hue, saturation, brightness, kelvin,
bulb=ALL_BULBS, timeout=None):
"""
Sets the (low-level) light state of one or more bulbs.
"""
with _blocking(self.lock, self.light_state, self.light_state_event,
timeout)... |
java | private static MessageElement getMapKVMessageElements(String name, MapType mapType) {
MessageElement.Builder ret = MessageElement.builder();
ret.name(name);
DataType keyType = mapType.keyType();
Builder fieldBuilder = FieldElement.builder().name("key").tag(1);
fieldBuilder... |
java | @Override
public void clearCache() {
entityCache.clearCache(CommercePriceListImpl.class);
finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
} |
python | def _create_service_nwk(self, tenant_id, tenant_name, direc):
"""Function to create the service in network in DCNM. """
net_dict = self.retrieve_dcnm_net_info(tenant_id, direc)
net = utils.Dict2Obj(net_dict)
subnet_dict = self.retrieve_dcnm_subnet_info(tenant_id, direc)
subnet = ... |
python | def kelvin2rgb(temperature):
"""
Converts from Kelvin temperature to an RGB color.
Algorithm credits: |tannerhelland|_
"""
# range check
if temperature < 1000:
temperature = 1000
elif temperature > 40000:
temperature = 40000
tmp_internal = temperature / 100.0
# red... |
python | def _stage(self, accepted, count=0):
"""This is a repeated state in the state removal algorithm"""
new5 = self._combine_rest_push()
new1 = self._combine_push_pop()
new2 = self._combine_push_rest()
new3 = self._combine_pop_rest()
new4 = self._combine_rest_rest()
ne... |
java | @Override
public Iterable<Tag> httpLongRequestTags(@Nullable HttpServletRequest request, @Nullable Object handler) {
return Arrays.asList(WebMvcTags.method(request), WebMvcTags.uri(request, null));
} |
java | @Modified
protected void modified(Map<String, Object> map) {
String filterString = OpentracingConfiguration.getServerSkipPattern();
updateFilters(filterString);
} |
python | def request_sensor_sampling(self, req, msg):
"""Configure or query the way a sensor is sampled.
Sampled values are reported asynchronously using the #sensor-status
message.
Parameters
----------
name : str
Name of the sensor whose sampling strategy to query ... |
java | public static <K, V> FIFOCache<K, V> newFIFOCache(int capacity, long timeout){
return new FIFOCache<K, V>(capacity, timeout);
} |
python | def get_events(self, from_=None, to=None):
"""Query a slice of the events.
Events are always returned in the order the were added.
Does never throw EventOrderError because it is hard to detect
from an append-only file.
Parameters:
from_ -- if not None, return only ev... |
python | def _grid_widgets(self):
"""Put the widgets in the correct position based on self.__compound."""
orient = str(self._scale.cget('orient'))
self._scale.grid(row=2, column=2, sticky='ew' if orient == tk.HORIZONTAL else 'ns',
padx=(0, self.__entryscalepad) if self.__compound... |
java | public synchronized boolean startUpgrade() throws IOException {
if(upgradeState) { // upgrade is already in progress
assert currentUpgrades != null :
"UpgradeManagerDatanode.currentUpgrades is null.";
UpgradeObjectDatanode curUO = (UpgradeObjectDatanode)currentUpgrades.first();
curUO.sta... |
java | private void freeAllocatedSpace(java.util.Collection sortedFreeSpaceList)
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this,
cclass,
"freeAllocatedSpace",
new Object[] { new Integer(sortedFreeSp... |
python | def average_temperature(self, unit='kelvin'):
"""Returns the average value in the temperature series
:param unit: the unit of measure for the temperature values. May be
among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*'
:type unit: str
:returns: a float
... |
python | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'values') and self.values is not None:
_dict['values'] = [x._to_dict() for x in self.values]
if hasattr(self, 'pagination') and self.pagination is not None:
_di... |
java | @Override
public DescribeSnapshotCopyGrantsResult describeSnapshotCopyGrants(DescribeSnapshotCopyGrantsRequest request) {
request = beforeClientExecution(request);
return executeDescribeSnapshotCopyGrants(request);
} |
java | public void marshall(LocationListEntry locationListEntry, ProtocolMarshaller protocolMarshaller) {
if (locationListEntry == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(locationListEntry.getLocatio... |
python | def record_close(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /record-xxxx/close API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Data-Object-Lifecycle#API-method%3A-%2Fclass-xxxx%2Fclose
"""
return DXHTTPRequest('/%s/close' % object_id... |
java | @Override
public SortedSet<String> getDomainNames(String name) {
if ( name.length() < 4)
throw new IllegalArgumentException("Can't interpret IDs that are shorter than 4 residues!");
String url = String.format("%srepresentativeDomains?cluster=%s&structureId=%s",
base, cutoff, name);
return requestRepresen... |
java | public void lock() {
boolean wasInterrupted = false;
while (true) {
try {
impl.lockInterruptibly();
if (wasInterrupted) {
Thread.currentThread().interrupt();
}
return;
}
catch (Interru... |
python | async def _client_ready_async(self):
"""Determine whether the client is ready to start sending messages.
To be ready, the connection must be open and authentication complete,
The Session, Link and MessageSender must be open and in non-errored
states.
:rtype: bool
:raises... |
python | def related_archives(self):
"""
The pathnames of the source distribution(s) for this requirement (a list of strings).
.. note:: This property is very new in pip-accel and its logic may need
some time to mature. For now any misbehavior by this property
shouldn... |
java | public List<Motion> findCameraMotions(Camera target , @Nullable List<Motion> storage ) {
if( storage == null )
storage = new ArrayList<>();
for (int i = 0; i < edges.size(); i++) {
Motion m = edges.get(i);
if( m.viewSrc.camera == target && m.viewDst.camera == target ) {
storage.add(m);
}
}
ret... |
python | def latcyl(radius, lon, lat):
"""
Convert from latitudinal coordinates to cylindrical coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/latcyl_c.html
:param radius: Distance of a point from the origin.
:type radius:
:param lon: Angle of the point from the XZ plane in radians... |
python | def require_directory(self):
"""Ensure directory path entered in dialog exist.
When the path does not exist, this function will ask the user if he
want to create it or not.
:raises: CanceledImportDialogError - when user choose 'No' in
the question dialog for creating direct... |
java | public <T extends Function> T addFunction(T function) {
addItem(function, functions, "functions");
return function;
} |
java | void encodeProperty(ByteArrayOutputStream baos, Object value) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "encodeProperty", new Object[]{baos, value});
if (value.equals(ApiJmsConstants.ON)) {
super.encodeProperty(baos, SHORT_ON);
}
... |
java | public EncodingState getEncodingStateFor(CharSequence string) {
int identityHashCode = System.identityHashCode(string);
Set<Encoder> result = null;
for (Map.Entry<Encoder, Set<Integer>> entry : encodingTagIdentityHashCodes.entrySet()) {
if (entry.getValue().contains(identityHashCode)... |
java | public KafkaMessage consumeMessage(String consumerGroupId, boolean consumeFromBeginning,
String topic) {
KafkaMsgConsumer kafkaConsumer = getKafkaConsumer(consumerGroupId, consumeFromBeginning);
return kafkaConsumer.consume(topic);
} |
python | def toList(variable, types=(basestring, int, float, )):
"""Converts a variable of type string, int, float to a list, containing the
variable as the only element.
:param variable: any python object
:type variable: (str, int, float, others)
:returns: [variable] or variable
"""
if isinstance(... |
java | private void moveIndex() {
int i = rightmostIndexBelowMax();
if (i >= 0) {
index[i] = index[i]+1;
for (int j = i+1; j<r; j++)
index[j] = index[j-1] + 1;
}
else hasNext = false;
} |
python | def augmentation_transform(self, data, label): # pylint: disable=arguments-differ
"""Override Transforms input data with specified augmentations."""
for aug in self.auglist:
data, label = aug(data, label)
return (data, label) |
python | def result(cls, ab, pa, pitch_list):
"""
At Bat Result
:param ab: at bat object(type:Beautifulsoup)
:param pa: atbat data for plate appearance
:param pitch_list: Pitching data
:return: pa result value(dict)
"""
atbat = OrderedDict()
atbat['ball_ct'... |
java | public int getFormatIndex(CellValueRecordInterface cell) {
ExtendedFormatRecord xfr = _xfRecords.get(cell.getXFIndex());
if (xfr == null) {
logger.log(POILogger.ERROR, "Cell " + cell.getRow() + "," + cell.getColumn()
+ " uses XF with index " + cell.getXFIndex() + ", but we do... |
python | def get_object_by_filename(self, request, filename):
"""
Returns owner object by filename (to be downloaded).
This can be used to implement custom permission checks.
:param request: HttpRequest
:param filename: File name of the downloaded object.
:return: owner object
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.