language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Override
public com.liferay.commerce.shipping.engine.fixed.model.CommerceShippingFixedOptionRel getCommerceShippingFixedOptionRel(
long commerceShippingFixedOptionRelId)
throws com.liferay.portal.kernel.exception.PortalException {
return _commerceShippingFixedOptionRelLocalService.getCommerceShippingFixedOption... |
python | def copyFeatures(self, featureSource):
""" Copy the features from this source """
if featureSource in self.sources:
src, loc = self.sources[featureSource]
if isinstance(src.features.text, str):
self.font.features.text = u""+src.features.text
elif isins... |
python | def ReplaceInstanceDisks(r, instance, disks=None, mode=REPLACE_DISK_AUTO,
remote_node=None, iallocator=None, dry_run=False):
"""
Replaces disks on an instance.
@type instance: str
@param instance: instance whose disks to replace
@type disks: list of ints
@param disks: I... |
python | def _restore_seq_field_pickle(checked_class, item_type, data):
"""Unpickling function for auto-generated PVec/PSet field types."""
type_ = _seq_field_types[checked_class, item_type]
return _restore_pickle(type_, data) |
python | def next(self) -> mx.io.DataBatch:
"""
Returns the next batch from the data iterator.
"""
if not self.iter_next():
raise StopIteration
i, j = self.batch_indices[self.curr_batch_index]
self.curr_batch_index += 1
batch_size = self.bucket_batch_sizes[i]... |
python | def main(argv):
"""Main."""
del argv # Unused.
if flags.FLAGS.version:
print("GRR console {}".format(config_server.VERSION["packageversion"]))
return
banner = ("\nWelcome to the GRR console\n")
config.CONFIG.AddContext(contexts.COMMAND_LINE_CONTEXT)
config.CONFIG.AddContext(contexts.CONSOLE_CONT... |
python | def daOnes(shap, dtype=numpy.float):
"""
One constructor for numpy distributed array
@param shap the shape of the array
@param dtype the numpy data type
"""
res = DistArray(shap, dtype)
res[:] = 1
return res |
java | public OvhOrder cdn_dedicated_serviceName_backend_duration_POST(String serviceName, String duration, Long backend) throws IOException {
String qPath = "/order/cdn/dedicated/{serviceName}/backend/{duration}";
StringBuilder sb = path(qPath, serviceName, duration);
HashMap<String, Object>o = new HashMap<String, Obje... |
python | def get_attached_instruments(
self, expected: Dict[Mount, str])\
-> Dict[Mount, Dict[str, Optional[str]]]:
""" Find the instruments attached to our mounts.
:param expected: A dict that may contain a mapping from mount to
strings that should prefix instru... |
python | def generate_slug(name):
"""Generate a slug for the knowledge.
:param name: text to slugify
:return: slugified text
"""
slug = slugify(name)
i = KnwKB.query.filter(db.or_(
KnwKB.slug.like(slug),
KnwKB.slug.like(slug + '-%'),
)).count()
... |
python | def count(self, *columns):
"""
Retrieve the "count" result of the query
:param columns: The columns to get
:type columns: tuple
:return: The count
:rtype: int
"""
if not columns and self.distinct_:
columns = self.columns
if not colum... |
java | public void setAccessModel(AccessModel accessModel) {
addField(ConfigureNodeFields.access_model, FormField.Type.list_single);
setAnswer(ConfigureNodeFields.access_model.getFieldName(), getListSingle(accessModel.toString()));
} |
java | @SuppressWarnings("unchecked")
public <T extends WebLocatorAbstractBuilder> T setId(final String id) {
pathBuilder.setId(id);
return (T) this;
} |
java | public CompletionStage<ResponseBuilder> createResource(final ResponseBuilder builder) {
LOGGER.debug("Creating resource as {}", getIdentifier());
final TrellisDataset mutable = TrellisDataset.createDataset();
final TrellisDataset immutable = TrellisDataset.createDataset();
return handl... |
java | protected File[] asFiles( File pDir, String[] pFileNames )
{
if ( pFileNames == null )
{
return new File[0];
}
File dir = asAbsoluteFile( pDir );
File[] result = new File[pFileNames.length];
for ( int i = 0; i < pFileNames.length; i++ )
{
... |
java | public static void attributes(Data data, TagLibTag tag, Tag parent) throws TemplateException {
int type = tag.getAttributeType();
int start = data.srcCode.getPos();
// Tag with attribute names
if (type != TagLibTag.ATTRIBUTE_TYPE_NONAME) {
try {
int min = tag.getMin();
int max = tag.getMax();
int count =... |
java | public static void _main(String[] args) {
ImageInfo imageInfo = new ImageInfo();
imageInfo.setDetermineImageNumber(true);
boolean verbose = determineVerbosity(args);
if (args.length == 0) {
run(null, System.in, imageInfo, verbose);
} else {
int index = 0;
while (index < args.length) {
InputStream... |
java | private void initializeGeneratorProperties(ResourceGenerator generator) {
// Initialize the generator
if (generator instanceof InitializingResourceGenerator) {
if (generator instanceof ConfigurationAwareResourceGenerator) {
((ConfigurationAwareResourceGenerator) generator).setConfig(config);
}
if (gene... |
python | def load(cls, model, opt, meta, flag_gpu=None):
'''Loads in model as a class instance with with the specified
model and optimizer states.
Parameters
----------
model : str
Path to the model state file.
opt : str
Path to the optimizer state file... |
java | protected void exceptionCaught(IoSession session, Throwable cause) {
log.error("Unhandled exception for: " + String.valueOf(session), cause);
if (this.disconnectOnException) {
this._disconnect();
}
} |
java | Expression result(CodeChunk.Generator codeGenerator) {
Expression accessChain = buildAccessChain(base, codeGenerator, chain.iterator());
if (unpackFunction == null) {
return accessChain;
} else {
return accessType.unpackResult(accessChain, unpackFunction);
}
} |
python | def get_reverse_dependency_tree(package_name, depth=None, paths=None,
build_requires=False,
private_build_requires=False):
"""Find packages that depend on the given package.
This is a reverse dependency lookup. A tree is constructed, showing what
... |
java | public boolean hasPanelAccess(Panel panel, User user, DelfoiActionName actionName) {
if (panel == null) {
logger.warn("Panel was null when checking panel access");
return false;
}
if (user == null) {
logger.warn("User was null when checking panel access");
return false;
}
i... |
java | public void marshall(StopChannelRequest stopChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (stopChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(stopChannelRequest.getCha... |
java | public static void printQuery(JcQuery query, QueryToObserve toObserve, Format format) {
boolean titlePrinted = false;
ContentToObserve tob = QueriesPrintObserver.contentToObserve(toObserve);
if (tob == ContentToObserve.CYPHER || tob == ContentToObserve.CYPHER_JSON) {
titlePrinted = true;
QueriesPrintObserve... |
java | public static TypeVariableToken of(TypeDescription.Generic typeVariable, ElementMatcher<? super TypeDescription> matcher) {
return new TypeVariableToken(typeVariable.getSymbol(),
typeVariable.getUpperBounds().accept(new TypeDescription.Generic.Visitor.Substitutor.ForDetachment(matcher)),
... |
python | def filter_by_type(stmts_in, stmt_type, **kwargs):
"""Filter to a given statement type.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
stmt_type : indra.statements.Statement
The class of the statement type to filter for.
Exa... |
java | @Override
public CPAttachmentFileEntry findByC_C_LtD_S_First(long classNameId,
long classPK, Date displayDate, int status,
OrderByComparator<CPAttachmentFileEntry> orderByComparator)
throws NoSuchCPAttachmentFileEntryException {
CPAttachmentFileEntry cpAttachmentFileEntry = fetchByC_C_LtD_S_First(classNameId,
... |
java | public void backup(Path pathToDir) {
if (!isPersistent()) {
throw new BitsyException(BitsyErrorCodes.OPERATION_UNDEFINED_FOR_NON_PERSISTENT_GRAPHS, "Transaction log threshold is only defined for persistent graphs (with a defined path to DB)");
} else {
((FileBackedMemoryGraphStor... |
java | @Override
public boolean purgeJobInstance(long jobInstanceId) throws JobSecurityException, NoSuchJobInstanceException {
if (authService != null) {
authService.authorizedJobPurgeByInstance(jobInstanceId);
}
//save this instance object to use in the publishEvent call.
WSJo... |
python | def get_Mapping_key_value(mp):
"""Retrieves the key and value types from a PEP 484 mapping or subclass of such.
mp must be a (subclass of) typing.Mapping.
"""
try:
res = _select_Generic_superclass_parameters(mp, typing.Mapping)
except TypeError:
res = None
if res is None:
... |
java | private void fillMethodIndex() {
mainClassMethodHeader = metaMethodIndex.getHeader(theClass);
LinkedList<CachedClass> superClasses = getSuperClasses();
CachedClass firstGroovySuper = calcFirstGroovySuperClass(superClasses);
Set<CachedClass> interfaces = theCachedClass.getInterfaces();
... |
java | public ExchangeRate getExchangeRate(CurrencyUnit base, CurrencyUnit term){
Objects.requireNonNull(base, "Base Currency is null");
Objects.requireNonNull(term, "Term Currency is null");
return getExchangeRate(ConversionQueryBuilder.of().setBaseCurrency(base).setTermCurrency(term).build());
} |
python | def receiveError(self, reasonCode, description):
"""
Called when we receive a disconnect error message from the other
side.
"""
error = disconnectErrors.get(reasonCode, DisconnectError)
self.connectionClosed(error(reasonCode, description))
SSHClientTransport.recei... |
java | public <T> List<Long> insertAll(Collection<T> records, boolean withTransaction) {
return insertAll(this.getTableNameByEntity(records.iterator().next()), records, withTransaction);
} |
java | public synchronized void close() {
Map<String, IDataLogger> copiedLoggers = new HashMap<String, IDataLogger>(this.openLoggers);
for (IDataLogger dataLogger : copiedLoggers.values()) {
try {
dataLogger.close();
} catch (Exception e) { }
}
this.openLo... |
python | def grouper(iterable, items, fillvalue=None):
"""
Collect data into fixed-length chunks or blocks
e.g:
grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
Got it from https://docs.python.org/2/library/itertools.html#recipes
"""
args = [iter(iterable)] * items
return izip_longest(fillvalue=... |
python | def tear_down(self):
"""Tear down the instance
This is mainly use to stop the proxy
"""
self.runner.info_log("Tear down")
if self.browser_config.config.get('enable_proxy'):
self.stop_proxy() |
python | def parse_delta(__string: str) -> datetime.timedelta:
"""Parse ISO-8601 duration string.
Args:
__string: Duration string to parse
Returns:
Parsed delta object
"""
if not __string:
return datetime.timedelta(0)
match = re.fullmatch(r"""
P
((?P<days>\d+)D)?
... |
python | def session_exists(self, username):
"""
:param username:
:type username: str
:return:
:rtype:
"""
logger.debug("session_exists(%s)?" % username)
return self._store.containsSession(username, 1) |
java | public static String URLDecode( byte[] bytes,
String enc ) {
if (bytes == null) {
return (null);
}
int len = bytes.length;
int ix = 0;
int ox = 0;
while (ix < len) {
byte b = bytes[ix++]; // Get byte to test
... |
python | def load(self):
"""
Load table data from a Google Spreadsheet.
This method consider :py:attr:`.source` as a path to the
credential JSON file to access Google Sheets API.
The method automatically search the header row start from
:py:attr:`.start_row`. The condition of th... |
python | def _slugify(string):
"""
This is not as good as a proper slugification function, but the input space is limited
>>> _slugify("beets")
'beets'
>>> _slugify("Toaster Strudel")
'toaster-strudel'
Here's why: It handles very little. It doesn't handle esoteric whitespace or symbols:
>>> _... |
python | def prepare_for_submission(self, folder):
"""Create the input files from the input nodes passed to this instance of the `CalcJob`.
:param folder: an `aiida.common.folders.Folder` to temporarily write files on disk
:return: `aiida.common.datastructures.CalcInfo` instance
"""
# cr... |
java | @Override
public GetOpenIdTokenResult getOpenIdToken(GetOpenIdTokenRequest request) {
request = beforeClientExecution(request);
return executeGetOpenIdToken(request);
} |
java | public void setProxyExcludedDomains(List<DomainMatcher> proxyExcludedDomains) {
if (proxyExcludedDomains == null || proxyExcludedDomains.isEmpty()) {
((HierarchicalConfiguration) getConfig()).clearTree(ALL_PROXY_EXCLUDED_DOMAINS_KEY);
this.proxyExcludedDomains = Collections.emptyLis... |
java | @Override
public void setUpdatePeriod(final String updatePeriod) {
if (!PERIODS.contains(updatePeriod)) {
throw new IllegalArgumentException("Invalid period [" + updatePeriod + "]");
}
this.updatePeriod = updatePeriod;
} |
python | def object_patch_rm_link(self, root, link, **kwargs):
"""Creates a new merkledag object based on an existing one.
The new object will lack a link to the specified object.
.. code-block:: python
>>> c.object_patch_rm_link(
... 'QmNtXbF3AjAk59gQKRgEdVabHcSsiPUnJwHnZK... |
java | public void onNotificationsResumed() {
isNotificationsPaused = false;
// If there are notifications during pause
if (notificationsDuringPause.size() > 0) {
if (isAppVisible) {
if (visiblePeer != null && notificationsDuringPause.containsKey(visiblePeer)) {
... |
python | def lnprior(pars):
"""
Return probability of parameter values according to prior knowledge.
Parameter limits should be done here through uniform prior ditributions
"""
# Limit norm and B to be positive
logprob = (
naima.uniform_prior(pars[0], 0.0, np.inf)
+ naima.uniform_prior(pa... |
python | def get_metadata(self):
"""
::
GET /:login/machines/:id/metadata
:Returns: machine metadata
:rtype: :py:class:`dict`
Fetch and return the metadata dict for the machine. The method
refreshes the locally cached copy of the metadata ke... |
python | def resubmit(self, job_ids = None, also_success = False, running_jobs = False, new_command=None, keep_logs=False, **kwargs):
"""Re-submit jobs automatically"""
self.lock()
# iterate over all jobs
jobs = self.get_jobs(job_ids)
if new_command is not None:
if len(jobs) == 1:
jobs[0].set_c... |
java | @SuppressWarnings("unchecked")
public <T extends CMAResource> T setId(String id) {
getSystem().setId(id);
return (T) this;
} |
java | public static void print( PrintStream out , DMatrixSparseCSC m , String format ) {
if( format.toLowerCase().equals("matlab")) {
printMatlab(out,m);
} else {
printTypeSize(out, m);
int length = String.format(format, -1.1123).length();
char[] zero = new cha... |
python | def get_longest_target_alignment_coords_by_name(self,name):
"""For a name get the best alignment
:return: [filebyte,innerbyte] describing the to distance the zipped block start, and the distance within the unzipped block
:rtype: list
"""
longest = -1
coord = None
#for x in self._queries[sel... |
java | public void setModel(Database databaseModel, DescriptorRepository objModel)
{
_dbModel = databaseModel;
_preparedModel = new PreparedModel(objModel, databaseModel);
} |
java | public static boolean hasExpression(final Template template, final String expression) {
final TemplateElement rootTreeNode = template.getRootTreeNode();
return hasExpression(template, expression, rootTreeNode);
} |
java | protected void removeLastFieldSeparator(final StringBuffer buffer) {
final int len = buffer.length();
final int sepLen = fieldSeparator.length();
if (len > 0 && sepLen > 0 && len >= sepLen) {
boolean match = true;
for (int i = 0; i < sepLen; i++) {
if (buf... |
java | @TargetApi(Build.VERSION_CODES.FROYO)
public static boolean hasWifiFeature(PackageManager manager) {
return manager.hasSystemFeature(PackageManager.FEATURE_WIFI);
} |
python | def add_instruction(self, target, data):
"""
Add an instruction node to this element.
:param string text: text content to add as an instruction.
"""
self._add_instruction(self.impl_node, target, data) |
java | public boolean isIncludeFile()
{
if (value != null && value.length() > 0 && CmdLine.INCLUDE_FILE_PREFIX.charAt(0) == value.charAt(0))
return true;
return false;
} |
python | def _log_board_numbers(self, numbers):
"""
Numbers are logged counterclockwise beginning from the top-left.
See module hexgrid (https://github.com/rosshamish/hexgrid) for the tile layout.
:param numbers: list of catan.board.HexNumber objects.
"""
self._logln('numbers: {0... |
java | private void putValue(EsRequest doc, EsIndexColumn column, Object value) {
Object columnValue = column.columnValue(value);
String stringValue = column.stringValue(value);
doc.put(column.getName(), columnValue);
if (!(value instanceof ModeShapeDateTime || value instanceof Long || value in... |
java | public ServiceFuture<List<ManagedInstanceVulnerabilityAssessmentInner>> listByInstanceNextAsync(final String nextPageLink, final ServiceFuture<List<ManagedInstanceVulnerabilityAssessmentInner>> serviceFuture, final ListOperationCallback<ManagedInstanceVulnerabilityAssessmentInner> serviceCallback) {
return Azur... |
python | def _executor_script(self):
"""Create shell-script in charge of executing the benchmark
and return its path.
"""
fd, path = tempfile.mkstemp(suffix='.sh', dir=os.getcwd())
os.close(fd)
with open(path, 'w') as ostr:
self._write_executor_script(ostr)
mod... |
python | def load_config(config, expand_env=False, force=False):
"""Return repos from a directory and fnmatch. Not recursive.
:param config: paths to config file
:type config: str
:param expand_env: True to expand environment varialbes in the config.
:type expand_env: bool
:param bool force: True to agg... |
python | def initialize(template, service_name, environment='dev'):
"""Adds SERVICE_NAME, SERVICE_ENVIRONMENT, and DEFAULT_TAGS to the template
:param template:
:param service_name:
:param environment:
:return:
"""
template.SERVICE_NAME = os.getenv('SERVICE_NAME', service_name)
template.SERVICE_... |
java | protected void doClose(int tabIndex) {
if (tabCloseListener == null || tabCloseListener.tabAboutToBeClosed(tabIndex)) {
String title = tabPane.getTitleAt(tabIndex);
Component component = tabPane.getComponentAt(tabIndex);
tabPane.removeTabAt(tabIndex);
if ... |
java | public <B> XMLReader<B> map(final Function<? super T, ? extends B> mapper) {
requireNonNull(mapper);
return new XMLReader<B>(_name, _type) {
@Override
public B read(final XMLStreamReader xml, final boolean lenient)
throws XMLStreamException
{
try {
return mapper.apply(XMLReader.this.read(xml,... |
java | @Override
public Temporal subtractFrom(Temporal temporal) {
if (days != 0) {
temporal = temporal.minus(days, DAYS);
}
return temporal;
} |
java | public Type getType() {
if (coordinates[0].length==1) return Type.POINT;
else if (coordinates[0].length>2) return Type.POLYGON;
else { //coordinates[0].length==2
if (Float.isNaN(coordinates[0][1])) return Type.CIRCLE;
else return Type.BOX;
}
} |
java | @Override
public void introspect(final PrintWriter writer) throws Exception {
// Put out a header before the information
writer.println("Network Interface Information");
writer.println("-----------------------------");
// Extract the interface information inside a doPriv
try... |
python | def format_load_balancer_configuration(result):
'''
Formats the LoadBalancerConfiguration object removing arguments that are empty
'''
from collections import OrderedDict
# Only display parameters that have content
order_dict = OrderedDict()
if result.private_ip_address is not None:
... |
python | def __vDecodeDIGICAMConfigure(self, mCommand_Long):
if mCommand_Long.param1 != 0:
print ("Exposure Mode = %d" % mCommand_Long.param1)
if mCommand_Long.param1 == self.ProgramAuto:
self.__vCmdSetCamExposureMode(["Program Auto"])
elif mC... |
java | public PmiDataInfo copy() {
PmiDataInfo r = new PmiDataInfo(id);
// name is translatable
if (name != null)
r.name = new String(name);
// description is translatable
if (description != null)
r.description = new String(description);
// unit is tra... |
python | def show_objects(self):
''' display the entire of objects with their (id, value, node) '''
for key in self.nodes:
node = self.nodes[key]
value = node.obj
print(key, '-', repr(value), '-', node) |
python | def do_get_next(endpoint, access_token):
'''Do an HTTP GET request, follow the nextLink chain and return JSON.
Args:
endpoint (str): Azure Resource Manager management endpoint.
access_token (str): A valid Azure authentication token.
Returns:
HTTP response. JSON body.
'''
he... |
java | private <T extends Request, U> void sendRequest(T request, BiFunction<Request, Connection, CompletableFuture<U>> sender, CompletableFuture<U> future) {
if (open) {
connect().whenComplete((c, e) -> sendRequest(request, sender, c, e, future));
}
} |
java | public GalleryInfo galleryInfo(String galleryId) throws JinxException {
JinxUtils.validateParams(galleryId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.galleries.getInfo");
params.put("gallery_id", galleryId);
return jinx.flickrPost(params, GalleryInfo.class);
} |
python | def add_page(self, title=None, content=None, old_url=None,
tags=None, old_id=None, old_parent_id=None):
"""
Adds a page to the list of pages to be imported - used by the
Wordpress importer.
"""
if not title:
text = decode_entities(strip_tags(content))... |
java | public static long getLongHash(@NonNull String string) {
long h = HSTART;
final long hmult = HMULT;
final long[] ht = byteTable;
final int len = string.length();
for (int i = 0; i < len; i++) {
char ch = string.charAt(i);
h = (h * hmult) ^ ht[ch & 0xff];
... |
java | public static String getUserPackageName(TypeLiteral<?> typeLiteral) {
Map<String, Class<?>> packageNames = new LinkedHashMap<String, Class<?>>();
getTypePackageNames(typeLiteral.getType(), packageNames);
if (packageNames.size() == 0) {
// All type names are public, so typeLiteral is visible from any ... |
java | public void writeKey(Destination dst, int level, byte[] key)
throws KNXTimeoutException, KNXDisconnectException, KNXRemoteException,
KNXLinkClosedException
{
// level 255 is free access
if (level < 0 || level > 254 || key.length != 4)
throw new KNXIllegalArgumentException(
"level out of range or ... |
java | public void scan () throws IOException
{
this.includedGrammars.clear ();
this.scanner.scan ();
final String [] includedFiles = this.scanner.getIncludedFiles ();
for (final String includedFile : includedFiles)
{
final GrammarInfo grammarInfo = new GrammarInfo (this.scanner.getBasedir (), inc... |
java | protected final ChannelFuture doConnect(InetSocketAddress target)
{
ChannelHandler fixHandler=fixHandlerBeforeConnect(channelInitFix(handler));//修正handler
return doBooterConnect(target, fixHandler);
} |
java | @Override
public final void decode(long spatialKey, GHPoint latLon) {
// Performance: calculating 'midLon' and 'midLat' on the fly is not slower than using
// precalculated values from arrays and for 'bits' a precalculated array is even slightly slower!
// Use the value in the middle => st... |
java | @BetaApi
public final ListAcceleratorTypesPagedResponse listAcceleratorTypes(ProjectZoneName zone) {
ListAcceleratorTypesHttpRequest request =
ListAcceleratorTypesHttpRequest.newBuilder()
.setZone(zone == null ? null : zone.toString())
.build();
return listAcceleratorTypes(requ... |
java | public ArrayList<PinCapability> getPinCapabilities(Integer pin) {
if (pinCapabilities.size() >= pin) {
return pinCapabilities.get(pin);
}
return null;
} |
python | def _should_ignore(self, name):
"""Return True if a given library name should be ignored
This is necessary because not all files we find in the library
folder are libraries. I wish there was a public robot API
for "give me a list of installed libraries"...
"""
_name = na... |
java | private static Level calculateMinimumLevel(final Level globalLevel, final Map<String, Level> customLevels) {
Level minimumLevel = globalLevel;
for (Level level : customLevels.values()) {
if (level.ordinal() < minimumLevel.ordinal()) {
minimumLevel = level;
}
}
return minimumLevel;
} |
java | public ManageableCollection getCollectionByQuery(Class collectionClass, Query query, boolean lazy) throws PersistenceBrokerException
{
ManageableCollection result;
try
{
// BRJ: return empty Collection for null query
if (query == null)
{
... |
java | public long cacheSize() {
if (use_lru) {
return (int) (lru_name_cache.size() + lru_id_cache.size());
}
return name_cache.size() + id_cache.size();
} |
java | public DateRange getSelectedRange() {
Listitem selected = getSelectedItem();
return selected == null ? null : (DateRange) selected.getData();
} |
java | public ServiceFuture<ImportExportResponseInner> importMethodAsync(String resourceGroupName, String serverName, ImportRequest parameters, final ServiceCallback<ImportExportResponseInner> serviceCallback) {
return ServiceFuture.fromResponse(importMethodWithServiceResponseAsync(resourceGroupName, serverName, param... |
python | def _WsdlHasMethod(self, method_name):
"""Determine if the wsdl contains a method.
Args:
method_name: The name of the method to search.
Returns:
True if the method is in the WSDL, otherwise False.
"""
return method_name in self.suds_client.wsdl.services[0].ports[0].methods |
java | public static int nextAllOnesInt(int x) {
x |= x >>> 1;
x |= x >>> 2;
x |= x >>> 4;
x |= x >>> 8;
x |= x >>> 16;
return x;
} |
python | def generate(self, inputs, context, beam_size):
"""
Autoregressive generator, works with SequenceGenerator class.
Executes decoder (in inference mode), applies log_softmax and topK for
inference with beam search decoding.
:param inputs: tensor with inputs to the decoder
... |
python | def get_DRAT_tail(max_check, L):
"""
input: tail_check_max, best fit line length
output: DRAT_tail
"""
if max_check == 0:
return float('nan')
DRAT_tail = (old_div(max_check, L)) * 100.
return DRAT_tail |
python | def get_hierarchy_uploader(root):
"""
Returns uploader, that uses get_hierarch_path to store files
"""
# Workaround to avoid Django 1.7 makemigrations wierd behaviour:
# More details: https://code.djangoproject.com/ticket/22436
import sys
if len(sys.argv) > 1 and sys.argv[1] in ('makemigrati... |
python | def get_player(first_name,
last_name=None,
season=constants.CURRENT_SEASON,
only_current=0,
just_id=True):
"""
Calls our PlayerList class to get a full list of players and then returns
just an id if specified or the full row of player information
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.