language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static DataDescriptor[] listMembers() {
if (disabled)
return null;
ModuleItem[] modItems = moduleRoot.children();
if (modItems == null)
return null;
DataDescriptor[] res = new DataDescriptor[modItems.length];
for (int i = 0; i < res.length; i++) {
... |
python | def serializable(obj: Any, on_filter: Callable[[Any, str], bool] = None) -> Any:
"""
Ensures the specified object is serializable, converting if necessary.
:param obj: the object to use.
:param on_filter: optional function that can be used to filter which
properties on the object ... |
java | public static SenseDocument makeSenseDocument(SenseIdValue senseIdValue,
List<MonolingualTextValue> glosses,
List<StatementGroup> statementGroups) {
return factory.getSenseDocument(senseIdValue, glosses, statementGroups, 0);
} |
python | def start(self):
"""
Starts the connection
"""
self.__stop = False
self._queue.start()
self._zk.start() |
java | public static TypeAnnotationPosition
localVariable(final List<TypePathEntry> location,
final JCLambda onLambda,
final int pos) {
return new TypeAnnotationPosition(TargetType.LOCAL_VARIABLE, pos,
Integer.MIN_VALUE, onLa... |
java | public static void encode(File file) throws IOException {
if (!file.exists()) {
System.exit(0);
}
else {
byte[] decoded = readBytes(file);
char[] encoded = encode(decoded);
writeChars(file, encoded);
}
file = null;
} |
python | def generate_sample_cfn_module(env_root, module_dir=None):
"""Generate skeleton CloudFormation sample module."""
if module_dir is None:
module_dir = os.path.join(env_root, 'sampleapp.cfn')
generate_sample_module(module_dir)
for i in ['stacks.yaml', 'dev-us-east-1.env']:
shutil.copyfile(
... |
python | def set_partial_filling(self, propname):
r"""
Define which pore filling model to apply.
Parameters
----------
propname : string
Dictionary key on the physics object(s) containing the pore
filling model(s) to apply.
Notes
-----
It ... |
java | public static double toAnnualReturnFromGrowthRate(double growthRate, CalendarDateUnit growthRateUnit) {
double tmpGrowthRateUnitsPerYear = growthRateUnit.convert(CalendarDateUnit.YEAR);
return PrimitiveMath.EXPM1.invoke(growthRate * tmpGrowthRateUnitsPerYear);
} |
python | def regex_find_txt(pattern, text, default=""):
"""""
RegEx search for pattern in text. Will try to match the data type of the "default" value
or return the default value if no match is found.
This is to parse IOS config like below:
regex_find_txt(r"remote-as (65000)", "neighbor 10.0.0.1 remote-as 65... |
java | public EClass getIfcSectionalAreaIntegralMeasure() {
if (ifcSectionalAreaIntegralMeasureEClass == null) {
ifcSectionalAreaIntegralMeasureEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(735);
}
return ifcSectionalAreaIntegralMeasureEClass;
} |
python | def upsert(self, row, keys, ensure=None, types=None):
"""An UPSERT is a smart combination of insert and update.
If rows with matching ``keys`` exist they will be updated, otherwise a
new row is inserted in the table.
::
data = dict(id=10, title='I am a banana!')
... |
java | public static <T> Optional<T> find(final Iterable<? extends T> iterable, final Predicate<? super T> predicate) {
checkNotNull(iterable, "iterable may not be null");
checkNotNull(predicate, "the predicate may not be null");
for (T t : iterable) {
if (predicate.test(t)) {
... |
java | public com.google.protobuf.Duration getRetryDelay() {
return retryDelay_ == null ? com.google.protobuf.Duration.getDefaultInstance() : retryDelay_;
} |
python | def get_table_service_properties(self, timeout=None):
'''
Gets the properties of a storage account's Table service, including
logging, analytics and CORS rules.
:param int timeout:
The server timeout, expressed in seconds.
:return: The table service properties.
... |
python | def exclude(self):
"""
Custom descriptor for exclude since there is no get_exclude method to
be overridden
"""
exclude = self.VERSIONED_EXCLUDE
if super(VersionedAdmin, self).exclude is not None:
# Force cast to list as super exclude could return a tuple
... |
java | @Override
public java.util.Iterator<com.google.api.ads.admanager.axis.v201805.User> iterator() {
if (results == null) {
return java.util.Collections.<com.google.api.ads.admanager.axis.v201805.User>emptyIterator();
}
return java.util.Arrays.<com.google.api.ads.admanager.axis.v2018... |
java | public Version putVersionedWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper)
throws ObsoleteVersionException {
validateTimeout(requestWrapper.getRoutingTimeoutInMs());
for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {
try {
... |
java | public static String evaluateName(final String _typeName,
final String _name)
{
final StringBuilder ret = new StringBuilder();
ret.append(_typeName).append(":").append(_name).toString();
return ret.toString();
} |
java | void checkAccessibleType(Env<AttrContext> env, Type t) {
accessibilityChecker.visit(t, env);
} |
java | public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
... |
python | def listdir(self, path, **kwargs):
"""Return a list containing names of files in the given path"""
statuses = self.list_status(path, **kwargs)
if len(statuses) == 1 and statuses[0].pathSuffix == '' and statuses[0].type == 'FILE':
raise NotADirectoryError('Not a directory: {!r}'.forma... |
python | def collect(self):
"""
Collect and publish S.M.A.R.T. attributes
"""
devices = re.compile(self.config['devices'])
for device in os.listdir('/dev'):
if devices.match(device):
command = [self.config['bin'], "-A", os.path.join('/dev',
... |
python | def invite(self, username):
"""Invite the user to join this team.
This returns a dictionary like so::
{'state': 'pending', 'url': 'https://api.github.com/teams/...'}
:param str username: (required), user to invite to join this team.
:returns: dictionary
"""
... |
java | @Override
public CommerceTaxMethod fetchByG_E(long groupId, String engineKey) {
return fetchByG_E(groupId, engineKey, true);
} |
java | @Override
public List<DecisionService> getDecisionService() {
return drgElement.stream().filter(DecisionService.class::isInstance).map(DecisionService.class::cast).collect(Collectors.toList());
} |
java | @Override
public GetConnectorDefinitionResult getConnectorDefinition(GetConnectorDefinitionRequest request) {
request = beforeClientExecution(request);
return executeGetConnectorDefinition(request);
} |
java | private PluralAttribute<? super X, ?, ?> getPluralAttriute(String paramName)
{
if (superClazzType != null)
{
return ((AbstractManagedType<? super X>) superClazzType).getDeclaredPluralAttribute(paramName);
}
return null;
} |
python | def get_sec2gos(sortobj):
"""Initialize section_name2goids."""
sec_gos = []
for section_name, nts in sortobj.get_desc2nts_fnc(hdrgo_prt=True)['sections']:
sec_gos.append((section_name, set(nt.GO for nt in nts)))
return cx.OrderedDict(sec_gos) |
java | public static Iterable<MutableLongTuple> colexicographicalIterable(
LongTuple min, LongTuple max)
{
return iterable(Order.COLEXICOGRAPHICAL,
min, max);
} |
python | def get_filetype_from_buffer(buf, max_lines=5):
"""
Scan the buffer for modelines and return filetype if one is found.
"""
lines = buf.splitlines()
for l in lines[-1:-max_lines-1:-1]:
ret = get_filetype_from_line(l)
if ret:
return ret
for i in range(max_lines, -1, -1)... |
python | def success_response(**data):
"""Return a generic success response."""
data_out = {}
data_out["status"] = "success"
data_out.update(data)
js = dumps(data_out, default=date_handler)
return Response(js, status=200, mimetype="application/json") |
java | public static <S, R> ObjectBinding<R> map(ObservableValue<S> source, Function<? super S, ? extends R> function) {
return map(source, function, null);
} |
java | @Deprecated
public <T> TypeSerializerSchemaCompatibility<T> resolveCompatibilityWithNested(
TypeSerializerSchemaCompatibility<?> outerCompatibility,
TypeSerializer<?>... newNestedSerializers) {
checkArgument(newNestedSerializers.length == nestedSnapshots.length,
"Different number of new serializers and ex... |
java | @XmlElementDecl(namespace = "http://www.opengis.net/citygml/relief/2.0", name = "ReliefFeature", substitutionHeadNamespace = "http://www.opengis.net/citygml/2.0", substitutionHeadName = "_CityObject")
public JAXBElement<ReliefFeatureType> createReliefFeature(ReliefFeatureType value) {
return new JAXBElement... |
java | public int getSelectorDomain()
{
if (tc.isEntryEnabled())
{
SibTr.entry(tc, "getSelectorDomain");
SibTr.exit(tc, "getSelectorDomain", new Integer(selectorDomain));
}
return selectorDomain;
} |
python | def to_array(self):
"""
Serializes this EncryptedCredentials to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(EncryptedCredentials, self).to_array()
array['data'] = u(self.data) # py2: type unicode, py3: type str... |
java | public boolean containsKey(Object key)
{
checkKey(key);
int keyLength = ((String)key).length();
if (keyLength >= MIN_LENGHT_CHECK)
{
if (MARK_CREATED.length() == keyLength &&
MARK_CREATED.equals(key))
{
return ((UIComponentBase... |
java | public static String compose (String key, Object... args)
{
StringBuilder buf = new StringBuilder();
buf.append(key);
buf.append('|');
for (int i = 0; i < args.length; i++) {
if (i > 0) {
buf.append('|');
}
// escape the string whil... |
python | def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ParticipantContext for this ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participan... |
python | def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths):
"""
Get the cached commit times for the combination of this parent_dir and relpaths
Return the commit assigned to this combination and the actual times!
"""
result = get_all_cached_commit_times(root_folder)
for item in resu... |
java | public static Connection connect(String url) throws IOException, InterruptedException {
Options options = new Options.Builder().server(url).build();
return createConnection(options, false);
} |
java | public static base_response update(nitro_service client, lbsipparameters resource) throws Exception {
lbsipparameters updateresource = new lbsipparameters();
updateresource.rnatsrcport = resource.rnatsrcport;
updateresource.rnatdstport = resource.rnatdstport;
updateresource.retrydur = resource.retrydur;
updat... |
java | public String serialize(Object o) {
ObjectMapper om = getObjectMapper();
try {
return om.writeValueAsString(o);
} catch (Exception e) {
throw new RuntimeException(e);
}
} |
java | public VnetGatewayInner updateVnetGateway(String resourceGroupName, String name, String vnetName, String gatewayName, VnetGatewayInner connectionEnvelope) {
return updateVnetGatewayWithServiceResponseAsync(resourceGroupName, name, vnetName, gatewayName, connectionEnvelope).toBlocking().single().body();
} |
java | @NullSafe
@SafeVarargs
public static <T> T getFirst(T... array) {
return getFirst(array, null);
} |
python | def relation_column(instance, fields):
'''
such as: user.username
such as: replies.content
'''
relation = getattr(instance.__class__, fields[0]).property
_field = getattr(instance, fields[0])
if relation.lazy == 'dynamic':
_field = _field.first()
return getattr(_field, fields[1])... |
python | def dump_as_json(record, output_file):
"""
Dump an relation record as a json value.
Arguments:
record -- A RelationRecord instance to dump.
output_file -- A file to output.
"""
def default_func(value):
"""
Default conversion for JSON value.
"""
if isi... |
java | @Override
public final synchronized void removePropertyChangeListener(
PropertyChangeListener listener) {
if (listener == null || changeSupport == null) {
return;
}
changeSupport.removePropertyChangeListener(listener);
} |
python | def _deserialize_encrypted_data_keys(stream):
# type: (IO) -> Set[EncryptedDataKey]
"""Deserialize some encrypted data keys from a stream.
:param stream: Stream from which to read encrypted data keys
:return: Loaded encrypted data keys
:rtype: set of :class:`EncryptedDataKey`
"""
(encrypted... |
java | public <T extends Actor> ActorRef actorOf(Class<T> actor, String path) {
return actorOf(Props.create(actor), path);
} |
java | public static int updateEncryptCert(Map<String, String> resData,
String encoding) {
return SDKUtil.getEncryptCert(resData, encoding);
} |
python | def filter_by_maf(min_maf=0.01):
"""
return function that filters by maf
(takes minimum maf, default is 0.01)
"""
def f(G, bim):
maf = 0.5 * G.mean(0)
maf[maf > 0.5] = 1.0 - maf[maf > 0.5]
Isnp = maf > min_maf
G_out = G[:, Isnp]
bim_out = bim[Isnp]... |
python | def maybe_infer_dtype_type(element):
"""Try to infer an object's dtype, for use in arithmetic ops
Uses `element.dtype` if that's available.
Objects implementing the iterator protocol are cast to a NumPy array,
and from there the array's type is used.
Parameters
----------
element : object
... |
python | def __get_ssl_context(cls, sslca=None):
"""Make an SSLConext for this Python version using public or sslca
"""
if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or
(version_info[0] == 3 and version_info[1] >= 4)):
logger.debug('SSL method ... |
java | private ThymeLeafTemplateImplementation getTemplateByFile(File templateFile) {
try {
return getTemplateByURL(templateFile.toURI().toURL());
} catch (MalformedURLException e) { //NOSONAR
// Ignored.
}
return null;
} |
python | def get_namespace_preorder( self, namespace_id_hash ):
"""
Given the hash(namesapce_id, sender_script_pubkey, reveal_addr) for a
namespace that is being imported, get its associated NAMESPACE_PREORDER
record.
Return the namespace preorder record on success.
Return None ... |
python | def GetAttribute(self, identifier):
"""Retrieves a specific attribute.
Args:
identifier (str): identifier of the attribute within the volume.
Returns:
VolumeAttribute: volume attribute or None if not available.
"""
if not self._is_parsed:
self._Parse()
self._is_parsed = Tru... |
python | def train(cluster_info, cluster_meta, feed_timeout=600, qname='input'):
"""Feeds Spark partitions into the shared multiprocessing.Queue.
Args:
:cluster_info: node reservation information for the cluster (e.g. host, executor_id, pid, ports, etc)
:cluster_meta: dictionary of cluster metadata (e.g. cluster_id... |
python | def chart(line, cell=None):
""" Generate charts with Google Charts. Use %chart --help for more details. """
parser = _commands.CommandParser(prog='%chart', description="""
Generate an inline chart using Google Charts using the data in a Table, Query, dataframe, or list.
Numerous types of charts are supported. Optio... |
java | private boolean loadPlugin(final String plugin) {
if (checkPlugin(plugin)) {
final Features pluginFeatures = pluginTable.get(plugin);
final Map<String, List<String>> featureSet = pluginFeatures.getAllFeatures();
for (final Map.Entry<String, List<String>> currentFeature : feat... |
python | def execute_show(self, show_command, delim=';'):
"""
Executes show-type commands on the CLI and returns parsable output usinng ';' as delimitor.
:param show_command: Show command to be executed
:param delim: Will use specific delimitor. Default: ';'
:raise pyPluribus.exceptions.... |
python | def _synthesize_multiple_c_extension(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize multiple text fragments, using the cew extension.
Return a tuple (anchors, total_time, num_chars).
:rtype: (bool, (list, :class:`~aeneas.exacttiming.TimeValue`, int... |
java | public synchronized Histogram getIntervalHistogram(Histogram histogramToRecycle) {
// Verify that replacement histogram can validly be used as an inactive histogram replacement:
validateFitAsReplacementHistogram(histogramToRecycle);
inactiveHistogram = (InternalHistogram) histogramToRecycle;
... |
java | @Override
public Object callWithNamedValues(PageContext pc, Key key, Struct args) throws PageException {
// first check variables
Object o = shadow.get(key);
if (o instanceof UDFPlus) {
return ((UDFPlus) o).callWithNamedValues(pc, key, args, false);
}
Member m = component.getMember(access, key, false, fa... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case XbasePackage.XCATCH_CLAUSE__EXPRESSION:
return getExpression();
case XbasePackage.XCATCH_CLAUSE__DECLARED_PARAM:
return getDeclaredParam();
}
return super.eGet(featureID, resolve, coreType)... |
python | def list(self, **kwargs):
"""
Returns a list of items in the database. Encrypted attributes are not
decrypted when listing items.
"""
response = self._new_response()
if self._check_supported_op('list', response):
self._call_ddb_method(self.table.scan, {}, res... |
python | def get_institution(self, **kwargs):
"""Get the dissertation institution."""
qualifier = kwargs.get('qualifier', '')
content = kwargs.get('content', '')
if qualifier == 'grantor':
return content
return None |
java | private void readLinks2DMTypes()
throws CacheReloadException
{
Connection con = null;
try {
final List<Long> values = new ArrayList<>();
con = Context.getConnection();
PreparedStatement stmt = null;
try {
stmt = con.prepareState... |
python | def planetType(temperature, mass, radius):
""" Returns the planet type as 'temperatureType massType'
"""
if mass is not np.nan:
sizeType = planetMassType(mass)
elif radius is not np.nan:
sizeType = planetRadiusType(radius)
else:
return None
return '{0} {1}'.format(plane... |
java | public String convertIfcFlowDirectionEnumToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
} |
python | def get_machine_states(self, machines):
"""Gets the state of several machines in a single operation.
in machines of type :class:`IMachine`
Array with the machine references.
return states of type :class:`MachineState`
Machine states, corresponding to the machines.
... |
python | def get_all_lines(self):
"""Return all lines of the SourceString as a list of SourceLine's."""
output = []
line = []
lineno = 1
for char in self.string:
line.append(char)
if char == '\n':
output.append(SourceLine(''.join(line), lineno))
... |
python | def activated(self, value):
"""
Setter for **self.__activated** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("activated", value)
... |
python | def count(self, name=None, **attrs):
r"""Number of descendants matching criteria.
:param Union[None,str] name: name of LaTeX expression
:param attrs: LaTeX expression attributes, such as item text.
:return: number of matching expressions
:rtype: int
>>> from TexSoup imp... |
java | public void setPsegName(String newPsegName) {
String oldPsegName = psegName;
psegName = newPsegName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.BPS__PSEG_NAME, oldPsegName, psegName));
} |
python | def _sampleHiddenStateTrajectory(self, obs, dtype=np.int32):
"""Sample a hidden state trajectory from the conditional distribution P(s | T, E, o)
Parameters
----------
o_t : numpy.array with dimensions (T,)
observation[n] is the nth observation
dtype : numpy.dtype, o... |
java | CodeChunk generateMsgGroupCode(MsgFallbackGroupNode node) {
Preconditions.checkState(placeholderNames.isEmpty(), "This class is not reusable.");
// Non-HTML {msg}s should be extracted into LetContentNodes and handled by jssrc.
Preconditions.checkArgument(node.getHtmlContext() == HtmlContext.HTML_PCDATA,
... |
python | def head(self, limit, partition=None, columns=None):
"""
Get the head records of a table or its partition.
:param limit: records' size, 10000 at most
:param partition: partition of this table
:param columns: the columns which is subset of the table columns
:type columns:... |
java | public void rollbackClientWrongInput(List articles, List persons)
{
log.info("rollbackClientWrongInput method was called");
ArticleManagerODMGLocal am = getArticleManager();
PersonManagerODMGLocal pm = getPersonManager();
am.storeArticles(articles);
pm.storePersons(pers... |
python | def each_object(collection):
"""Yields each object in the given ``collection``.
The objects are loaded from cache and failing that,
from disk."""
c_path = collection_path(collection)
paths = glob('%s/*.%s' % (c_path, _ext))
for path in paths:
yield load_object_at_path(path) |
python | def has_parent_gradebooks(self, gradebook_id):
"""Tests if the ``Gradebook`` has any parents.
arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook
return: (boolean) - ``true`` if the gradebook has parents,
``false`` otherwise
raise: NotFound - ``gradebook_id`` i... |
java | private static final String getString(CharacterIterator text, int start, int length) {
StringBuilder result = new StringBuilder(length);
int offset = text.getIndex();
text.setIndex(start);
for (int i = 0; i < length; i++) {
result.append(text.current());
text.next... |
java | private void seqeval() throws IOException {
final String metric = this.parsedArguments.getString("metric");
final String lang = this.parsedArguments.getString("language");
final String model = this.parsedArguments.getString("model");
final String testset = this.parsedArguments.getString("testset");
... |
java | static Point2d[] reorderCoords(Point2d[] coords, int[] order) {
Point2d[] neworder = new Point2d[coords.length];
for (int i = 0; i < order.length; i++)
neworder[order[i]] = coords[i];
return neworder;
} |
python | def exponential_chirp(npts=2000):
"""
Generates an exponential chirp.
:param npts: Number of samples.
:type npts: int
:returns: Generated signal
:rtype: numpy.ndarray
"""
time = np.linspace(0, 20, npts)
chirp = np.sin(2 * np.pi * 0.2 * (1.3 ** time - 1) / np.log(1.3))
return chi... |
python | def switch(self, name):
"""
Returns the switch with the provided ``name``.
If ``autocreate`` is set to ``True`` and no switch with that name
exists, a ``DISABLED`` switch will be with that name.
Keyword Arguments:
name -- A name of a switch.
"""
try:
... |
python | def perform_permissions_check(self, user, obj, perms):
""" Performs the permission check. """
return self.request.forum_permission_handler.can_lock_topics(obj, user) |
java | public final String getRangesAsString(final Status status) {
List<String> ranges = new ArrayList<String>();
List<Range> rangeList;
switch (status) {
case OK:
rangeList = okThresholdList;
break;
case WARNING:
rangeList = warningThresholdList;
... |
java | public List<String> getSynonyms(AnalyzedTokenReadings token) {
List<String> synonyms = new ArrayList<String>();
if(linguServices == null || token == null) {
return synonyms;
}
List<AnalyzedToken> readings = token.getReadings();
for (AnalyzedToken reading : readings) {
String lemma = read... |
java | @Factory
public static Matcher<Element> hasAttribute(final String attributeName, final Matcher<? super String> attributeValueMatcher) {
return new ElementWithAttribute(attributeName, attributeValueMatcher);
} |
java | LogMetadata updateLedgerStatus(Map<Long, Long> lastAddConfirmed) {
if (lastAddConfirmed.isEmpty()) {
// Nothing to change.
return this;
}
val newLedgers = this.ledgers.stream()
.map(lm -> {
long lac = lastAddConfirmed.getOrDefault(lm.g... |
java | public static byte[][] split(byte[] source, byte[] separator, int limit) {
List<Range> segments = splitRanges(source, separator, limit);
byte[][] splits = new byte[segments.size()][];
for (int i = 0; i < segments.size(); i++) {
Range r = segments.get(i);
byte[] tmp = new byte[r.length()];
... |
java | @XmlElementDecl(namespace = "http://schema.intuit.com/finance/v3", name = "Employee", substitutionHeadNamespace = "http://schema.intuit.com/finance/v3", substitutionHeadName = "IntuitObject")
public JAXBElement<Employee> createEmployee(Employee value) {
return new JAXBElement<Employee>(_Employee_QNAME, Empl... |
python | def get_page_number_from_request(
request, querystring_key=PAGE_LABEL, default=1):
"""Retrieve the current page number from *GET* or *POST* data.
If the page does not exists in *request*, or is not a number,
then *default* number is returned.
"""
try:
if request.method == 'POST':
... |
java | public void setScalingInstructions(java.util.Collection<ScalingInstruction> scalingInstructions) {
if (scalingInstructions == null) {
this.scalingInstructions = null;
return;
}
this.scalingInstructions = new java.util.ArrayList<ScalingInstruction>(scalingInstructions);
... |
python | def transform_inverse(im_tensor, mean, std):
"""
transform from mxnet im_tensor to ordinary RGB image
im_tensor is limited to one image
:param im_tensor: [batch, channel, height, width]
:param mean: [RGB pixel mean]
:param std: [RGB pixel std var]
:return: im [height, width, channel(RGB)]
... |
python | def until(self, method, message=''):
"""Calls the method provided with the driver as an argument until the \
return value does not evaluate to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the l... |
java | public void setParamElem(ElemWithParam ParamElem)
{
if (null == m_paramElems)
{
m_paramElems = new ElemWithParam[1];
m_paramElems[0] = ParamElem;
}
else
{
// Expensive 1 at a time growth, but this is done at build time, so
// I think it's OK.
int length = m_paramElem... |
python | def OnUpdate(self, event):
"""Updates the toolbar states"""
# Gray out undo and redo id not available
undo_toolid = self.label2id["Undo"]
redo_toolid = self.label2id["Redo"]
self.EnableTool(undo_toolid, undo.stack().canundo())
self.EnableTool(redo_toolid, undo.stack().... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.