language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | @Override
public List<BatchPartitionWorkUnit> buildNewParallelPartitions(PartitionsBuilderConfig config)
throws JobRestartException, JobStartException {
List<JSLJob> jobModels = config.getJobModels();
Properties[] partitionPropertiesArray = config.getPartitionProperties();
List<BatchPartitionWorkUni... |
java | protected ResultSet findWorkspaceDataSize() throws SQLException
{
if (findWorkspaceDataSize == null)
{
findWorkspaceDataSize = dbConnection.prepareStatement(FIND_WORKSPACE_DATA_SIZE);
}
return findWorkspaceDataSize.executeQuery();
} |
java | public QrPayResponse qrPay(QrPayRequest request, Boolean convert){
checkPayParams(request);
Map<String, Object> respData = doQrPay(request, TradeType.NATIVE);
String codeUrl = String.valueOf(respData.get(WepayField.CODE_URL));
if (convert){
try {
codeUrl = ... |
python | def Open(self):
"""Opens the USB device for this setting, and claims the interface."""
# Make sure we close any previous handle open to this usb device.
port_path = tuple(self.port_path)
with self._HANDLE_CACHE_LOCK:
old_handle = self._HANDLE_CACHE.get(port_path)
... |
python | def get_configs(self, command):
"""Compose a dictionary with information for writing the submit script."""
logger.debug("Requesting one block with {} nodes per block and {} tasks per node".format(
self.nodes_per_block, self.tasks_per_node))
job_config = {}
job_config["submi... |
python | def single_value(self, key, ts=None, direction=None):
"""Return a single value for a series. You can supply a timestamp
as the ts argument, otherwise the search defaults to the current
time.
The direction argument can be one of "exact", "before", "after", or
"nearest".
... |
python | def update_idxs(self):
"set root idx highest, tip idxs lowest ordered as ladderized"
# internal nodes: root is highest idx
idx = self.ttree.nnodes - 1
for node in self.ttree.treenode.traverse("levelorder"):
if not node.is_leaf():
node.add_feature("idx", idx)
... |
java | @Override
public List<CommerceNotificationQueueEntry> findByLtS(Date sentDate,
int start, int end) {
return findByLtS(sentDate, start, end, null);
} |
python | def _on_shortcut_changed(self, renderer, path, new_shortcuts):
"""Callback handling a change of a shortcut
:param Gtk.CellRenderer renderer: Cell renderer showing the shortcut
:param path: Path of shortcuts within the list store
:param str new_shortcuts: New shortcuts
"""
... |
java | public static <R> Stream<R> zip(final short[] a, final short[] b, final short valueForNoneA, final short valueForNoneB,
final ShortBiFunction<R> zipFunction) {
return zip(ShortIteratorEx.of(a), ShortIteratorEx.of(b), valueForNoneA, valueForNoneB, zipFunction);
} |
python | def get_genomic_seq_for_transcript(self, transcript_id, expand):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/sequence/id/{0}?type=genomic;expand_3prime={1};expand_5prime={1}".f... |
python | def lock(self):
'''
Place an lock file and report on the success/failure. This is an
interface to be used by the fileserver runner, so it is hard-coded to
perform an update lock. We aren't using the gen_lock()
contextmanager here because the lock is meant to stay and not be
... |
java | private void traverseClass(Node n) {
final Node className = n.getFirstChild();
final Node extendsClause = className.getNext();
final Node body = extendsClause.getNext();
boolean isClassExpression = NodeUtil.isClassExpression(n);
traverseBranch(extendsClause, n);
for (Node child = body.getFirs... |
java | public static TypeDeclaration getTypeDeclaration(CompilationUnit compilationUnit, String typeName)
throws TypeDeclarationNotFoundException {
requireNonNull(compilationUnit, "compilation unit");
requireNonNull(typeName, "class name");
int index = typeName.lastIndexOf('.');
St... |
java | public Observable<ServiceResponse<DatabasePrincipalListResultInner>> addPrincipalsWithServiceResponseAsync(String resourceGroupName, String clusterName, String databaseName, List<DatabasePrincipalInner> value) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceG... |
java | private static Money getBid(BiddableAdGroupCriterion biddableCriterion) {
BiddingStrategyConfiguration biddingConfig =
biddableCriterion.getBiddingStrategyConfiguration();
Money cpcBidAmount = null;
if (biddingConfig.getBids() != null) {
for (Bids bid : biddingConfig.getBids()) {
if (b... |
python | def get_description(self, lang: str=None) -> Literal:
""" Get the description of the object
:param lang: Lang to retrieve
:return: Description string representation
:rtype: Literal
"""
return self.metadata.get_single(key=DC.description, lang=lang) |
java | @Override
public int doEndTag() throws JspException {
try {
String imgSrc = getImgSrcToRender();
if (null == var) {
try {
pageContext.getOut().print(imgSrc);
} catch (IOException e) {
throw new JspException(e);
}
} else {
pageContext.setAttribute(var, imgSrc);
}
return sup... |
java | public Future<Pair<String, INDArray>> inferVectorBatched(@NonNull LabelledDocument document) {
if (countSubmitted == null)
initInference();
if (this.vocab == null || this.vocab.numWords() == 0)
reassignExistingModel();
// we block execution until queued amount of docume... |
java | public List<LocalTime> bottom(int n) {
List<LocalTime> bottom = new ArrayList<>();
int[] values = data.toIntArray();
IntArrays.parallelQuickSort(values);
int rowCount = 0;
int validCount = 0;
while (validCount < n && rowCount < size()) {
int value = values[row... |
python | def _thread_to_xml(self, thread):
""" thread information as XML """
name = pydevd_xml.make_valid_xml_value(thread.getName())
cmdText = '<thread name="%s" id="%s" />' % (quote(name), get_thread_id(thread))
return cmdText |
python | def debug_print_line(self, i, level, line):
"""
Debug print of the currently parsed line
:param i: The line number of the line that is being currently parsed
:param level: Parser level
:param line: the line that is currently being parsed
:return: None
"""
... |
python | def at(self, instant):
"""Iterates (in chronological order) over all events that are occuring during `instant`.
Args:
instant (Arrow object)
"""
for event in self:
if event.begin <= instant <= event.end:
yield event |
python | def _dihed_cos_low(a, b, c, deriv):
"""Similar to dihed_cos, but with relative vectors"""
a = Vector3(9, deriv, a, (0, 1, 2))
b = Vector3(9, deriv, b, (3, 4, 5))
c = Vector3(9, deriv, c, (6, 7, 8))
b /= b.norm()
tmp = b.copy()
tmp *= dot(a, b)
a -= tmp
tmp = b.copy()
tmp *= dot(c... |
java | public Expression foldBooleanConditions(List<Function> booleanAtoms) {
if (booleanAtoms.length() == 0)
return TRUE_EQ;
Expression firstBooleanAtom = convertOrCastIntoBooleanAtom( booleanAtoms.head());
return booleanAtoms.tail().foldLeft(new F2<Expression, Function, Expression>() {
... |
python | def get_numeric_feature_names(example):
"""Returns a list of feature names for float and int64 type features.
Args:
example: An example.
Returns:
A list of strings of the names of numeric features.
"""
numeric_features = ('float_list', 'int64_list')
features = get_example_features(example)
retur... |
java | private static final int getSecurityFlags(final Map properties) {
int securityType = 0;
securityType = "true".equals(properties
.get(IHtmlToPdfTransformer.PDF_ALLOW_PRINTING)) ? (securityType | PdfWriter.ALLOW_PRINTING)
: securityType;
securityType = "true".equals(properties
.get(IHtmlToPdfTransformer... |
java | @Deprecated
public String request(String graphPath) throws MalformedURLException, IOException {
return requestImpl(graphPath, new Bundle(), "GET");
} |
python | def convex_hull(labels, indexes=None, fast=True):
"""Given a labeled image, return a list of points per object ordered by
angle from an interior point, representing the convex hull.s
labels - the label matrix
indexes - an array of label #s to be processed, defaults to all non-zero
lab... |
python | def _adaptive(self, gamma=1.0, relative_tolerance=1.0e-8, maximum_iterations=1000, verbose=True, print_warning=True):
"""
Determine dimensionless free energies by a combination of Newton-Raphson iteration and self-consistent iteration.
Picks whichever method gives the lowest gradient.
Is... |
python | def gff3_to_recarray(path, attributes=None, region=None, score_fill=-1,
phase_fill=-1, attributes_fill='.', tabix='tabix', dtype=None):
"""Load data from a GFF3 into a NumPy recarray.
Parameters
----------
path : string
Path to input file.
attributes : list of strings, ... |
python | async def roll_call_handler(service, action_type, payload, props, **kwds):
"""
This action handler responds to the "roll call" emitted by the api
gateway when it is brought up with the normal summary produced by
the service.
"""
# if the action type corresponds to a roll call
if ... |
python | def list(self, catid):
'''
页面打开后的渲染方法,不包含 list 的查询结果与分页导航
'''
logger.info('Infocat input: {0}'.format(catid))
condition = self.gen_redis_kw()
sig = catid
bread_title = ''
bread_crumb_nav_str = '<li>当前位置:<a href="/">信息</a></li>'
_catinfo = MCategor... |
python | def build_additional_match(self, ident, node_set):
"""
handle additional matches supplied by 'has()' calls
"""
source_ident = ident
for key, value in node_set.must_match.items():
if isinstance(value, dict):
label = ':' + value['node_class'].__labe... |
java | public int addAnnotationValue(int annotationDefinitionId,
String annotationValue) {
if (annotationValue == null) {
throw new InvalidArgument("annotationValue is null.");
}
TableAnnotationValue tav = new TableAnnotationValue(
annotationDefinitionId, annota... |
java | public Grammar getFragmentGrammar() {
/*
* Fragment Content
*/
Grammar builtInFragmentContentGrammar = new BuiltInFragmentContent();
/*
* Fragment
*/
fragmentGrammar = new Fragment("Fragment");
fragmentGrammar.addProduction(new StartDocument(),
builtInFragmentContentGrammar);
return fragme... |
java | public ZoneDeleteResultInner beginDelete(String resourceGroupName, String zoneName, String ifMatch) {
return beginDeleteWithServiceResponseAsync(resourceGroupName, zoneName, ifMatch).toBlocking().single().body();
} |
java | @Override
public Transport newInstance(final int port,
final EventHandler<TransportEvent> clientHandler,
final EventHandler<TransportEvent> serverHandler,
final EventHandler<Exception> exHandler) {
final Injector injecto... |
java | public void setCase(String v) {
if (PronounFeats_Type.featOkTst && ((PronounFeats_Type)jcasType).casFeat_case == null)
jcasType.jcas.throwFeatMissing("case", "de.julielab.jules.types.PronounFeats");
jcasType.ll_cas.ll_setStringValue(addr, ((PronounFeats_Type)jcasType).casFeatCode_case, v);} |
java | public static RoundingParams fromCornersRadii(
float topLeft,
float topRight,
float bottomRight,
float bottomLeft) {
return (new RoundingParams())
.setCornersRadii(topLeft, topRight, bottomRight, bottomLeft);
} |
java | public static String[] findTiers(Cache<?, ?> cache) {
// Here I'm randomly taking the eviction observer because it exists on all tiers
@SuppressWarnings("unchecked")
Query statQuery = queryBuilder()
.descendants()
.filter(context(attributes(Matchers.allOf(hasAttribute("name", "eviction"), hasAtt... |
python | def dequeue(self):
"""
Returns a :class:`~retask.task.Task` object from the queue. Returns ``None`` if the
queue is empty.
:return: :class:`~retask.task.Task` object from the queue
If the queue is not connected then it will raise
:class:`retask.ConnectionError`
... |
python | def _is_auto_field(self, cursor, table_name, column_name):
"""
Checks whether column is Identity
"""
# COLUMNPROPERTY: http://msdn2.microsoft.com/en-us/library/ms174968.aspx
#from django.db import connection
#cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsId... |
java | @Path("confirm")
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
@SuppressWarnings("checkstyle:illegalcatch")
public Response confirm()
{
Response ret = null;
try {
final Context context = Context.getThreadContext();
final ContextReply rep... |
java | private static void loadDefinition(final UUID _typeUUID)
throws EFapsException
{
final Type type = Type.get(_typeUUID);
final QueryBuilder queryBldr = new QueryBuilder(CIAdminIndex.IndexDefinition);
queryBldr.addWhereAttrEqValue(CIAdminIndex.IndexDefinition.Active, true);
que... |
java | @Override
public DescribeSimulationJobResult describeSimulationJob(DescribeSimulationJobRequest request) {
request = beforeClientExecution(request);
return executeDescribeSimulationJob(request);
} |
python | async def send_cred_def(self, s_id: str, revo: bool = True, rr_size: int = None) -> str:
"""
Create a credential definition as Issuer, store it in its wallet, and send it to the ledger.
Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure
to send cred... |
java | static Field fieldSerialPersistentFields(Class<?> cl) {
try {
Field f = cl.getDeclaredField("serialPersistentFields");
int modifiers = f.getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isPrivate(modifiers)
&& Modifier.isFinal(modifiers)) {
... |
java | public long readLong(final int offset) throws IOException {
final int bytesToRead = Math.max(0, offset + 8 - used);
if (bytesToRead > 0) {
readMore(bytesToRead);
}
return ((buf[offset] & 0xffL) << 56) //
| ((buf[offset + 1] & 0xffL) << 48) //
|... |
python | def adjoint(self):
"""Adjoint, given as scaling with the conjugate of the scalar.
Examples
--------
In the real case, the adjoint is the same as the operator:
>>> r3 = odl.rn(3)
>>> x = r3.element([1, 2, 3])
>>> op = ScalingOperator(r3, 2)
>>> op(x)
... |
java | @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
labelTitle = new javax.swing.JLabel();
textFieldSearchText = new javax.swing.JTextField();
buttonP... |
java | @Override
public void metadataResolving(RepositoryEvent event) {
log.finer("Resolving metadata " + event.getMetadata() + " from " + event.getRepository());
} |
java | public static List<Tuple2<TypeSerializer<?>, TypeSerializerSnapshot<?>>> readSerializersAndConfigsWithResilience(
DataInputView in,
ClassLoader userCodeClassLoader) throws IOException {
int numSerializersAndConfigSnapshots = in.readInt();
int[] offsets = new int[numSerializersAndConfigSnapshots * 2];
for... |
java | public void cancel(String resourceGroupName, String deploymentName) {
cancelWithServiceResponseAsync(resourceGroupName, deploymentName).toBlocking().single().body();
} |
java | private void handleWebSocketHandshake(FullHttpRequest fullHttpRequest, ChannelHandlerContext ctx)
throws WebSocketConnectorException {
String extensionsHeader = fullHttpRequest.headers().getAsString(HttpHeaderNames.SEC_WEBSOCKET_EXTENSIONS);
DefaultWebSocketHandshaker webSocketHandshaker =
... |
java | public void setDateTimeZone(Object dtz) throws JspTagException {
if (dtz == null || dtz instanceof String
&& ((String) dtz).length() == 0) {
this.dateTimeZone = null;
} else if (dtz instanceof DateTimeZone) {
this.dateTimeZone = (DateTimeZone) dtz;
} else ... |
python | async def preprocess_request(
self, request_context: Optional[RequestContext]=None,
) -> Optional[ResponseReturnValue]:
"""Preprocess the request i.e. call before_request functions.
Arguments:
request_context: The request context, optional as Flask
omits this arg... |
python | def match_https_hostname(cls, hostname):
"""
:param hostname: a string
:returns: an :py:class:`~httpretty.core.URLMatcher` or ``None``
"""
items = sorted(
cls._entries.items(),
key=lambda matcher_entries: matcher_entries[0].priority,
reverse=Tr... |
java | private boolean notContains(long prefix) {
long cmp;
for (int hash = Prefix.hashFirst(prefix, table.length); true; hash = Prefix.hashNext(prefix, hash, table.length)) {
cmp = table[hash];
if (cmp == FREE) {
return true;
}
if (cmp == prefix... |
java | private void addToList(List<Object> list, Object value) {
if (value instanceof List) {
list.addAll((List) value);
} else {
list.add(value);
}
} |
java | public void prewrite(byte[] b,int offset, int length)
{
ensureReserve(length);
System.arraycopy(b,offset,_buf,_start-length,length);
_start-=length;
} |
java | private void addClassProperties() {
List<VariableElement> fields = processingContext.allFields(element);
for (VariableElement field : fields) {
PropertyType type = processingContext.getPropertyType(field);
if (type != null) {
type.addImports(importTypes);
properties.add(new Propert... |
python | def info(package, long_description, classifiers, license):
"""Get info about a package or packages.
"""
client = requests.Session()
for name_or_url in package:
package = get_package(name_or_url, client)
if not package:
secho(u'Invalid name or URL: "{name}"'.format(name=name_o... |
python | def construct_rest_of_worlds(self, excluded, fp=None, use_mp=True, simplify=True):
"""Construct many rest-of-world geometries and optionally write to filepath ``fp``.
``excluded`` must be a **dictionary** of {"rest-of-world label": ["names", "of", "excluded", "locations"]}``."""
geoms = {}
... |
python | def joint_positions_for_eef_command(self, right, left):
"""
This function runs inverse kinematics to back out target joint positions
from the provided end effector command.
Same arguments as @get_control.
Returns:
A list of size @num_joints corresponding to the targ... |
java | public NamespacesList<Value> getValues(String namespace, String predicate, int perPage, int page) throws FlickrException {
Map<String, Object> parameters = new HashMap<String, Object>();
NamespacesList<Value> valuesList = new NamespacesList<Value>();
parameters.put("method", METHOD_GET_VALUES... |
java | @Override
public void messageSent(IoSession session, Object message) throws Exception {
log.debug("messageSent");
if (message instanceof Packet) {
String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
log.trace("Session id: {}", sessionId);
... |
python | def _set_vni_mask(self, v, load=False):
"""
Setter method for vni_mask, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/vni_mask (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_vni_mask is considered as a private
method. Backends looki... |
python | def detectTierTablet(self):
"""Return detection of any device in the Tablet Tier
The quick way to detect for a tier of devices.
This method detects for the new generation of
HTML 5 capable, larger screen tablets.
Includes iPad, Android (e.g., Xoom), BB Playbook, WebOS, etc.
... |
java | static Object extractAttributeValue(Extractors extractors, InternalSerializationService serializationService,
String attributeName, Data key, Object value, Object metadata) throws QueryException {
Object result = extractAttributeValueIfAttributeQueryConstant(serialization... |
python | def yindex(self):
"""Positions of the data on the y-axis
:type: `~astropy.units.Quantity` array
"""
try:
return self._yindex
except AttributeError:
self._yindex = Index.define(self.y0, self.dy, self.shape[1])
return self._yindex |
python | def stationarystate(self, k):
"""See docs for `Model` abstract base class."""
assert 0 <= k < self.ncats
return self._models[k].stationarystate |
python | def from_dict(cls, d):
"""
Reconstructs the SimplestChemenvStrategy object from a dict representation of the SimplestChemenvStrategy object
created using the as_dict method.
:param d: dict representation of the SimplestChemenvStrategy object
:return: StructureEnvironments object
... |
python | def delete_nic(access_token, subscription_id, resource_group, nic_name):
'''Delete a network interface.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
nic_name (str): Na... |
java | public GetDatasetContentResult withEntries(DatasetEntry... entries) {
if (this.entries == null) {
setEntries(new java.util.ArrayList<DatasetEntry>(entries.length));
}
for (DatasetEntry ele : entries) {
this.entries.add(ele);
}
return this;
} |
python | def memoize(func):
""" quick memoize decorator for class instance methods
NOTE: this assumes that the class that the functions to be
memoized already has a memoized and refresh_interval
property """
@functools.wraps(func)
def wrapper(*args, **kwargs):
""" wrap it up and stor... |
python | def clear_messages(self):
"""
Clears all messages.
"""
while len(self._messages):
msg = self._messages.pop(0)
usd = msg.block.userData()
if usd and hasattr(usd, 'messages'):
usd.messages[:] = []
if msg.decoration:
... |
java | static IBlockState applyVariant(IBlockState state, Variation variant)
{
// Try the variant property first - if that fails, look for other properties that match the supplied variant.
boolean relaxRequirements = false;
for (int i = 0; i < 2; i++)
{
for (IProperty prop : sta... |
java | private boolean taskClaimedByUs(Tenant tenant, String claimID) {
waitForClaim();
Iterator<DColumn> colIter =
DBService.instance(tenant).getAllColumns(TaskManagerService.TASKS_STORE_NAME, claimID).iterator();
if (colIter == null) {
m_logger.warn("Claim record disappeared: ... |
java | public static Double getDouble(Config config, String path) {
try {
Object obj = config.getAnyRef(path);
return obj instanceof Number ? ((Number) obj).doubleValue() : null;
} catch (ConfigException.Missing | ConfigException.WrongType e) {
if (e instanceof ConfigExcepti... |
java | public PdfArray getAsArray(PdfName key) {
PdfArray array = null;
PdfObject orig = getDirectObject(key);
if (orig != null && orig.isArray())
array = (PdfArray) orig;
return array;
} |
java | public NotificationChain basicSetArrayType(JvmArrayType newArrayType, NotificationChain msgs)
{
JvmArrayType oldArrayType = arrayType;
arrayType = newArrayType;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, TypesPackage.JVM_COMPONENT_TYPE__ARRA... |
python | def present(name,
if_not_exists=None,
schema=None,
ext_version=None,
from_version=None,
user=None,
maintenance_db=None,
db_user=None,
db_password=None,
db_host=None,
db_port=None):
'''
Ensure ... |
python | def show_vpnservice(self, vpnservice, **kwargs):
'''
Fetches information of a specific VPN service
'''
vpnservice_id = self._find_vpnservice_id(vpnservice)
return self.network_conn.show_vpnservice(vpnservice_id, **kwargs) |
java | private RTPFormat createFormat(int payload, Text description) {
MediaType mtype = MediaType.fromDescription(mediaType);
switch (mtype) {
case AUDIO:
return createAudioFormat(payload, description);
case VIDEO:
return createVideoFormat(payload, description);
case APPLICATION:
return createApplicationFo... |
python | def put(self, destination):
""" Copy the referenced directory to this path
Note:
This ignores anything not in the desired directory, given by ``self.dirname``.
Args:
destination (str): path to put this directory (which must NOT already exist)
References:
... |
java | public static void prepareSplits(final String url, final int nFolds, final String inFile, final String folder, final String outPath) {
DataDownloader dd = new DataDownloader(url, folder);
dd.downloadAndUnzip();
boolean perUser = true;
long seed = SEED;
Parser<Long, Long> parser ... |
python | def delete(self):
# type: (_BaseResumeManager) -> None
"""Delete the resume file db
:param _BaseResumeManager self: this
"""
self.close()
if self._resume_file.exists(): # noqa
try:
self._resume_file.unlink()
except OSError as e:
... |
java | public static String escape(String content) {
if (StrUtil.isBlank(content)) {
return content;
}
int i;
char j;
StringBuilder tmp = new StringBuilder();
tmp.ensureCapacity(content.length() * 6);
for (i = 0; i < content.length(); i++) {
j = content.charAt(i);
if (Character.isDigit... |
java | public KNXNetworkLink detach()
{
final KNXNetworkLink lnk = tl.detach();
if (lnk != null) {
logger.info("detached from " + lnk.getName());
LogManager.getManager().removeLogService(logger.getName());
}
detached = true;
return lnk;
} |
java | Map<String,Long> getContext(String... tokens) throws IOException {
Objects.requireNonNull(tokens);
TermsEnum iterator = getIterator();
Map<String,Long> result = new HashMap<>();
BytesRef byteRef;
int i = 0;
while ((byteRef = iterator.next()) != null) {
String term = new String(byteRef.byte... |
python | def get_flow_by_idx(self, idx, bus):
"""Return seriesflow based on the external idx on the `bus` side"""
P, Q = [], []
if type(idx) is not list:
idx = [idx]
if type(bus) is not list:
bus = [bus]
for line_idx, bus_idx in zip(idx, bus):
line_int... |
python | def push(self):
"""Push built documents to ElasticSearch."""
self._refresh_connection()
# Check if we need to update mappings as this needs to be done
# before we push anything to the Elasticsearch server.
# This must be done even if the queue is empty, as otherwise ES
#... |
python | def playlist_detail(self, playlist_id):
"""获取歌单详情
如果歌单歌曲数超过 100 时,该接口的 songs 字段不会包含所有歌曲,
但是它有个 allSongs 字段,会包含所有歌曲的 ID。
"""
action = 'mtop.alimusic.music.list.collectservice.getcollectdetail'
payload = {'listId': playlist_id}
code, msg, rv = self.request(action, ... |
java | protected static float A( int x , int y , GrayF32 flow ) {
int index = flow.getIndex(x,y);
float u0 = flow.data[index-1];
float u1 = flow.data[index+1];
float u2 = flow.data[index-flow.stride];
float u3 = flow.data[index+flow.stride];
float u4 = flow.data[index-1-flow.stride];
float u5 = flow.data[index... |
python | def out_name(stem, timestep=None):
"""Return StagPy out file name.
Args:
stem (str): short description of file content.
timestep (int): timestep if relevant.
Returns:
str: the output file name.
Other Parameters:
conf.core.outname (str): the generic name stem, defaults ... |
java | public void parseStyleAttribute(final Reader reader, String systemID, final CssErrorHandler err, final CssContentHandler doc) throws
IOException,
CssException
{
CssTokenIterator iter = scan(reader, systemID, err);
doc.startDocument();
while (iter.hasNext())
{
CssToken tk = iter.next(... |
python | def refine_peaks(arr, ipeaks, window_width):
"""Refine the peak location previously found by find_peaks_indexes
Parameters
----------
arr : 1d numpy array, float
Input 1D spectrum.
ipeaks : 1d numpy array (int)
Indices of the input array arr in which the peaks were initially found.
... |
java | public ServerUpdater setVoiceChannel(User user, ServerVoiceChannel channel) {
delegate.setVoiceChannel(user, channel);
return this;
} |
python | def on_state_changed(self, state):
"""
Connects/Disconnects to the painted event of the editor
:param state: Enable state
"""
if state:
self.editor.painted.connect(self._paint_margin)
self.editor.repaint()
else:
self.editor.painted.dis... |
End of preview. Expand in Data Studio
- Downloads last month
- 5