language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public static Pattern get(String regex, int flags) {
final RegexWithFlag regexWithFlag = new RegexWithFlag(regex, flags);
Pattern pattern = POOL.get(regexWithFlag);
if (null == pattern) {
pattern = Pattern.compile(regex, flags);
POOL.put(regexWithFlag, pattern);
}
return pattern;
} |
java | private void parseQueryRowsRaw(boolean lastChunk) {
while (responseContent.isReadable()) {
int splitPos = findSplitPosition(responseContent, ',');
int arrayEndPos = findSplitPosition(responseContent, ']');
boolean doSectionDone = false;
if (splitPos == -1 && arr... |
java | @Override
public CancelTaskExecutionResult cancelTaskExecution(CancelTaskExecutionRequest request) {
request = beforeClientExecution(request);
return executeCancelTaskExecution(request);
} |
java | public Backup backup( Database dest, String destName, String srcName ) throws jsqlite.Exception {
synchronized (this) {
Backup b = new Backup();
_backup(b, dest, destName, this, srcName);
return b;
}
} |
python | def eig(C):
"""eigendecomposition of a symmetric matrix, much slower than
`numpy.linalg.eigh`, return ``(EVals, Basis)``, the eigenvalues
and an orthonormal basis of the corresponding eigenvectors, where
``Basis[i]``
the i-th row of ``Basis``
columns of `... |
java | @Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case AfplibPackage.BEGIN_SEGMENT__SEGNAME:
setSEGNAME((Integer)newValue);
return;
}
super.eSet(featureID, newValue);
} |
python | def add_config_parser(subparsers, parent_parser):
"""Creates the arg parsers needed for the config command and
its subcommands.
"""
parser = subparsers.add_parser(
'config',
help='Changes genesis block settings and create, view, and '
'vote on settings proposals',
descrip... |
python | def get_custom_functions():
"""
Return a dict of function names, to be used from inside SASS
"""
def get_setting(*args):
try:
return getattr(settings, args[0])
except AttributeError as e:
raise TemplateSyntaxError(str(e))
if hasattr(get_custom_functions, '_cu... |
java | public static void put(Writer writer, Enum<?> value) throws IOException {
if (value == null) {
writer.write("null");
} else {
writer.write("\"");
writer.write(sanitize(value.name()));
writer.write("\"");
}
} |
python | def standarize( trainingset ):
"""
Morph the input signal to a mean of 0 and scale the signal strength by
dividing with the standard deviation (rather that forcing a [0, 1] range)
"""
def encoder( dataset ):
for instance in dataset:
if np.any(stds == 0):
non... |
python | def set_values(self, values):
"""expects a list of 2-tuples"""
self.values = values
self.height = len(self.values) * 14
self._max = max(rec[1] for rec in values) if values else dt.timedelta(0) |
python | def cmd_cymon_ip_timeline(ip, no_cache, verbose, output, pretty):
"""Simple cymon API client.
Prints the JSON result of a cymon IP timeline query.
Example:
\b
$ habu.cymon.ip.timeline 8.8.8.8
{
"timeline": [
{
"time_label": "Aug. 18, 2018",
... |
python | def system_content(self):
r"""A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
In the case of :attr:`MessageType.default`\, this just returns the
regular :attr:`Message.content`. Otherwise this returns an English
message denoting the c... |
java | public void setOutputDataObject( Object outputDataObject ) {
dataObject = outputDataObject;
if (outputDataObject instanceof Vector) {
if (((Vector) outputDataObject).capacity() == 0)
dataObject = new Vector();
}
} |
python | def delete(self, model):
""" Given a model object instance delete it """
signals.pre_delete.send(model.__class__, model=model)
param = {'rid_value': self.to_pg(model)[model.rid_field]}
query = """
DELETE FROM {table}
WHERE {rid_field} = %(rid_value)s
... |
java | public ApiResponse<DevicePricingTierEnvelope> setPricingTierWithHttpInfo(String did, DevicePricingTierRequest pricingTier) throws ApiException {
com.squareup.okhttp.Call call = setPricingTierValidateBeforeCall(did, pricingTier, null, null);
Type localVarReturnType = new TypeToken<DevicePricingTierEnvelo... |
java | public DaemonConfigurationBuilder parseProgramArgs(String... args) {
Iterator<String> it = Arrays.asList(args).iterator();
while (it.hasNext()) {
String parameter = it.next();
switch (parameter) {
case DaemonConfiguration.JUMI_HOME:
setJumiHome... |
python | def parse_month_year(date_string):
"""
>>> parse_month_year('01/10/2012')
(10, 2012)
"""
match = re.match('\d{2}/(?P<month>\d{2})/(?P<year>\d{4})$',
date_string.lower())
if not match:
raise ValueError("Not format 'dd/mm/yyyy': '{}'".format(date_string))
month = i... |
java | public static Charset[] getAvailableCharsets() {
Collection collection = Charset.availableCharsets().values();
return (Charset[]) collection.toArray(EMPTY_CHARSET_ARRAY);
} |
python | def search_items(self, query,
fields=None,
sorts=None,
params=None,
request_kwargs=None,
max_retries=None):
"""Search for items on Archive.org.
:type query: str
:param query: The Archive.org... |
java | public static DTree convertTreeBankToCoNLLX(final String constituentTree) {
Tree tree = Tree.valueOf(constituentTree);
SemanticHeadFinder headFinder = new SemanticHeadFinder(false); // keep copula verbs as head
Collection<TypedDependency> dependencies = new EnglishGrammaticalStructure(tree, str... |
python | def _parse_blkio_metrics(self, stats):
"""Parse the blkio metrics."""
metrics = {
'io_read': 0,
'io_write': 0,
}
for line in stats:
if 'Read' in line:
metrics['io_read'] += int(line.split()[2])
if 'Write' in line:
... |
java | public static float wrapAngleAroundZero (float a) {
if (a >= 0) {
float rotation = a % MathUtils.PI2;
if (rotation > MathUtils.PI) rotation -= MathUtils.PI2;
return rotation;
} else {
float rotation = -a % MathUtils.PI2;
if (rotation > MathUtils.PI) rotation -= MathUtils.PI2;
return -rotation;
}... |
python | def put(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to PUT"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='PUT', **overrides) |
python | def add(self, *args, **kwargs):
""" Add new mapping from args and kwargs
>>> om = OperationIdMapping()
>>> om.add(
... OperationIdMapping(),
... 'aiohttp_apiset.swagger.operations', # any module
... getPets='mymod.handler',
... getPet='mymod.get_... |
java | public ClientConfig setBootstrapUrls(String... bootstrapUrls) {
this.bootstrapUrls = Arrays.asList(Utils.notNull(bootstrapUrls));
if(this.bootstrapUrls.size() <= 0)
throw new IllegalArgumentException("Must provide at least one bootstrap URL.");
return this;
} |
python | def get_help(self, prefix='', include_special_flags=True):
"""Returns a help string for all known flags.
Args:
prefix: str, per-line output prefix.
include_special_flags: bool, whether to include description of
SPECIAL_FLAGS, i.e. --flagfile and --undefok.
Returns:
str, formatted... |
java | public JRecordExtractor<T, DoubleSparseArray>
extractWithSubsetSettingsDoubleSparseArray(String settings) {
return new JRecordExtractor<>(JavaOps.extractWithSubsetSettingsDoubleSparseArray(self, settings));
} |
python | def update_load_balancer(access_token, subscription_id, resource_group, lb_name, body):
'''Updates a load balancer model, i.e. PUT an updated LB body.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure ... |
java | private static boolean polylineCrossesEnvelope_(Polyline polyline_a,
Envelope envelope_b, double tolerance,
ProgressTracker progress_tracker) {
Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D();
polyline_a.queryEnvelope2D(env_a);
envelope_b.queryEnvelope2D(env_b);
if (envelopeInfContainsEnvel... |
python | def insert_base_bank_options(parser):
"""
Adds essential common options for template bank generation to an
ArgumentParser instance.
"""
def match_type(s):
err_msg = "must be a number between 0 and 1 excluded, not %r" % s
try:
value = float(s)
except ValueError:
... |
java | private static void createFeedMapping(
AdWordsServicesInterface adWordsServices, AdWordsSession session, DSAFeedDetails feedDetails)
throws RemoteException {
// Get the FeedMappingService.
FeedMappingServiceInterface feedMappingService =
adWordsServices.get(session, FeedMappingServiceInterfa... |
python | def cookiestring(self):
"""Cookie string"""
return '; '.join('%s=%s' % (k, v) for k, v in self.cookies.items()) |
java | public State getWifiState() {
if (connMan == null) {
connMan = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo wifiNetworkInfo = connMan.getNetworkInfo(TYPE_WIFI);
if (wifiNetworkInfo == null) {
return State.UNKNOWN;
}
return wifiNetworkInfo.getState(... |
python | def send(self, body, req_type, seq_no=1):
"""
Send a TACACS+ message body
:param body: packed bytes, i.e., `struct.pack(...)`
:param req_type: TAC_PLUS_AUTHEN,
TAC_PLUS_AUTHOR,
TAC_PLUS_ACCT
:param seq_no: The sequence numb... |
python | def execute(self, sql, parameters=None):
"""
Execute an SQL command or query
:param sql: A (unicode) string that contains the SQL command or query. If you would like to
use parameters, please use a question mark ``?`` at the location where the
parameter shall be in... |
java | public void consumeMessages(LockedMessageEnumeration messages) throws Exception
{
if (tc.isEntryEnabled())
SibTr.entry(tc, "consumeMessages", new Object[] { messages });
SIBusMessage jsMessage = null;
while (messages.hasNext())
{
try
{
jsMessage = messages.nextLocke... |
python | def free_symbols(self):
"""Set of all symbols occcuring in S, L, or H"""
return set.union(
self.S.free_symbols, self.L.free_symbols, self.H.free_symbols) |
java | public LineElement generateInnerElement(IBond bond, IRing ring, RendererModel model) {
Point2d center = GeometryUtil.get2DCenter(ring);
Point2d a = bond.getBegin().getPoint2d();
Point2d b = bond.getEnd().getPoint2d();
// the proportion to move in towards the ring center
double d... |
java | public Collection<Defect> getFoundDefects(DefectFilter filter) {
filter = (filter != null) ? filter : new DefectFilter();
filter.foundIn.clear();
filter.foundIn.add(this);
return getInstance().get().defects(filter);
} |
python | def _get_binned_arrays(self, wavelengths, flux_unit, area=None,
vegaspec=None):
"""Get binned observation in user units."""
x = self._validate_binned_wavelengths(wavelengths)
y = self.sample_binned(wavelengths=x, flux_unit=flux_unit, area=area,
... |
java | public ETriggerState getTriggerState (final TriggerKey triggerKey) throws SchedulerException
{
validateState ();
return m_aResources.getJobStore ().getTriggerState (triggerKey);
} |
java | public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
return new Compound(
ClassConstant.of(methodDescription.getDeclaringType()),
methodName(),
ArrayFactory.forType(TypeDescription.Generic.OfNonGenericType.CLASS)
... |
python | def conduct(self, randomize=True):
'''
Run control & candidate functions and return the control's return value.
``control()`` must be called first.
:param bool randomize: controls whether we shuffle the order
of execution between control and candidate
:raise Laborato... |
java | private String[] mergeAndConvert(List<String> list, String[] array) {
Set<String> set = new HashSet<String>(Arrays.asList(array));
set.addAll(list);
return set.toArray(new String[set.size()]);
} |
java | public void genCode(String language, File outputDirectory)
throws IOException {
if ("c++".equals(language)) {
CppGenerator gen = new CppGenerator(mName, mInclFiles, mRecords,
outputDirectory);
gen.genCode();
} else if ("java".equals(language)) {
... |
python | def collect_sound_streams(self):
"""
Return a list of sound streams in this timeline and its children.
The streams are returned in order with respect to the timeline.
A stream is returned as a list: the first element is the tag
which introduced that stream; other elements are th... |
java | @Nonnull
protected Completer discoverCompleter() {
log.debug("Discovering completer");
// TODO: Could probably use CliProcessorAware to avoid re-creating this
CliProcessor cli = new CliProcessor();
cli.addBean(this);
List<ArgumentDescriptor> argumentDescriptors = cli.getArgumentDescriptors();
... |
java | @Override
public DeleteCodeRepositoryResult deleteCodeRepository(DeleteCodeRepositoryRequest request) {
request = beforeClientExecution(request);
return executeDeleteCodeRepository(request);
} |
java | public static int intersectionSize(DBIDs first, DBIDs second) {
// If exactly one is a Set, use it as second parameter.
if(second instanceof SetDBIDs) {
if(!(first instanceof SetDBIDs)) {
return internalIntersectionSize(first, second);
}
}
else if(first instanceof SetDBIDs) {
r... |
java | public CTX soThat(@Nonnull AssertionsCheck assertions) {
normalCheck(description, caseDescription, preconditioner, assertFunction, assertPreConsumer, a -> assertions.assertionsCheck());
return context.self();
} |
java | public static <T> T pickRandom (Iterator<T> iter, int count)
{
return pickRandom(iter, count, rand);
} |
java | protected SIDestinationAddress getConsumerSIDestinationAddress() throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "getConsumerSIDestinationAddress");
if (consumerDestinationAddress == null) {
if (TraceComponent.isAnyTra... |
python | def prepare_url(self, uri, kwargs):
"""Convert dict for URL params
"""
params = dict()
for key in kwargs:
if key in ('include', 'exclude', 'fields'):
params.update({
key: ','.join(kwargs.get(key))
})
elif key in ... |
java | public RetryerBuilder<V> withWaitStrategy(@Nonnull WaitStrategy waitStrategy) throws IllegalStateException {
Preconditions.checkNotNull(waitStrategy, "waitStrategy may not be null");
Preconditions.checkState(this.waitStrategy == null, "a wait strategy has already been set %s", this.waitStrategy);
... |
java | public static synchronized void startSinksFromConfig(MetricsConfig config) {
if (sSinks != null) {
LOG.info("Sinks have already been started.");
return;
}
LOG.info("Starting sinks with config: {}.", config);
sSinks = new ArrayList<>();
Map<String, Properties> sinkConfigs =
Metric... |
java | public static String getConfigurationDirectoryFromEnv() {
String location = System.getenv(ConfigConstants.ENV_FLINK_CONF_DIR);
if (location != null) {
if (new File(location).exists()) {
return location;
}
else {
throw new RuntimeException("The configuration directory '" + location + "', specified ... |
python | def boddef(name, code):
"""
Define a body name/ID code pair for later translation via
:func:`bodn2c` or :func:`bodc2n`.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/boddef_c.html
:param name: Common name of some body.
:type name: str
:param code: Integer code for that body.
... |
python | def _check_integrity(self, lons, lats):
"""
Ensure lons and lats are:
- 1D numpy arrays
- equal size
- within the appropriate range in radians
"""
lons = np.array(lons).ravel()
lats = np.array(lats).ravel()
if len(lons.shape) != 1 or len(lats.... |
python | def load_plugins(self, raise_error=False):
"""
Load the plotters and defaultParams from the plugins
This method loads the `plotters` attribute and `defaultParams`
attribute from the plugins that use the entry point specified by
`group`. Entry points must be objects (or modules) ... |
java | @Override
public EClass getIfcPolygonalFaceSet() {
if (ifcPolygonalFaceSetEClass == null) {
ifcPolygonalFaceSetEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(436);
}
return ifcPolygonalFaceSetEClass;
} |
java | private ProtoNetwork stage1(final ProtoNetwork pn) {
beginStage(PHASE3_STAGE1_HDR, "1", NUM_PHASES);
final StringBuilder bldr = new StringBuilder();
// Load the pfam resource from the resource index.
Index resourceIndex = ResourceIndex.INSTANCE.getIndex();
ResourceLocation pfRe... |
java | @Override
public int countByG_C_P(long groupId, long commerceCountryId,
boolean primary) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_C_P;
Object[] finderArgs = new Object[] { groupId, commerceCountryId, primary };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == nu... |
python | def getpaths(self):
'''
If we have children, use a list comprehension to instantiate new paths
objects to traverse.
'''
self.children = self.getchildren()
if self.children is None:
return
if self.paths is None:
self.paths = [Paths(self.scre... |
java | @EventHandler("command")
private void onCommand(CommandEvent event) {
if (isEnabled()) {
for (BaseComponent child : container.getChildren()) {
EventUtil.send(event, child);
if (event.isStopped()) {
break;
}
}
... |
python | def discovery_zookeeper(self):
"""
Installs the ZooKeeper discovery bundles and instantiates components
"""
# Install the bundle
self.context.install_bundle("pelix.remote.discovery.zookeeper").start()
with use_waiting_list(self.context) as ipopo:
# Instantiat... |
python | def edit_section(self, id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None):
"""
Edit a section.
Modify an existing section.
"""
path = {}
... |
java | public byte[] serialize(Calendar date)
{
final String calendarString =
CALENDAR_FIELDS_SEPARATOR + date.isLenient() + CALENDAR_FIELDS_DELIMITER + date.getFirstDayOfWeek()
+ CALENDAR_FIELDS_DELIMITER + date.getMinimalDaysInFirstWeek() + CALENDAR_FIELDS_DELIMITER
+ date.getTimeZo... |
java | public ActiveMQQueueJmxStats addCounts(ActiveMQQueueJmxStats other, String resultBrokerName) {
ActiveMQQueueJmxStats result = new ActiveMQQueueJmxStats(resultBrokerName, this.queueName);
result.setCursorPercentUsage(this.getCursorPercentUsage());
result.setDequeueCount(this.getDequeueCount() + o... |
java | public OvhSecret retrieve_POST(String id) throws IOException {
String qPath = "/secret/retrieve";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "id", id);
String resp = execN(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhSecret.class);
} |
java | public static boolean hasDbBind(Annotation[] annotations) {
final String name = DB_BIND_CNAME;
for (Annotation a : annotations) {
if (a.annotationType().getName().equals(name)) {
return true;
}
}
return false;
} |
java | protected void updateFoldingThreshhold() {
int left = estimateRequiredWidth(m_itemsLeft) + estimateRequiredWidth(m_leftButtons);
int right = estimateRequiredWidth(m_itemsRight) + estimateRequiredWidth(m_rightButtons);
int requiredWidth = left > right ? left : right;
if (requiredWidth < ... |
python | def __do_case_5_work(d_w, d_u, case_1, case_2, case_3, dfs_data):
"""Encapsulates the work that will be done for case 5 of __embed_frond,
since it gets used in more than one place."""
# --We should only ever see u-cases 1 and 2
if case_3:
# --We should never get here
return False
co... |
python | def net(narr,nnet):
"""
Automatically create QUBO which has value 1 for all connectivity defined by array of edges and graph size N
.. code-block:: python
print(wq.net([[0,1],[1,2]],4))
#=>
[[0. 1. 0. 0.]
[0. 0. 1. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
this create 4*4 QUBO and put value 1 on connection betwe... |
python | def _rotate_tr(self):
"""Rotate the transformation matrix based on camera parameters"""
rot, x, y, z = self._quaternion.get_axis_angle()
up, forward, right = self._get_dim_vectors()
self.transform.rotate(180 * rot / np.pi, (x, z, y)) |
java | public X509Certificate createProxyCertificate(X509Certificate issuerCert_, PrivateKey issuerKey,
PublicKey publicKey, int lifetime, int proxyType, X509ExtensionSet extSet, String cnValue)
throws GeneralSecurityException {
X509Certificate issuerCert = issuerCert_;
if (!(issuerCert_ insta... |
python | def cbday_roll(self):
"""
Define default roll function to be called in apply method.
"""
cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds)
if self._prefix.endswith('S'):
# MonthBegin
roll_func = cbday.rollforward
else:
... |
java | protected void writeDirectBytes(byte[] b, int off, int len)
throws IOException {
ostream.write(b, off, len);
len += len;
} |
java | private CreateVolumeResponseType createVolume(final String volumeType, final String size,
final String availabilityZone,
final int iops, final String snapshotId) {
CreateVolumeResponseType ret = new CreateVolumeResponseType();
ret.setRequestId(UUID.randomUUID().toString());
... |
python | def load_related(self, meta, fname, data, fields, encoding):
'''Parse data for related objects.'''
field = meta.dfields[fname]
if field in meta.multifields:
fmeta = field.structure_class()._meta
if fmeta.name in ('hashtable', 'zset'):
return ((native... |
java | public static IntDoubleVector estimateGradientFd(Function fn, IntDoubleVector x, double epsilon) {
int numParams = fn.getNumDimensions();
IntDoubleVector gradFd = new IntDoubleDenseVector(numParams);
for (int j=0; j<numParams; j++) {
// Test the deriviative d/dx... |
java | public void endElement(
StylesheetHandler handler, String uri, String localName, String rawName)
throws org.xml.sax.SAXException
{
ElemTemplateElement elem = handler.getElemTemplateElement();
if (elem instanceof ElemLiteralResult)
{
if (((ElemLiteralResult) elem).getIsLiteral... |
python | def tokenize(self, data):
"""
Tokenizes the given string. A token is a 4-tuple of the form:
(token_type, tag_name, tag_options, token_text)
token_type
One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA
tag_name
The name... |
python | def initWithArticleUriList(uriList):
"""
instead of making a query, provide a list of article URIs manually, and then produce the desired results on top of them
"""
q = QueryArticles()
assert isinstance(uriList, list), "uriList has to be a list of strings that represent article u... |
java | @Internal
private static void pushAnnotationAttributes(Type declaringType, ClassVisitor declaringClassWriter, GeneratorAdapter generatorAdapter, Map<? extends CharSequence, Object> annotationData, Map<String, GeneratorAdapter> loadTypeMethods) {
int totalSize = annotationData.size() * 2;
// start a ... |
python | def stream_buckets(self, bucket_type=None, timeout=None):
"""
Stream list of buckets through an iterator
"""
if not self.bucket_stream():
raise NotImplementedError('Streaming list-buckets is not '
"supported on %s" %
... |
java | public boolean sendBatch() throws IOException
{
if (isClosed)
{
throw new IOException("Telemetry connector is closed");
}
if (!isTelemetryEnabled())
{
return false;
}
LinkedList<TelemetryData> tmpList;
synchronized (locker)
{
tmpList = this.logBatch;
this.l... |
java | public static URL getResource(String resourceName, Class<?> callingClass) {
URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName);
if (url == null) {
url = ClassLoaderUtil.class.getClassLoader().getResource(resourceName);
}
if (url == null) {
ClassLoader cl = callingClas... |
python | def tril(array, k=0):
'''Lower triangle of an array.
Return a copy of an array with elements above the k-th diagonal zeroed.
Need a multi-dimensional version here because numpy.tril does not
broadcast for numpy verison < 1.9.'''
try:
tril_array = np.tril(array, k=k)
except:
# hav... |
java | public final static Selector getSelector() {
synchronized (selectors) {
Selector s = null;
try {
if (selectors.size() != 0) {
s = selectors.pop();
}
} catch (EmptyStackException ex) {
}
int attempts = 0;
try {
while (s == null && attempts < 2) {... |
python | def get_item_hrefs(result_collection):
"""
Given a result_collection (returned by a previous API call that
returns a collection, like get_bundle_list() or search()), return a
list of item hrefs.
'result_collection' a JSON object returned by a previous API
call.
Returns a list, which may be... |
python | def remove_global_handler(self, event, handler):
"""Removes a global handler function.
Arguments:
event -- Event type (a string).
handler -- Callback function.
Returns 1 on success, otherwise 0.
"""
with self.mutex:
if event not in self.hand... |
java | final public void writeSingleRegister(int serverAddress, int startAddress, int register) throws
ModbusProtocolException, ModbusNumberException, ModbusIOException {
processRequest(ModbusRequestBuilder.getInstance().buildWriteSingleRegister(serverAddress, startAddress, register));
} |
java | public static long parseDuration(String input,
ConfigOrigin originForException, String pathForException) {
String s = ConfigImplUtil.unicodeTrim(input);
String originalUnitString = getUnits(s);
String unitString = originalUnitString;
String numberString = ConfigImplUtil.unico... |
java | public static String getStateKey(CmsResourceState state) {
StringBuffer sb = new StringBuffer(GUI_STATE_PREFIX);
sb.append(state.getState());
sb.append(GUI_STATE_POSTFIX);
return sb.toString();
} |
java | public Index open(Transaction tx) {
TableInfo ti = VanillaDb.catalogMgr().getTableInfo(tblName, tx);
if (ti == null)
throw new TableNotFoundException("table '" + tblName
+ "' is not defined in catalog.");
return Index.newInstance(this, new SearchKeyType(ti.schema(), fldNames), tx);
} |
java | private void setRule(String name, String value) throws InvalidArgumentException, XmlPullParserException {
if (value.length() > 1024) {
throw new InvalidArgumentException("value '" + value + "' is more than 1024 long");
}
for (FilterRule rule: filterRuleList) {
// Remove rule.name is same as giv... |
java | @Override
public void doServerAssignmentAnswer(ClientCxDxSession appSession, JServerAssignmentRequest request, JServerAssignmentAnswer answer)
throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
logger.info("Diameter Cx/Dx Session Factory :: doServerAssignmentAnsw... |
python | def stopDistributionMessage(self, chatroomId):
"""
聊天室消息停止分发方法(可实现控制对聊天室中消息是否进行分发,停止分发后聊天室中用户发送的消息,融云服务端不会再将消息发送给聊天室中其他用户。) 方法
@param chatroomId:聊天室 Id。(必传)
@return code:返回码,200 为正常。
@return errorMessage:错误信息。
"""
desc = {
"name": "CodeSuccessReslut"... |
java | public void moveTail(int delta) {
assert !isRecycled() : "Attempt to use recycled bytebuf";
assert tail + delta >= head;
assert tail + delta <= array.length;
tail += delta;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.