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<BatchPartitionWorkUnit> batchWorkUnits = new ArrayList<BatchPartitionWorkUnit>(jobModels.size());
int instance = 0;
for (JSLJob parallelJob : jobModels){
Properties partitionProps = (partitionPropertiesArray == null) ? null : partitionPropertiesArray[instance];
if (logger.isLoggable(Level.FINER)) {
logger.finer("Starting execution for jobModel = " + parallelJob.toString());
}
RuntimeJobExecution jobExecution = JobExecutionHelper.startPartition(parallelJob, partitionProps);
jobExecution.setPartitionInstance(instance);
if (logger.isLoggable(Level.FINE)) {
logger.fine("JobExecution constructed: " + jobExecution);
}
BatchPartitionWorkUnit batchWork = new BatchPartitionWorkUnit(this, jobExecution, config);
registerCurrentInstanceAndExecution(jobExecution, batchWork.getController());
batchWorkUnits.add(batchWork);
instance++;
}
return batchWorkUnits;
} |
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 = LIANTU_URL + URLEncoder.encode(codeUrl, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new WepayException(e);
}
}
String prepayId = String.valueOf(respData.get(WepayField.PREPAY_ID));
QrPayResponse resp = new QrPayResponse();
resp.setCodeUrl(codeUrl);
resp.setPrepayId(prepayId);
return resp;
} |
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)
if old_handle is not None:
old_handle.Close()
self._read_endpoint = None
self._write_endpoint = None
for endpoint in self._setting.iterEndpoints():
address = endpoint.getAddress()
if address & libusb1.USB_ENDPOINT_DIR_MASK:
self._read_endpoint = address
self._max_read_packet_len = endpoint.getMaxPacketSize()
else:
self._write_endpoint = address
assert self._read_endpoint is not None
assert self._write_endpoint is not None
handle = self._device.open()
iface_number = self._setting.getNumber()
try:
if (platform.system() != 'Windows'
and handle.kernelDriverActive(iface_number)):
handle.detachKernelDriver(iface_number)
except libusb1.USBError as e:
if e.value == libusb1.LIBUSB_ERROR_NOT_FOUND:
_LOG.warning('Kernel driver not found for interface: %s.', iface_number)
else:
raise
handle.claimInterface(iface_number)
self._handle = handle
self._interface_number = iface_number
with self._HANDLE_CACHE_LOCK:
self._HANDLE_CACHE[port_path] = self
# When this object is deleted, make sure it's closed.
weakref.ref(self, self.Close) |
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["submit_script_dir"] = self.channel.script_dir
job_config["nodes"] = self.nodes_per_block
job_config["walltime"] = wtime_to_minutes(self.walltime)
job_config["overrides"] = self.overrides
job_config["user_script"] = command
job_config["user_script"] = self.launcher(command,
self.tasks_per_node,
self.nodes_per_block)
return job_config |
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".
:param string key: the key for the series to use
:param ts: (optional) the time to begin searching from
:type ts: ISO8601 string or Datetime object
:param string direction: criterion for the search
:rtype: :class:`tempodb.response.Response` with a
:class:`tempodb.protocol.objects.SingleValue` object as the
data payload"""
url = make_series_url(key)
url = urlparse.urljoin(url + '/', 'single')
if ts is not None:
vts = check_time_param(ts)
else:
vts = None
params = {
'ts': vts,
'direction': direction
}
url_args = endpoint.make_url_args(params)
url = '?'.join([url, url_args])
resp = self.session.get(url)
return resp |
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)
if not node.name:
node.name = str(idx)
idx -= 1
# external nodes: lowest numbers are for tips (0-N)
for node in self.ttree.treenode.get_leaves():
node.add_feature("idx", idx)
if not node.name:
node.name = str(idx)
idx -= 1 |
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
"""
action = self.shortcut_list_store[int(path)][self.KEY_STORAGE_ID]
old_shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True)[action]
from ast import literal_eval
try:
new_shortcuts = literal_eval(new_shortcuts)
if not isinstance(new_shortcuts, list) and \
not all([isinstance(shortcut, string_types) for shortcut in new_shortcuts]):
raise ValueError()
except (ValueError, SyntaxError):
logger.warning("Shortcuts must be a list of strings")
new_shortcuts = old_shortcuts
shortcuts = self.gui_config_model.get_current_config_value("SHORTCUTS", use_preliminary=True, default={})
shortcuts[action] = new_shortcuts
self.gui_config_model.set_preliminary_config_value("SHORTCUTS", shortcuts)
self._select_row_by_column_value(self.view['shortcut_tree_view'], self.shortcut_list_store,
self.KEY_STORAGE_ID, action) |
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}".format(transcript_id, expand)
r = self.ensembl_request(ext, headers)
gene = json.loads(r)
seq = gene["seq"]
seq_id = gene["id"]
if seq_id != transcript_id:
raise ValueError("ensembl gave the wrong transcript")
desc = gene["desc"].split(":")
chrom = desc[2]
start = int(desc[3]) + expand
end = int(desc[4]) - expand
strand_temp = int(desc[5])
strand = "+"
if strand_temp == -1:
strand = "-"
return (chrom, start, end, strand, seq) |
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
automatically removed.
'''
success = []
failed = []
try:
result = self._lock(lock_type='update')
except GitLockError as exc:
failed.append(exc.strerror)
else:
if result is not None:
success.append(result)
return success, failed |
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.getFirstChild(); child != null;) {
Node next = child.getNext(); // see traverseChildren
if (child.isComputedProp()) {
traverseBranch(child.getFirstChild(), child);
}
child = next;
}
if (!isClassExpression) {
// Class declarations are in the scope containing the declaration.
traverseBranch(className, n);
}
curNode = n;
pushScope(n);
if (isClassExpression) {
// Class expression names are only accessible within the function
// scope.
traverseBranch(className, n);
}
// Body
traverseBranch(body, n);
popScope();
} |
java | public static TypeDeclaration getTypeDeclaration(CompilationUnit compilationUnit, String typeName)
throws TypeDeclarationNotFoundException {
requireNonNull(compilationUnit, "compilation unit");
requireNonNull(typeName, "class name");
int index = typeName.lastIndexOf('.');
String packageName = index > 0 ? typeName.substring(0, index) : "";
if (!matchesPackage(compilationUnit.getPackage(), packageName)) {
throw new TypeDeclarationNotFoundException(compilationUnit, typeName, "The package '" + packageName
+ "' doesn't match the package of the compilation unit.");
}
TypeDeclaration type = searchTypeDeclaration(compilationUnit.types(), typeName.substring(index + 1));
if (type == null) {
throw new TypeDeclarationNotFoundException(compilationUnit, typeName);
}
return type;
} |
java | public Observable<ServiceResponse<DatabasePrincipalListResultInner>> addPrincipalsWithServiceResponseAsync(String resourceGroupName, String clusterName, String databaseName, List<DatabasePrincipalInner> value) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (clusterName == null) {
throw new IllegalArgumentException("Parameter clusterName is required and cannot be null.");
}
if (databaseName == null) {
throw new IllegalArgumentException("Parameter databaseName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
Validator.validate(value);
DatabasePrincipalListRequest databasePrincipalsToAdd = new DatabasePrincipalListRequest();
databasePrincipalsToAdd.withValue(value);
return service.addPrincipals(resourceGroupName, clusterName, databaseName, this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), databasePrincipalsToAdd, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<DatabasePrincipalListResultInner>>>() {
@Override
public Observable<ServiceResponse<DatabasePrincipalListResultInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<DatabasePrincipalListResultInner> clientResponse = addPrincipalsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
} |
java | private static Money getBid(BiddableAdGroupCriterion biddableCriterion) {
BiddingStrategyConfiguration biddingConfig =
biddableCriterion.getBiddingStrategyConfiguration();
Money cpcBidAmount = null;
if (biddingConfig.getBids() != null) {
for (Bids bid : biddingConfig.getBids()) {
if (bid instanceof CpcBid) {
CpcBid cpcBid = (CpcBid) bid;
if (BidSource.CRITERION.equals(cpcBid.getCpcBidSource())) {
cpcBidAmount = cpcBid.getBid();
break;
}
}
}
}
return cpcBidAmount;
} |
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 super.doEndTag();
} finally {
// Reset the Thread local for the Jawr context
ThreadLocalJawrContext.reset();
}
} |
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 documents gets below acceptable level, to avoid memory exhaust
while (countSubmitted.get() - countFinished.get() > 1024) {
ThreadUtils.uncheckedSleep(50);
}
InferenceCallable callable = new InferenceCallable(vocab, tokenizerFactory, document);
Future<Pair<String, INDArray>> future = inferenceExecutor.submit(callable);
countSubmitted.incrementAndGet();
return future;
} |
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[rowCount];
if (value != TimeColumnType.missingValueIndicator()) {
bottom.add(PackedLocalTime.asLocalTime(value));
validCount++;
}
rowCount++;
}
return bottom;
} |
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
"""
if self.debug_level == 2:
print("Line %d (%d): '%s'" % (i + 1, level, line.rstrip(' \r\n\t\f')))
if self.debug_level > 2:
print("Line %d (%d):" % (i + 1, level))
hexdump(line) |
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, b)
c -= tmp
a /= a.norm()
c /= c.norm()
return dot(a, c).results() |
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>() {
@Override
public Expression f(Expression previousAtom, Function currentAtom) {
return termFactory.getFunctionAND(previousAtom, currentAtom);
}
}, firstBooleanAtom);
} |
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)
return sorted([
feature_name for feature_name in features
if features[feature_name].WhichOneof('kind') in numeric_features
]) |
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.PDF_ALLOW_MODIFY_CONTENTS)) ? (securityType | PdfWriter.ALLOW_MODIFY_CONTENTS)
: securityType;
securityType = "true".equals(properties
.get(IHtmlToPdfTransformer.PDF_ALLOW_COPY)) ? (securityType | PdfWriter.ALLOW_COPY)
: securityType;
securityType = "true".equals(properties
.get(IHtmlToPdfTransformer.PDF_ALLOW_MODIFT_ANNOTATIONS)) ? (securityType | PdfWriter.ALLOW_MODIFY_ANNOTATIONS)
: securityType;
securityType = "true".equals(properties
.get(IHtmlToPdfTransformer.PDF_ALLOW_FILLIN)) ? (securityType | PdfWriter.ALLOW_FILL_IN)
: securityType;
securityType = "true".equals(properties
.get(IHtmlToPdfTransformer.PDF_ALLOW_SCREEN_READERS)) ? (securityType | PdfWriter.ALLOW_SCREENREADERS)
: securityType;
securityType = "true".equals(properties
.get(IHtmlToPdfTransformer.PDF_ALLOW_ASSEMBLY)) ? (securityType | PdfWriter.ALLOW_ASSEMBLY)
: securityType;
securityType = "true".equals(properties
.get(IHtmlToPdfTransformer.PDF_ALLOW_DEGRADED_PRINTING)) ? (securityType | PdfWriter.ALLOW_DEGRADED_PRINTING)
: securityType;
return securityType;
} |
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
labels
Returns a matrix and a vector. The matrix consists of one row per
point in the convex hull. Each row has three columns, the label #,
the i coordinate of the point and the j coordinate of the point. The
result is organized first by label, then the points are arranged
counter-clockwise around the perimeter.
The vector is a vector of #s of points in the convex hull per label
"""
if indexes is None:
indexes = np.unique(labels)
indexes.sort()
indexes=indexes[indexes!=0]
else:
indexes=np.array(indexes)
if len(indexes) == 0:
return np.zeros((0,2),int),np.zeros((0,),int)
#
# Reduce the # of points to consider
#
outlines = outline(labels)
coords = np.argwhere(outlines > 0).astype(np.int32)
if len(coords)==0:
# Every outline of every image is blank
return (np.zeros((0,3),int),
np.zeros((len(indexes),),int))
i = coords[:,0]
j = coords[:,1]
labels_per_point = labels[i,j]
pixel_labels = np.column_stack((i,j,labels_per_point))
return convex_hull_ijv(pixel_labels, indexes, fast) |
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 slower than NR (approximated, not calculated) since it calculates the log norms twice each iteration.
OPTIONAL ARGUMENTS
gamma (float between 0 and 1) - incrementor for NR iterations.
relative_tolerance (float between 0 and 1) - relative tolerance for convergence (default 1.0e-6)
maximum_iterations (int) - maximum number of Newton-Raphson iterations (default 1000)
verbose (boolean) - verbosity level for debug output
NOTES
This method determines the dimensionless free energies by minimizing a convex function whose solution is the desired estimator.
The original idea came from the construction of a likelihood function that independently reproduced the work of Geyer (see [1]
and Section 6 of [2]).
This can alternatively be formulated as a root-finding algorithm for the Z-estimator.
More details of this procedure will follow in a subsequent paper.
Only those states with nonzero counts are include in the estimation procedure.
REFERENCES
See Appendix C.2 of [1].
"""
if verbose:
print("Determining dimensionless free energies by Newton-Raphson iteration.")
# keep track of Newton-Raphson and self-consistent iterations
nr_iter = 0
sci_iter = 0
N_k = self.N_k[self.states_with_samples]
K = len(N_k)
f_k_sci = np.zeros([K], dtype=np.float64)
f_k_new = np.zeros([K], dtype=np.float64)
# Perform Newton-Raphson iterations (with sci computed on the way)
for iteration in range(0, maximum_iterations):
# Store for new estimate of dimensionless relative free energies.
f_k = self.f_k[self.states_with_samples].copy()
# compute weights for gradients: the denominators and free energies are from the previous
# iteration in most cases.
(W_nk, f_k_sci) = self._computeWeights(
recalc_denom=(iteration == 0), return_f_k = True)
# Compute gradient and Hessian of last (K-1) states.
#
# gradient (defined by Eq. C6 of [1])
# g_i(theta) = N_i - \sum_n N_i W_ni
#
# Hessian (defined by Eq. C9 of [1])
# H_ii(theta) = - \sum_n N_i W_ni (1 - N_i W_ni)
# H_ij(theta) = \sum_n N_i W_ni N_j W_nj
#
"""
g = np.matrix(np.zeros([K-1,1], dtype=np.float64)) # gradient
H = np.matrix(np.zeros([K-1,K-1], dtype=np.float64)) # Hessian
for i in range(1,K):
g[i-1] = N_k[i] - N_k[i] * W_nk[:,i].sum()
H[i-1,i-1] = - (N_k[i] * W_nk[:,i] * (1.0 - N_k[i] * W_nk[:,i])).sum()
for j in range(1,i):
H[i-1,j-1] = (N_k[i] * W_nk[:,i] * N_k[j] * W_nk[:,j]).sum()
H[j-1,i-1] = H[i-1,j-1]
# Update the free energy estimate (Eq. C11 of [1]).
Hinvg = linalg.lstsq(H,g)[0] #
# Hinvg = linalg.solve(H,g) # This might be faster if we can guarantee full rank.
for k in range(0,K-1):
f_k_new[k+1] = f_k[k+1] - gamma*Hinvg[k]
"""
g = N_k - N_k * W_nk.sum(axis=0)
NW = N_k * W_nk
H = np.dot(NW.T, NW)
H += (g.T - N_k) * np.eye(K)
# Update the free energy estimate (Eq. C11 of [1]).
# will always have lower rank the way it is set up
Hinvg = linalg.lstsq(H, g)[0]
Hinvg -= Hinvg[0]
f_k_new = f_k - gamma * Hinvg
# self-consistent iteration gradient norm and saved log sums.
g_sci = self._gradientF(f_k_sci)
gnorm_sci = np.dot(g_sci, g_sci)
# save this so we can switch it back in if g_sci is lower.
log_weight_denom = self.log_weight_denom.copy()
# newton raphson gradient norm and saved log sums.
g_nr = self._gradientF(f_k_new)
gnorm_nr = np.dot(g_nr, g_nr)
# we could save the gradient, too, but it's not too expensive to
# compute since we are doing the Hessian anyway.
if verbose:
print("self consistent iteration gradient norm is %10.5g, Newton-Raphson gradient norm is %10.5g" % (gnorm_sci, gnorm_nr))
# decide which directon to go depending on size of gradient norm
if (gnorm_sci < gnorm_nr or sci_iter < 2):
sci_iter += 1
self.log_weight_denom = log_weight_denom.copy()
if verbose:
if sci_iter < 2:
print("Choosing self-consistent iteration on iteration %d" % iteration)
else:
print("Choosing self-consistent iteration for lower gradient on iteration %d" % iteration)
f_k_new = f_k_sci.copy()
else:
nr_iter += 1
if verbose:
print("Newton-Raphson used on iteration %d" % iteration)
# get rid of big matrices that are not used.
del(log_weight_denom, NW, W_nk)
# have to set the free energies back in self, since the gradient
# routine changes them.
self.f_k[self.states_with_samples] = f_k
if (self._amIdoneIterating(f_k_new, relative_tolerance, iteration, maximum_iterations, print_warning, verbose)):
if verbose:
print('Of %d iterations, %d were Newton-Raphson iterations and %d were self-consistent iterations' % (iteration + 1, nr_iter, sci_iter))
break
return |
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, optional
List of columns to extract from the "attributes" field.
region : string, optional
Genome region to extract. If given, file must be position
sorted, bgzipped and tabix indexed. Tabix must also be installed
and on the system path.
score_fill : int, optional
Value to use where score field has a missing value.
phase_fill : int, optional
Value to use where phase field has a missing value.
attributes_fill : object or list of objects, optional
Value(s) to use where attribute field(s) have a missing value.
tabix : string, optional
Tabix command.
dtype : dtype, optional
Override dtype.
Returns
-------
np.recarray
"""
# read records
recs = list(iter_gff3(path, attributes=attributes, region=region,
score_fill=score_fill, phase_fill=phase_fill,
attributes_fill=attributes_fill, tabix=tabix))
if not recs:
return None
# determine dtype
if dtype is None:
dtype = [('seqid', object),
('source', object),
('type', object),
('start', int),
('end', int),
('score', float),
('strand', object),
('phase', int)]
if attributes:
for n in attributes:
dtype.append((n, object))
a = np.rec.fromrecords(recs, dtype=dtype)
return a |
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 action_type == roll_call_type():
# then announce the service
await service.announce() |
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 = MCategory.get_by_uid(catid)
logger.info('Infocat input: {0}'.format(_catinfo))
if _catinfo.pid == '0000':
pcatinfo = _catinfo
catinfo = None
parent_id = catid
parent_catname = MCategory.get_by_uid(parent_id).name
condition['parentid'] = [parent_id]
catname = MCategory.get_by_uid(sig).name
bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(sig, catname)
bread_title = '{0}'.format(catname)
else:
catinfo = _catinfo
pcatinfo = MCategory.get_by_uid(_catinfo.pid)
condition['def_cat_uid'] = [sig]
parent_id = _catinfo.uid
parent_catname = MCategory.get_by_uid(parent_id).name
catname = MCategory.get_by_uid(sig).name
bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(
parent_id,
parent_catname
)
bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(sig, catname)
bread_title += '{0} - '.format(parent_catname)
bread_title += '{0}'.format(catname)
num = MPost.get_num_condition(condition)
kwd = {'catid': catid,
'daohangstr': bread_crumb_nav_str,
'breadtilte': bread_title,
'parentid': parent_id,
'parentlist': MCategory.get_parent_list(),
'condition': condition,
'catname': catname,
'rec_num': num}
# cat_rec = MCategory.get_by_uid(catid)
if self.get_current_user() and self.userinfo:
redis_kw = redisvr.smembers(CMS_CFG['redis_kw'] + self.userinfo.user_name)
else:
redis_kw = []
kw_condition_arr = []
for the_key in redis_kw:
kw_condition_arr.append(the_key.decode('utf-8'))
self.render('autogen/list/list_{0}.html'.format(catid),
userinfo=self.userinfo,
kwd=kwd,
widget_info=kwd,
condition_arr=kw_condition_arr,
cat_enum=MCategory.get_qian2(parent_id[:2]),
pcatinfo=pcatinfo,
catinfo=catinfo) |
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'].__label__
stmt = _rel_helper(lhs=source_ident, rhs=label, ident='', **value)
self._ast['where'].append(stmt)
else:
raise ValueError("Expecting dict got: " + repr(value))
for key, val in node_set.dont_match.items():
if isinstance(val, dict):
label = ':' + val['node_class'].__label__
stmt = _rel_helper(lhs=source_ident, rhs=label, ident='', **val)
self._ast['where'].append('NOT ' + stmt)
else:
raise ValueError("Expecting dict got: " + repr(val)) |
java | public int addAnnotationValue(int annotationDefinitionId,
String annotationValue) {
if (annotationValue == null) {
throw new InvalidArgument("annotationValue is null.");
}
TableAnnotationValue tav = new TableAnnotationValue(
annotationDefinitionId, annotationValue);
int nextIndex = annotationValues.size();
if (annotationValues.add(tav)) {
valueIndex.put(tav, nextIndex);
indexValue.put(nextIndex, tav);
return nextIndex;
}
return valueIndex.get(tav);
} |
java | public Grammar getFragmentGrammar() {
/*
* Fragment Content
*/
Grammar builtInFragmentContentGrammar = new BuiltInFragmentContent();
/*
* Fragment
*/
fragmentGrammar = new Fragment("Fragment");
fragmentGrammar.addProduction(new StartDocument(),
builtInFragmentContentGrammar);
return fragmentGrammar;
} |
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 injector = Tang.Factory.getTang().newInjector();
injector.bindVolatileParameter(RemoteConfiguration.HostAddress.class, this.localAddress);
injector.bindVolatileParameter(RemoteConfiguration.Port.class, port);
injector.bindVolatileParameter(RemoteConfiguration.RemoteClientStage.class, new SyncStage<>(clientHandler));
injector.bindVolatileParameter(RemoteConfiguration.RemoteServerStage.class, new SyncStage<>(serverHandler));
final Transport transport;
try {
transport = injector.getInstance(NettyMessagingTransport.class);
transport.registerErrorHandler(exHandler);
return transport;
} catch (final InjectionException e) {
throw new RuntimeException(e);
}
} |
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"), hasAttribute("type", StoreOperationOutcomes.EvictionOutcome.class)))))
.build();
Set<TreeNode> statResult = statQuery.execute(Collections.singleton(ContextManager.nodeFor(cache)));
if (statResult.isEmpty()) {
throw new RuntimeException("Failed to find tiers using the eviction observer, valid result Set sizes must 1 or more");
}
String[] tiers = new String[statResult.size()];
int i = 0;
for (TreeNode treeNode : statResult) {
Set<?> tags = (Set<?>) treeNode.getContext().attributes().get("tags");
if (tags.size() != 1) {
throw new RuntimeException("We expect tiers to have only one tag");
}
String storeType = tags.iterator().next().toString();
tiers[i++] = storeType;
}
return tiers;
} |
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`
.. doctest::
>>> from retask import Queue
>>> q = Queue('test')
>>> q.connect()
True
>>> t = q.dequeue()
>>> print t.data
{u'name': u'kushal'}
"""
if not self.connected:
raise ConnectionError('Queue is not connected')
if self.rdb.llen(self._name) == 0:
return None
data = self.rdb.rpop(self._name)
if not data:
return None
if isinstance(data, six.binary_type):
data = six.text_type(data, 'utf-8', errors = 'replace')
task = Task()
task.__dict__ = json.loads(data)
return task |
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, 'IsIdentity')",
# (connection.ops.quote_name(table_name), column_name))
cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, 'IsIdentity')",
(self.connection.ops.quote_name(table_name), column_name))
return cursor.fetchall()[0][0] |
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 reply = new ContextReply()
.setUserName(context.getPerson().getName())
.setUserLastName(context.getPerson().getLastName())
.setUserFirstName(context.getPerson().getFirstName())
.setCompanyName(context.getCompany().getName())
.setLocale(context.getLocale().toString());
ret = Response.ok().type(MediaType.APPLICATION_JSON).entity(getJSONReply(reply)).build();
} catch (final Exception e) {
RestContext.LOG.error("Error processing data.", e);
final ErrorReply reply = new ErrorReply()
.setError(e.getClass().getName())
.setMessage(e.getMessage())
.setStacktrace(ExceptionUtils.getStackTrace(e));
ret = Response.serverError().type(MediaType.APPLICATION_JSON).entity(getJSONReply(reply)).build();
}
return ret;
} |
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);
queryBldr.addWhereAttrEqValue(CIAdminIndex.IndexDefinition.TypeLink, type.getId());
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CIAdminIndex.IndexDefinition.MsgPhraseLink);
multi.executeWithoutAccessCheck();
IndexDefinition def;
if (multi.next()) {
def = new IndexDefinition(_typeUUID,
multi.<Long>getAttribute(CIAdminIndex.IndexDefinition.MsgPhraseLink));
final QueryBuilder fieldQueryBldr = new QueryBuilder(CIAdminIndex.IndexField);
fieldQueryBldr.addWhereAttrEqValue(CIAdminIndex.IndexField.DefinitionLink, multi.getCurrentInstance());
final MultiPrintQuery fieldMulti = fieldQueryBldr.getPrint();
fieldMulti.addAttribute(CIAdminIndex.IndexField.Key, CIAdminIndex.IndexField.Select,
CIAdminIndex.IndexField.FieldType, CIAdminIndex.IndexField.Identifier);
final SelectBuilder selTransName = SelectBuilder.get().linkto(CIAdminIndex.IndexField.TransformerLink)
.attribute(CIAdminProgram.Java.Name);
fieldMulti.addSelect(selTransName);
fieldMulti.executeWithoutAccessCheck();
while (fieldMulti.next()) {
final IndexField field = new IndexField(fieldMulti.<String>getAttribute(
CIAdminIndex.IndexField.Identifier),
fieldMulti.<String>getAttribute(CIAdminIndex.IndexField.Key),
fieldMulti.<String>getAttribute(CIAdminIndex.IndexField.Select),
fieldMulti.<FieldType>getAttribute(CIAdminIndex.IndexField.FieldType),
fieldMulti.<String>getSelect(selTransName));
def.fields.add(field);
}
} else {
def = NULLINDEXDEF;
}
final Cache<UUID, IndexDefinition> cache = InfinispanCache.get().<UUID, IndexDefinition>getCache(
IndexDefinition.UUIDCACHE);
cache.put(_typeUUID, def);
// only if it is not a null index check if it must be joined with parent index definitions
final List<IndexDefinition> defs = new ArrayList<>();
Type current = type;
while (current.getParentType() != null) {
current = current.getParentType();
final IndexDefinition parentDef = get(current.getUUID());
if (parentDef != null) {
defs.add(parentDef);
}
}
boolean dirty = false;
for (final IndexDefinition parentDef : defs) {
for (final IndexField parentField : parentDef.fields) {
boolean found = false;
if (def.equals(NULLINDEXDEF)) {
def = new IndexDefinition(_typeUUID, parentDef.msgPhraseId);
}
for (final IndexField currentField : def.fields) {
if (currentField.getIdentifier().equals(parentField.getIdentifier())) {
found = true;
break;
}
}
if (!found) {
def.fields.add(new IndexField(parentField.getIdentifier(), parentField.getKey(),
parentField.getSelect(), parentField.getFieldType(), parentField.getTransform()));
dirty = true;
}
}
}
if (dirty) {
cache.put(_typeUUID, def);
}
} |
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 credential definition to ledger if need be, WalletState for closed wallet,
or IndyError for any other failure to create and store credential definition in wallet.
:param s_id: schema identifier
:param revo: whether to support revocation for cred def
:param rr_size: size of initial revocation registry (default as per RevRegBuilder.create_rev_reg()),
if revocation supported
:return: json credential definition as it appears on ledger
"""
LOGGER.debug('Issuer.send_cred_def >>> s_id: %s, revo: %s, rr_size: %s', s_id, revo, rr_size)
if not ok_schema_id(s_id):
LOGGER.debug('Issuer.send_cred_def <!< Bad schema id %s', s_id)
raise BadIdentifier('Bad schema id {}'.format(s_id))
if not self.wallet.handle:
LOGGER.debug('Issuer.send_cred_def <!< Wallet %s is closed', self.name)
raise WalletState('Wallet {} is closed'.format(self.name))
if not self.pool:
LOGGER.debug('Issuer.send_cred_def <!< issuer %s has no pool', self.name)
raise AbsentPool('Issuer {} has no pool: cannot send cred def'.format(self.name))
rv_json = json.dumps({})
schema_json = await self.get_schema(schema_key(s_id))
schema = json.loads(schema_json)
cd_id = cred_def_id(self.did, schema['seqNo'], self.pool.protocol)
private_key_ok = True
with CRED_DEF_CACHE.lock:
try:
rv_json = await self.get_cred_def(cd_id)
LOGGER.info(
'Cred def on schema %s version %s already exists on ledger; Issuer %s not sending another',
schema['name'],
schema['version'],
self.name)
except AbsentCredDef:
pass # OK - about to create, store, and send it
(cred_def_json, private_key_ok) = await self._create_cred_def(schema, json.loads(rv_json), revo)
if not json.loads(rv_json): # checking the ledger returned no cred def: send it
req_json = await ledger.build_cred_def_request(self.did, cred_def_json)
await self._sign_submit(req_json)
for _ in range(16): # reasonable timeout
try:
rv_json = await self.get_cred_def(cd_id) # adds to cache
break
except AbsentCredDef:
await asyncio.sleep(1)
LOGGER.info('Sent cred def %s to ledger, waiting 1s for its appearance', cd_id)
if not rv_json:
LOGGER.debug('Issuer.send_cred_def <!< timed out waiting on sent cred_def %s', cd_id)
raise BadLedgerTxn('Timed out waiting on sent cred_def {}'.format(cd_id))
if revo: # create new rev reg for tag '0'
if self.rrbx:
(_, rr_size_suggested) = Tails.next_tag(self.dir_tails, cd_id)
self.rrb.mark_in_progress(rev_reg_id(cd_id, '0'), rr_size or rr_size_suggested)
await self._sync_revoc_for_issue(rev_reg_id(cd_id, '0'), rr_size) # sync rev reg on tag '0'
if revo and private_key_ok:
for tag in [str(t) for t in range(1, int(Tails.next_tag(self.dir_tails, cd_id)[0]))]: # '1' to next-1
await self._sync_revoc_for_issue(rev_reg_id(cd_id, tag), rr_size if tag == '0' else None)
makedirs(join(self.dir_tails, cd_id), exist_ok=True) # dir required for box id collection, revo or not
LOGGER.debug('Issuer.send_cred_def <<< %s', rv_json)
return rv_json |
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)) {
if (f.getType() == ARRAY_OF_FIELDS) {
return f;
}
}
} catch (NoSuchFieldException nsm) {
// Ignored
}
return null;
} |
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) //
| ((buf[offset + 2] & 0xffL) << 40) //
| ((buf[offset + 3] & 0xffL) << 32) //
| ((buf[offset + 4] & 0xffL) << 24) //
| ((buf[offset + 5] & 0xffL) << 16) //
| ((buf[offset + 6] & 0xffL) << 8) //
| (buf[offset + 7] & 0xffL);
} |
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)
rn(3).element([ 2., 4., 6.])
>>> op.adjoint(x) # The same
rn(3).element([ 2., 4., 6.])
In the complex case, the scalar is conjugated:
>>> c3 = odl.cn(3)
>>> x_complex = c3.element([1, 1j, 1-1j])
>>> op = ScalingOperator(c3, 1+1j)
>>> expected_op = ScalingOperator(c3, 1-1j)
>>> op.adjoint(x_complex)
cn(3).element([ 1.-1.j, 1.+1.j, 0.-2.j])
>>> expected_op(x_complex) # The same
cn(3).element([ 1.-1.j, 1.+1.j, 0.-2.j])
Returns
-------
adjoint : `ScalingOperator`
``self`` if `scalar` is real, else `scalar` is conjugated.
"""
if complex(self.scalar).imag == 0.0:
return self
else:
return ScalingOperator(self.domain, self.scalar.conjugate()) |
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();
buttonPrev = new javax.swing.JButton();
buttonNext = new javax.swing.JButton();
labelClose = new javax.swing.JLabel();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(0, 0), new java.awt.Dimension(32767, 0));
toggleButtonCaseSensitive = new javax.swing.JToggleButton();
panelButtonsForMap = new javax.swing.JPanel();
toggleButtonTopicText = new javax.swing.JToggleButton();
toggleButtonNote = new javax.swing.JToggleButton();
toggleButtonFile = new javax.swing.JToggleButton();
toggleButtonURI = new javax.swing.JToggleButton();
setLayout(new java.awt.GridBagLayout());
labelTitle.setText("Find:");
labelTitle.setFocusable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 10.0;
gridBagConstraints.insets = new java.awt.Insets(0, 16, 0, 8);
add(labelTitle, gridBagConstraints);
textFieldSearchText.setFocusTraversalPolicyProvider(true);
textFieldSearchText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
textFieldSearchTextKeyPressed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 16);
add(textFieldSearchText, gridBagConstraints);
buttonPrev.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/resultset_previous.png"))); // NOI18N
buttonPrev.setToolTipText("Find previous (SHFT+ENTER)");
buttonPrev.setFocusable(false);
buttonPrev.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonPrevActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 10.0;
add(buttonPrev, gridBagConstraints);
buttonNext.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/resultset_next.png"))); // NOI18N
buttonNext.setToolTipText("Find next (ENTER)");
buttonNext.setFocusable(false);
buttonNext.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buttonNextActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 10.0;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 16);
add(buttonNext, gridBagConstraints);
labelClose.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
labelClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/nimbusCloseFrame.png"))); // NOI18N
labelClose.setToolTipText("Close search form (ESC)");
labelClose.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
labelClose.setFocusable(false);
labelClose.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
labelCloseMouseClicked(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 7;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 8);
add(labelClose, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 6;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 100000.0;
add(filler1, gridBagConstraints);
toggleButtonCaseSensitive.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/find/case16.png"))); // NOI18N
toggleButtonCaseSensitive.setToolTipText("Case sensitive mode");
toggleButtonCaseSensitive.setFocusable(false);
toggleButtonCaseSensitive.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
toggleButtonCaseSensitiveActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 4;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 8);
add(toggleButtonCaseSensitive, gridBagConstraints);
panelButtonsForMap.setLayout(new java.awt.GridBagLayout());
toggleButtonTopicText.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/find/text16.png"))); // NOI18N
toggleButtonTopicText.setToolTipText("Find in topic title");
toggleButtonTopicText.setFocusable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
panelButtonsForMap.add(toggleButtonTopicText, gridBagConstraints);
toggleButtonNote.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/find/note16.png"))); // NOI18N
toggleButtonNote.setToolTipText("Find in topic notes");
toggleButtonNote.setFocusable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
panelButtonsForMap.add(toggleButtonNote, gridBagConstraints);
toggleButtonFile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/find/disk16.png"))); // NOI18N
toggleButtonFile.setToolTipText("Find in file links");
toggleButtonFile.setFocusable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
panelButtonsForMap.add(toggleButtonFile, gridBagConstraints);
toggleButtonURI.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/find/url16.png"))); // NOI18N
toggleButtonURI.setToolTipText("Find in URI links");
toggleButtonURI.setFocusable(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
panelButtonsForMap.add(toggleButtonURI, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 5;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
add(panelButtonsForMap, gridBagConstraints);
} |
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 (int i = 0; i < numSerializersAndConfigSnapshots; i++) {
offsets[i * 2] = in.readInt();
offsets[i * 2 + 1] = in.readInt();
}
int totalBytes = in.readInt();
byte[] buffer = new byte[totalBytes];
in.readFully(buffer);
List<Tuple2<TypeSerializer<?>, TypeSerializerSnapshot<?>>> serializersAndConfigSnapshots =
new ArrayList<>(numSerializersAndConfigSnapshots);
TypeSerializer<?> serializer;
TypeSerializerSnapshot<?> configSnapshot;
try (
ByteArrayInputStreamWithPos bufferWithPos = new ByteArrayInputStreamWithPos(buffer);
DataInputViewStreamWrapper bufferWrapper = new DataInputViewStreamWrapper(bufferWithPos)) {
for (int i = 0; i < numSerializersAndConfigSnapshots; i++) {
bufferWithPos.setPosition(offsets[i * 2]);
serializer = tryReadSerializer(bufferWrapper, userCodeClassLoader, true);
bufferWithPos.setPosition(offsets[i * 2 + 1]);
configSnapshot = TypeSerializerSnapshotSerializationUtil.readSerializerSnapshot(
bufferWrapper, userCodeClassLoader, serializer);
if (serializer instanceof LegacySerializerSnapshotTransformer) {
configSnapshot = transformLegacySnapshot(serializer, configSnapshot);
}
serializersAndConfigSnapshots.add(new Tuple2<>(serializer, configSnapshot));
}
}
return serializersAndConfigSnapshots;
} |
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 =
new DefaultWebSocketHandshaker(ctx, serverConnectorFuture, fullHttpRequest, fullHttpRequest.uri(),
extensionsHeader != null);
// Setting common properties to handshaker
webSocketHandshaker.setHttpCarbonRequest(setupHttpCarbonRequest(fullHttpRequest, ctx));
ctx.channel().config().setAutoRead(false);
serverConnectorFuture.notifyWebSocketListener(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 {
try {
this.dateTimeZone = DateTimeZone.forID((String) dtz);
} catch (IllegalArgumentException iae) {
this.dateTimeZone = DateTimeZone.UTC;
}
}
} |
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 argument.
"""
request_ = (request_context or _request_ctx_stack.top).request
blueprint = request_.blueprint
processors = self.url_value_preprocessors[None]
if blueprint is not None:
processors = chain(processors, self.url_value_preprocessors[blueprint]) # type: ignore
for processor in processors:
processor(request.endpoint, request.view_args)
functions = self.before_request_funcs[None]
if blueprint is not None:
functions = chain(functions, self.before_request_funcs[blueprint]) # type: ignore
for function in functions:
result = await function()
if result is not None:
return result
return None |
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=True,
)
for matcher, value in items:
if matcher.info is None:
pattern_with_port = "https://{0}:".format(hostname)
pattern_without_port = "https://{0}/".format(hostname)
hostname_pattern = (
hostname_re
.match(matcher.regex.pattern)
.group(0)
)
for pattern in [pattern_with_port, pattern_without_port]:
if re.match(hostname_pattern, pattern):
return matcher
elif matcher.info.hostname == hostname:
return matcher
return None |
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) {
return false;
}
}
} |
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 PropertyMeta(field.getSimpleName().toString(), type));
}
}
} |
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_or_url),
fg='red', file=sys.stderr)
continue
# Name and summary
try:
info = package.data['info']
except NotFoundError:
secho(u'No versions found for "{0}". '
u'Skipping. . .'.format(package.name),
fg='red', file=sys.stderr)
continue
echo_header(name_or_url)
if package.summary:
echo(package.summary)
# Version info
echo()
echo('Latest release: {version:12}'.format(version=info['version']))
# Long description
if long_description:
echo()
echo(package.description)
# Download info
echo()
echo_download_summary(package)
# Author info
echo()
author, author_email = package.author, package.author_email
if author:
echo(u'Author: {author:12}'.format(**locals()))
if author_email:
echo(u'Author email: {author_email:12}'.format(**locals()))
# Maintainer info
maintainer, maintainer_email = (package.maintainer,
package.maintainer_email)
if maintainer or maintainer_email:
echo()
if maintainer:
echo(u'Maintainer: {maintainer:12}'.format(**locals()))
if maintainer_email:
echo(u'Maintainer email: {maintainer_email:12}'.format(**locals()))
# URLS
echo()
echo(u'PyPI URL: {pypi_url:12}'.format(pypi_url=package.package_url))
if package.home_page:
echo(u'Home Page: {home_page:12}'.format(
home_page=package.home_page))
if package.docs_url:
echo(u'Documentation: {docs_url:12}'.format(
docs_url=package.docs_url))
# Classifiers
if classifiers:
echo()
echo(u'Classifiers: ')
for each in info.get('classifiers', []):
echo('\t' + each)
if license and package.license:
echo()
echo(u'License: ', nl=False)
# license may be just a name, e.g. 'BSD' or the full license text
# If a new line is found in the text, print a new line
if package.license.find('\n') >= 0 or len(package.license) > 80:
echo()
echo(package.license)
echo() |
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 = {}
raw_data = []
for key in sorted(excluded):
locations = excluded[key]
for location in locations:
assert location in self.locations, "Can't find location {}".format(location)
included = self.all_faces.difference(
{face for loc in locations for face in self.data[loc]}
)
raw_data.append((key, self.faces_fp, included))
if use_mp:
with Pool(cpu_count() - 1) as pool:
results = pool.map(_union, raw_data)
geoms = dict(results)
else:
geoms = dict([_union(row) for row in raw_data])
if simplify:
geoms = {k: v.simplify(0.05) for k, v in geoms.items()}
if fp:
labels = sorted(geoms)
self.write_geoms_to_file(fp, [geoms[key] for key in labels], labels)
return fp
else:
return 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 target joint angles.
"""
dpos_right = right["dpos"]
dpos_left = left["dpos"]
self.target_pos_right = self.ik_robot_target_pos_right + np.array([0, 0, 0.913])
self.target_pos_left = self.ik_robot_target_pos_left + np.array([0, 0, 0.913])
self.ik_robot_target_pos_right += dpos_right
self.ik_robot_target_pos_left += dpos_left
rotation_right = right["rotation"]
rotation_left = left["rotation"]
self.ik_robot_target_orn_right = T.mat2quat(rotation_right)
self.ik_robot_target_orn_left = T.mat2quat(rotation_left)
# convert from target pose in base frame to target pose in bullet world frame
world_targets_right = self.bullet_base_pose_to_world_pose(
(self.ik_robot_target_pos_right, self.ik_robot_target_orn_right)
)
world_targets_left = self.bullet_base_pose_to_world_pose(
(self.ik_robot_target_pos_left, self.ik_robot_target_orn_left)
)
# Empirically, more iterations aren't needed, and it's faster
for _ in range(5):
arm_joint_pos = self.inverse_kinematics(
world_targets_right[0],
world_targets_right[1],
world_targets_left[0],
world_targets_left[1],
rest_poses=self.robot_jpos_getter(),
)
self.sync_ik_robot(arm_joint_pos, sync_last=True)
return arm_joint_pos |
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);
if (namespace != null) {
parameters.put("namespace", namespace);
}
if (predicate != null) {
parameters.put("predicate", predicate);
}
if (perPage > 0) {
parameters.put("per_page", "" + perPage);
}
if (page > 0) {
parameters.put("page", "" + page);
}
Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element nsElement = response.getPayload();
NodeList nsNodes = nsElement.getElementsByTagName("value");
valuesList.setPage(nsElement.getAttribute("page"));
valuesList.setPages(nsElement.getAttribute("pages"));
valuesList.setPerPage(nsElement.getAttribute("perPage"));
valuesList.setTotal("" + nsNodes.getLength());
for (int i = 0; i < nsNodes.getLength(); i++) {
Element element = (Element) nsNodes.item(i);
Value value = parseValue(element);
value.setNamespace(namespace);
value.setPredicate(predicate);
valuesList.add(value);
}
return valuesList;
} |
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);
RTMPMinaConnection conn = (RTMPMinaConnection) getConnectionManager(session).getConnectionBySessionId(sessionId);
handler.messageSent(conn, (Packet) message);
} else {
log.trace("messageSent: {}", Hex.encodeHexString(((IoBuffer) message).array()));
}
} |
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 looking to populate this variable should
do so via calling thisObj._set_vni_mask() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'0|[1-9a-fA-F][0-9a-fA-F]{0,5}'}), is_leaf=True, yang_name="vni-mask", rest_name="vni-mask", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'vni mask:Hexadecimal 0..FFFFFF', u'display-when': u'not(../vni-any)', u'cli-suppress-no': None}}, namespace='urn:brocade.com:mgmt:brocade-vxlan-visibility', defining_module='brocade-vxlan-visibility', yang_type='string', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """vni_mask must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'0|[1-9a-fA-F][0-9a-fA-F]{0,5}'}), is_leaf=True, yang_name="vni-mask", rest_name="vni-mask", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'vni mask:Hexadecimal 0..FFFFFF', u'display-when': u'not(../vni-any)', u'cli-suppress-no': None}}, namespace='urn:brocade.com:mgmt:brocade-vxlan-visibility', defining_module='brocade-vxlan-visibility', yang_type='string', is_config=True)""",
})
self.__vni_mask = t
if hasattr(self, '_set'):
self._set() |
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.
"""
return self.detectIpad() \
or self.detectAndroidTablet() \
or self.detectBlackBerryTablet() \
or self.detectFirefoxOSTablet() \
or self.detectUbuntuTablet() \
or self.detectWebOSTablet() |
java | static Object extractAttributeValue(Extractors extractors, InternalSerializationService serializationService,
String attributeName, Data key, Object value, Object metadata) throws QueryException {
Object result = extractAttributeValueIfAttributeQueryConstant(serializationService, attributeName, key, value);
if (result == null) {
boolean isKey = startsWithKeyConstant(attributeName);
attributeName = getAttributeName(isKey, attributeName);
Object target = isKey ? key : value;
result = extractAttributeValueFromTargetObject(extractors, attributeName, target, metadata);
}
return result;
} |
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
"""
return cls(distance_cutoff=d["distance_cutoff"], angle_cutoff=d["angle_cutoff"],
additional_condition=d["additional_condition"],
continuous_symmetry_measure_cutoff=d["continuous_symmetry_measure_cutoff"],
symmetry_measure_type=d["symmetry_measure_type"]) |
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): Name of the NIC.
Returns:
HTTP response.
'''
endpoint = ''.join([get_rm_endpoint(),
'/subscriptions/', subscription_id,
'/resourceGroups/', resource_group,
'/providers/Microsoft.Network/networkInterfaces/', nic_name,
'?api-version=', NETWORK_API])
return do_delete(endpoint, access_token) |
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 store info in a cache """
cache = args[0].memoized
refresh = args[0].refresh_interval
use_cache = args[0].use_cache
# short circuit if not using cache
if use_cache is False:
return func(*args, **kwargs)
if func.__name__ not in cache:
cache[func.__name__] = dict()
if "defaults" not in cache:
cache["defaults"] = dict()
cache["defaults"][func.__name__] = parse_all_arguments(func)
# build a key; should also consist of the default values
defaults = cache["defaults"][func.__name__].copy()
for key, val in kwargs.items():
defaults[key] = val
tmp = list()
tmp.extend(args[1:])
for k in sorted(defaults.keys()):
tmp.append("({0}: {1})".format(k, defaults[k]))
# handle possible unicode characters
if sys.version_info < (3, 0):
tmp = [unicode(x) for x in tmp]
key = " - ".join(tmp)
# set the value in the cache if missing or needs to be refreshed
if key not in cache[func.__name__]:
cache[func.__name__][key] = (time.time(), func(*args, **kwargs))
else:
tmp = cache[func.__name__][key]
# determine if we need to refresh the data...
if refresh is not None and time.time() - tmp[0] > refresh:
cache[func.__name__][key] = (time.time(), func(*args, **kwargs))
return cache[func.__name__][key][1]
return wrapper |
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:
self.editor.decorations.remove(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 : state.getProperties().keySet())
{
if ((prop.getName().equals("variant") || relaxRequirements) && prop.getValueClass().isEnum())
{
Object[] values = prop.getValueClass().getEnumConstants();
for (Object obj : values)
{
if (obj != null && obj.toString().equalsIgnoreCase(variant.getValue()))
{
return state.withProperty(prop, (Comparable) obj);
}
}
}
}
relaxRequirements = true; // Failed to set the variant, so try again with other properties.
}
return state;
} |
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: {}", claimID);
return false;
}
String claimingHost = m_hostClaimID;
long earliestClaim = Long.MAX_VALUE;
while (colIter.hasNext()) {
DColumn col = colIter.next();
try {
long claimStamp = Long.parseLong(col.getValue());
// otarakanov: sometimes, the task writes a claim but does not start. The claim remains the lowest
// and makes future tries to write new claims but not start.
// we disregard claims older that ten minutes.
long secondsSinceClaim = (System.currentTimeMillis() - claimStamp) / 1000;
if(secondsSinceClaim > 600) continue;
String claimHost = col.getName();
if (claimStamp < earliestClaim) {
claimingHost = claimHost;
earliestClaim = claimStamp;
} else if (claimStamp == earliestClaim) {
// Two nodes chose the same claim stamp. Lower node name wins.
if (claimHost.compareTo(claimingHost) < 0) {
claimingHost = claimHost;
}
}
} catch (NumberFormatException e) {
// Ignore this column
}
}
return claimingHost.equals(m_hostClaimID) && !m_bShutdown;
} |
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 ConfigException.WrongType) {
LOGGER.warn(e.getMessage(), e);
}
return null;
}
} |
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__ARRAY_TYPE, oldArrayType, newArrayType);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
} |
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 that the named extension is present.
.. note::
Before you can use the state to load an extension into a database, the
extension's supporting files must be already installed.
For more information about all of these options see ``CREATE EXTENSION`` SQL
command reference in the PostgreSQL documentation.
name
The name of the extension to be installed
if_not_exists
Add an ``IF NOT EXISTS`` parameter to the DDL statement
schema
Schema to install the extension into
ext_version
Version to install
from_version
Old extension version if already installed
user
System user all operations should be performed on behalf of
maintenance_db
Database to act on
db_user
Database username if different from config or default
db_password
User password if any password for a specified user
db_host
Database host if different from config or default
db_port
Database port if different from config or default
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Extension {0} is already present'.format(name)}
db_args = {
'maintenance_db': maintenance_db,
'runas': user,
'user': db_user,
'password': db_password,
'host': db_host,
'port': db_port,
}
# check if extension exists
mode = 'create'
mtdata = __salt__['postgres.create_metadata'](
name,
schema=schema,
ext_version=ext_version,
**db_args)
# The extension is not present, install it!
toinstall = postgres._EXTENSION_NOT_INSTALLED in mtdata
if toinstall:
mode = 'install'
toupgrade = False
if postgres._EXTENSION_INSTALLED in mtdata:
for flag in [
postgres._EXTENSION_TO_MOVE,
postgres._EXTENSION_TO_UPGRADE
]:
if flag in mtdata:
toupgrade = True
mode = 'upgrade'
cret = None
if toinstall or toupgrade:
if __opts__['test']:
ret['result'] = None
if mode:
ret['comment'] = 'Extension {0} is set to be {1}ed'.format(
name, mode).replace('eed', 'ed')
return ret
cret = __salt__['postgres.create_extension'](
name=name,
if_not_exists=if_not_exists,
schema=schema,
ext_version=ext_version,
from_version=from_version,
**db_args)
if cret:
if mode.endswith('e'):
suffix = 'd'
else:
suffix = 'ed'
ret['comment'] = 'The extension {0} has been {1}{2}'.format(name, mode, suffix)
ret['changes'][name] = '{0}{1}'.format(mode.capitalize(), suffix)
elif cret is not None:
ret['comment'] = 'Failed to {1} extension {0}'.format(name, mode)
ret['result'] = False
return ret |
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 createApplicationFormat(payload, description);
default:
return null;
}
} |
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:
https://stackoverflow.com/a/8261083/1958900
"""
target = get_target_path(destination, self.dirname)
valid_paths = (self.dirname, './%s' % self.dirname)
with tarfile.open(self.archive_path, 'r:*') as tf:
members = []
for tarinfo in tf:
# Get only files under the directory `self.dirname`
pathsplit = os.path.normpath(tarinfo.path).split(os.sep)
if pathsplit[0] not in valid_paths:
print('WARNING: skipped file "%s" in archive; not in directory "%s"' %
(tarinfo.path, self.dirname))
continue
if len(pathsplit) == 1:
continue
tarinfo.name = os.path.join(*pathsplit[1:])
members.append(tarinfo)
if not members:
raise ValueError("No files under path directory '%s' in this tarfile")
tf.extractall(target, members) |
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 = new MovielensParser();
DataModelIF<Long, Long> data = null;
try {
data = parser.parseData(new File(inFile));
} catch (IOException e) {
e.printStackTrace();
}
new IterativeCrossValidationSplitter<Long, Long>(nFolds, perUser, seed, outPath).split(data);
File dir = new File(outPath);
if (!dir.exists()) {
if (!dir.mkdir()) {
System.err.println("Directory " + dir + " could not be created");
return;
}
}
} |
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:
logger.warning('could not unlink resume db: {}'.format(e))
for ext in ('.bak', '.dat', '.dir'): # noqa
fp = pathlib.Path(str(self._resume_file) + ext)
if fp.exists():
try:
fp.unlink()
except OSError as e:
logger.warning('could not unlink resume db: {}'.format(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(j) || Character.isLowerCase(j) || Character.isUpperCase(j)) {
tmp.append(j);
} else if (j < 256) {
tmp.append("%");
if (j < 16) {
tmp.append("0");
}
tmp.append(Integer.toString(j, 16));
} else {
tmp.append("%u");
tmp.append(Integer.toString(j, 16));
}
}
return tmp.toString();
} |
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.bytes, byteRef.offset, byteRef.length);
for (String token : tokens) {
if (term.contains(" " + token + " ")) {
String[] split = term.split(" ");
if (split.length == 3) {
long count = getCount(Arrays.asList(split[0], split[1], split[2]));
result.put(term, count);
}
}
}
/*if (i++ > 1_000_000) { // comment in for faster testing with subsets of the data
break;
}*/
}
return result;
} |
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 = self.uid[line_idx]
if bus_idx == self.bus1[line_int]:
P.append(self.P1[line_int])
Q.append(self.Q1[line_int])
elif bus_idx == self.bus2[line_int]:
P.append(self.P2[line_int])
Q.append(self.Q2[line_int])
return matrix(P), matrix(Q) |
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
# will fail when retrieving data.
if not self._mapping_created:
logger.debug("Pushing mapping for Elasticsearch index '%s'.", self.__class__.__name__)
self.create_mapping()
if not self.push_queue:
logger.debug("No documents to push, skipping push.")
return
logger.debug("Found %s documents to push to Elasticsearch.", len(self.push_queue))
bulk(connections.get_connection(), (doc.to_dict(True) for doc in self.push_queue), refresh=True)
self.push_queue = []
logger.debug("Finished pushing builded documents to Elasticsearch server.") |
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, payload)
return rv['data']['data']['collectDetail'] |
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+1-flow.stride];
float u6 = flow.data[index-1+flow.stride];
float u7 = flow.data[index+1+flow.stride];
return (1.0f/6.0f)*(u0 + u1 + u2 + u3) + (1.0f/12.0f)*(u4 + u5 + u6 + u7);
} |
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 to
``'stagpy'``.
"""
if timestep is not None:
stem = (stem + INT_FMT).format(timestep)
return conf.core.outname + '_' + stem |
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();
if(MATCH_SEMI.apply(tk))
{
continue; //starting with ';' is allowed, Issue 238
}
try
{
CssDeclaration decl = handleDeclaration(tk, iter, doc, err, true);
if (decl != null)
{
doc.declaration(decl);
}
else
{
// #handleDeclaration has issued errors
return;
}
}
catch (PrematureEOFException te)
{
// The subroutines report premature EOF to ErrHandler
// on occurrence; if the listener rethrows it will
// be a CssException so we don't catch it here.
break;
}
}
doc.endDocument();
} |
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.
window_width : int
Width of the window where the peak must be found.
Returns
-------
xc, yc: tuple
X-coordinates in which the refined peaks have been found,
interpolated Y-coordinates
"""
_check_window_width(window_width)
step = window_width // 2
ipeaks = filter_array_margins(arr, ipeaks, window_width)
winoff = numpy.arange(-step, step+1, dtype='int')
peakwin = ipeaks[:, numpy.newaxis] + winoff
ycols = arr[peakwin]
ww = return_weights(window_width)
coff2 = numpy.dot(ww, ycols.T)
uc = -0.5 * coff2[1] / coff2[2]
yc = coff2[0] + uc * (coff2[1] + coff2[2] * uc)
xc = ipeaks + 0.5 * (window_width-1) * uc
return xc, yc |
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.disconnect(self._paint_margin)
self.editor.repaint() |