language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
|---|---|
python
|
def is_driver(self):
"""Check whether the file is a Windows driver.
This will return true only if there are reliable indicators of the image
being a driver.
"""
# Checking that the ImageBase field of the OptionalHeader is above or
# equal to 0x80000000 (that is, whether it lies in the upper 2GB of
# the address space, normally belonging to the kernel) is not a
# reliable enough indicator. For instance, PEs that play the invalid
# ImageBase trick to get relocated could be incorrectly assumed to be
# drivers.
# This is not reliable either...
#
# if any( (section.Characteristics & SECTION_CHARACTERISTICS['IMAGE_SCN_MEM_NOT_PAGED']) for section in self.sections ):
# return True
if hasattr(self, 'DIRECTORY_ENTRY_IMPORT'):
# If it imports from "ntoskrnl.exe" or other kernel components it should be a driver
#
if set( ('ntoskrnl.exe', 'hal.dll', 'ndis.sys', 'bootvid.dll', 'kdcom.dll' ) ).intersection( [ imp.dll.lower() for imp in self.DIRECTORY_ENTRY_IMPORT ] ):
return True
return False
|
python
|
def _parseAsteriskConf(self):
"""Parses Asterisk configuration file /etc/asterisk/manager.conf for
user and password for Manager Interface. Returns True on success.
@return: True if configuration file is found and parsed successfully.
"""
if os.path.isfile(confFileAMI):
try:
fp = open(confFileAMI, 'r')
data = fp.read()
fp.close()
except:
raise IOError('Failed reading Asterisk configuration file: %s'
% confFileAMI)
mobj = re.search('^\[(\w+)\]\s*\r{0,1}\nsecret\s*=\s*(\S+)\s*$',
data, re.MULTILINE)
if mobj:
self._amiuser = mobj.group(1)
self._amipass = mobj.group(2)
return True
return False
|
java
|
@Deprecated
public void writeTo(T object, int baseVisibility, DataWriter writer) throws IOException {
writeTo(object,new ByDepth(1-baseVisibility),writer);
}
|
python
|
def open(self):
"""Open an existing database and load its content into memory"""
# guess protocol
if self.protocol==0:
_in = open(self.name) # don't specify binary mode !
else:
_in = open(self.name,'rb')
self.fields = cPickle.load(_in)
self.next_id = cPickle.load(_in)
self.records = cPickle.load(_in)
self.indices = cPickle.load(_in)
for f in self.indices.keys():
setattr(self,'_'+f,Index(self,f))
_in.close()
self.mode = "open"
return self
|
java
|
public void setDashIngestErrors(com.google.api.ads.admanager.axis.v201902.DaiIngestError[] dashIngestErrors) {
this.dashIngestErrors = dashIngestErrors;
}
|
java
|
public Vector3d mul(double scalar, Vector3d dest) {
dest.x = x * scalar;
dest.y = y * scalar;
dest.z = z * scalar;
return dest;
}
|
java
|
public static FormValidation error(String format, Object... args) {
return error(String.format(format,args));
}
|
python
|
def disable_node(self, service_name, node_name):
"""
Disables a given node name for the given service name via the
"disable server" HAProxy command.
"""
logger.info("Disabling server %s/%s", service_name, node_name)
return self.send_command(
"disable server %s/%s" % (service_name, node_name)
)
|
java
|
public void extractFromArchive(final File targetFile, final boolean forceOverwrite) throws IOException {
if (zipArchive != null) {
ZipEntry entry = zipArchive.getEntry(targetFile.getName());
if (entry != null) {
if (!targetFile.exists()) {
try {
targetFile.createNewFile();
} catch (IOException ex) {
throw new JFunkException("Error creating file: " + targetFile, ex);
}
} else if (!forceOverwrite) {
return;
}
logger.info("Loading file '{}' from zip archive...", targetFile);
OutputStream out = null;
InputStream in = null;
try {
out = new FileOutputStream(targetFile);
in = zipArchive.getInputStream(entry);
IOUtils.copy(in, out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
} else {
logger.error("Could not find file '{}' in zip archive", targetFile);
}
}
}
|
java
|
public static EntityGetOperation<JobInfo> get(String jobId) {
return new DefaultGetOperation<JobInfo>(ENTITY_SET, jobId,
JobInfo.class);
}
|
python
|
def get_patches_base(self, expand_macros=False):
"""Return a tuple (version, number_of_commits) that are parsed
from the patches_base in the specfile.
"""
match = re.search(r'(?<=patches_base=)[\w.+?%{}]+', self.txt)
if not match:
return None, 0
patches_base = match.group()
if expand_macros and has_macros(patches_base):
# don't parse using rpm unless required
patches_base = self.expand_macro(patches_base)
patches_base_ref, _, n_commits = patches_base.partition('+')
try:
n_commits = int(n_commits)
except ValueError:
n_commits = 0
return patches_base_ref, n_commits
|
python
|
def create(self, instance):
"""
Create a new model instance.
"""
with self.flushing():
if instance.id is None:
instance.id = self.new_object_id()
self.session.add(instance)
return instance
|
java
|
public double[] solveLInplace(double[] X) {
final int n = L.length;
X[0] /= L[0][0]; // First iteration, simplified.
for(int k = 1; k < n; k++) {
final double[] Lk = L[k];
for(int i = 0; i < k; i++) {
X[k] -= X[i] * Lk[i];
}
X[k] /= Lk[k];
}
return X;
}
|
java
|
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.GSPT__PATT:
return getPATT();
}
return super.eGet(featureID, resolve, coreType);
}
|
python
|
def split_escape(string, sep, maxsplit=None, escape_char="\\"):
"""Like unicode/str/bytes.split but allows for the separator to be escaped
If passed unicode/str/bytes will only return list of unicode/str/bytes.
"""
assert len(sep) == 1
assert len(escape_char) == 1
if isinstance(string, bytes):
if isinstance(escape_char, text_type):
escape_char = escape_char.encode("ascii")
iter_ = iterbytes
else:
iter_ = iter
if maxsplit is None:
maxsplit = len(string)
empty = string[:0]
result = []
current = empty
escaped = False
for char in iter_(string):
if escaped:
if char != escape_char and char != sep:
current += escape_char
current += char
escaped = False
else:
if char == escape_char:
escaped = True
elif char == sep and len(result) < maxsplit:
result.append(current)
current = empty
else:
current += char
result.append(current)
return result
|
python
|
def random_name():
"""Return a random name
Example:
>> random_name()
dizzy_badge
>> random_name()
evasive_cactus
"""
adj = _data.adjectives[random.randint(0, len(_data.adjectives) - 1)]
noun = _data.nouns[random.randint(0, len(_data.nouns) - 1)]
return "%s_%s" % (adj, noun)
|
java
|
@Override
public java.util.Iterator findMemberGroups(IEntityGroup group) throws GroupsException {
String[] keys = findMemberGroupKeys(group); // No foreign groups here.
List groups = new ArrayList(keys.length);
for (int i = 0; i < keys.length; i++) {
groups.add(find(keys[i]));
}
return groups.iterator();
}
|
python
|
def print_docs(self):
'''
Pick up the documentation for all of the modules and print it out.
'''
docs = {}
for name, func in six.iteritems(self.minion.functions):
if name not in docs:
if func.__doc__:
docs[name] = func.__doc__
for name in sorted(docs):
if name.startswith(self.opts.get('fun', '')):
salt.utils.stringutils.print_cli('{0}:\n{1}\n'.format(name, docs[name]))
|
python
|
def add_rule(self, **args):
"""
@param args keyword argument list, consisting of:
source: <source service name>,
dest: <destination service name>,
messagetype: <request|response|publish|subscribe|stream>
headerpattern: <regex to match against the value of the X-Gremlin-ID trackingheader present in HTTP headers>
bodypattern: <regex to match against HTTP message body>
delayprobability: <float, 0.0 to 1.0>
delaydistribution: <uniform|exponential|normal> probability distribution function
mangleprobability: <float, 0.0 to 1.0>
mangledistribution: <uniform|exponential|normal> probability distribution function
abortprobability: <float, 0.0 to 1.0>
abortdistribution: <uniform|exponential|normal> probability distribution function
delaytime: <string> latency to inject into requests <string, e.g., "10ms", "1s", "5m", "3h", "1s500ms">
errorcode: <Number> HTTP error code or -1 to reset TCP connection
searchstring: <string> string to replace when Mangle is enabled
replacestring: <string> string to replace with for Mangle fault
"""
#The defaults are indicated below
myrule = {
"source": "",
"dest": "",
"messagetype": "request",
"headerpattern": "*",
"bodypattern": "*",
"delayprobability": 0.0,
"delaydistribution": "uniform",
"mangleprobability": 0.0,
"mangledistribution": "uniform",
"abortprobability": 0.0,
"abortdistribution": "uniform",
"delaytime": "0s",
"errorcode": -1,
"searchstring": "",
"replacestring": ""
}
rule = args.copy()
#copy
for i in rule.keys():
if i not in myrule:
continue
myrule[i] = rule[i]
#check defaults
services = self.app.get_services()
assert myrule["source"] != "" and myrule["dest"] != ""
assert myrule["source"] in services and myrule["dest"] in services
assert myrule['headerpattern'] != "" or myrule["bodypattern"] != ""
assert myrule['delayprobability'] >0.0 or myrule['abortprobability'] >0.0 or myrule['mangleprobability'] >0.0
if myrule["delayprobability"] > 0.0:
assert myrule["delaytime"] != ""
if myrule["abortprobability"] > 0.0:
assert myrule["errorcode"] >= -1
assert myrule["messagetype"] in ["request", "response", "publish", "subscribe"]
self._queue.append(myrule)
|
python
|
def input(self):
"""Returns a file-like object representing the request body."""
if self._input is None:
input_file = self.environ['wsgi.input']
content_length = self.content_length or 0
self._input = WsgiInput(input_file, self.content_length)
return self._input
|
java
|
private void approximateKnnDistances(MkCoPLeafEntry entry, KNNList knnDistances) {
StringBuilder msg = LOG.isDebugging() ? new StringBuilder(1000) : null;
if(msg != null) {
msg.append("knnDistances ").append(knnDistances);
}
DoubleDBIDListIter iter = knnDistances.iter();
// count the zero distances
int k_0 = 0;
for(iter.seek(0); iter.valid(); iter.advance()) {
if(iter.doubleValue() != 0) {
break;
}
k_0++;
}
// init variables
double[] log_k = new double[settings.kmax - k_0];
System.arraycopy(this.log_k, k_0, log_k, 0, settings.kmax - k_0);
double sum_log_kDist = 0, sum_log_k_kDist = 0;
double[] log_kDist = new double[settings.kmax - k_0];
iter.seek(k_0);
for(int i = 0; iter.valid(); iter.advance(), i++) {
final double logd = log_kDist[i] = FastMath.log(iter.doubleValue());
sum_log_kDist += logd;
sum_log_k_kDist += logd * log_k[i];
}
double sum_log_k = 0, sum_log_k2 = 0;
for(int i = 0; i < log_k.length; i++) {
final double logki = log_k[i];
sum_log_k += logki;
sum_log_k2 += logki * logki;
}
if(msg != null) {
msg.append("\nk_0 ").append(k_0) //
.append("\nk_max ").append(settings.kmax) //
.append("\nlog_k(").append(log_k.length).append(") ").append(FormatUtil.format(log_k)) //
.append("\nsum_log_k ").append(sum_log_k) //
.append("\nsum_log_k^2 ").append(sum_log_k2) //
.append("\nkDists ").append(knnDistances) //
.append("\nlog_kDist(").append(log_kDist.length).append(") ").append(FormatUtil.format(log_kDist)) //
.append("\nsum_log_kDist ").append(sum_log_kDist) //
.append("\nsum_log_k_kDist ").append(sum_log_k_kDist);
}
// lower and upper hull
ConvexHull convexHull = new ConvexHull(log_k, log_kDist);
// approximate upper hull
ApproximationLine conservative = approximateUpperHull(convexHull, log_k, log_kDist);
ApproximationLine c2 = approximateUpperHullPaper(convexHull, log_k, sum_log_k, sum_log_k2, log_kDist, sum_log_kDist, sum_log_k_kDist);
double err1 = ssqerr(k_0, settings.kmax, log_k, log_kDist, conservative.getM(), conservative.getT());
double err2 = ssqerr(k_0, settings.kmax, log_k, log_kDist, c2.getM(), c2.getT());
if(msg != null) {
msg.append("err1 ").append(err1).append("err2 ").append(err2);
}
if(err1 > err2 && err1 - err2 > 0.000000001) {
// if (err1 > err2) {
StringBuilder warning = new StringBuilder(10000);
int u = convexHull.getNumberOfPointsInUpperHull();
int[] upperHull = convexHull.getUpperHull();
warning.append("\nentry ").append(entry.getRoutingObjectID()) //
.append("\nlower Hull ").append(convexHull.getNumberOfPointsInLowerHull()).append(' ').append(FormatUtil.format(convexHull.getLowerHull())) //
.append("\nupper Hull ").append(convexHull.getNumberOfPointsInUpperHull()).append(' ').append(FormatUtil.format(convexHull.getUpperHull())) //
.append("\nerr1 ").append(err1) //
.append("\nerr2 ").append(err2) //
.append("\nconservative1 ").append(conservative) //
.append("\nconservative2 ").append(c2);
for(int i = 0; i < u; i++) {
warning.append("\nlog_k[").append(upperHull[i]).append("] = ").append(log_k[upperHull[i]]) //
.append("\nlog_kDist[").append(upperHull[i]).append("] = ").append(log_kDist[upperHull[i]]);
}
LOG.warning(warning.toString());
}
// approximate lower hull
ApproximationLine progressive = approximateLowerHull(convexHull, log_k, sum_log_k, sum_log_k2, log_kDist, sum_log_kDist, sum_log_k_kDist);
entry.setConservativeKnnDistanceApproximation(conservative);
entry.setProgressiveKnnDistanceApproximation(progressive);
if(msg != null) {
LOG.debugFine(msg.toString());
}
}
|
python
|
def move(self, from_path, to_path, **kwargs):
"""移动单个文件或目录.
:param from_path: 源文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.``
或空白字符,空白字符包括:
``\\r, \\n, \\t, 空格, \\0, \\x0B`` 。
:param to_path: 目标文件/目录在网盘中的路径(包括文件名)。
.. warning::
* 路径长度限制为1000;
* 径中不能包含以下字符:``\\\\ ? | " > < : *``;
* 文件名或路径名开头结尾不能是 ``.``
或空白字符,空白字符包括:
``\\r, \\n, \\t, 空格, \\0, \\x0B`` 。
:return: Response 对象
"""
data = {
'from': from_path,
'to': to_path,
}
return self._request('file', 'move', data=data, **kwargs)
|
java
|
public IntSet predecessors(int vertex) {
Set<T> in = inEdges(vertex);
IntSet preds = new TroveIntSet();
if (in.isEmpty())
return preds;
for (T e : in)
preds.add(e.from());
return preds;
}
/**
* {@inheritDoc}
*/
public IntSet successors(int vertex) {
Set<T> out = outEdges(vertex);
IntSet succs = new TroveIntSet();
if (out.isEmpty())
return succs;
for (T e : out)
succs.add(e.to());
return succs;
}
/**
* {@inheritDoc}
*/
public DirectedGraph<T> subgraph(Set<Integer> vertices) {
Graph<T> g = super.subgraph(vertices);
return new DirectedGraphAdaptor<T>(g);
}
}
|
java
|
@Override
public int predict(double[] x, double[] posteriori) {
Arrays.fill(posteriori, 0.0);
for (int i = 0; i < trees.length; i++) {
posteriori[trees[i].predict(x)] += alpha[i];
}
double sum = Math.sum(posteriori);
for (int i = 0; i < k; i++) {
posteriori[i] /= sum;
}
return Math.whichMax(posteriori);
}
|
java
|
@Override
public ListAuthorizersResult listAuthorizers(ListAuthorizersRequest request) {
request = beforeClientExecution(request);
return executeListAuthorizers(request);
}
|
java
|
public Binding createBoundList(String selectionFormProperty, Object selectableItems,
String renderedProperty, Integer forceSelectMode) {
final Map context = new HashMap();
if (forceSelectMode != null) {
context.put(ListBinder.SELECTION_MODE_KEY, forceSelectMode);
}
context.put(ListBinder.SELECTABLE_ITEMS_KEY, selectableItems);
if (renderedProperty != null) {
context.put(ListBinder.RENDERER_KEY, new BeanPropertyValueListRenderer(renderedProperty));
context.put(ListBinder.COMPARATOR_KEY, new PropertyComparator(renderedProperty, true, true));
}
return createBinding(JList.class, selectionFormProperty, context);
}
|
java
|
@Override
public UnsubscribeFromEventResult unsubscribeFromEvent(UnsubscribeFromEventRequest request) {
request = beforeClientExecution(request);
return executeUnsubscribeFromEvent(request);
}
|
java
|
public final void setEntryDetailsPopOverContentCallback(Callback<EntryDetailsPopOverContentParameter, Node> callback) {
requireNonNull(callback);
entryDetailsPopOverContentCallbackProperty().set(callback);
}
|
java
|
public static <T> Level0ArrayOperator<Float[],Float> onArray(final Float[] target) {
return onArrayOf(Types.FLOAT, target);
}
|
java
|
@Override
public int getMaxInactiveInterval() {
HttpSession session = backing.getSession(false);
if (session == null) {
return -1;
}
return session.getMaxInactiveInterval();
}
|
java
|
public void marshall(MatchedPlayerSession matchedPlayerSession, ProtocolMarshaller protocolMarshaller) {
if (matchedPlayerSession == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(matchedPlayerSession.getPlayerId(), PLAYERID_BINDING);
protocolMarshaller.marshall(matchedPlayerSession.getPlayerSessionId(), PLAYERSESSIONID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
|
java
|
public void addStyleSheetProperties(Content head) {
String stylesheetfile = configuration.stylesheetfile;
DocPath stylesheet;
if (stylesheetfile.isEmpty()) {
stylesheet = DocPaths.STYLESHEET;
} else {
DocFile file = DocFile.createFileForInput(configuration, stylesheetfile);
stylesheet = DocPath.create(file.getName());
}
HtmlTree link = HtmlTree.LINK("stylesheet", "text/css",
pathToRoot.resolve(stylesheet).getPath(),
"Style");
head.addContent(link);
if (configuration.createindex) {
HtmlTree jq_link = HtmlTree.LINK("stylesheet", "text/css",
pathToRoot.resolve(DocPaths.JQUERY_FILES.resolve(DocPaths.JQUERY_STYLESHEET_FILE)).getPath(),
"Style");
head.addContent(jq_link);
}
}
|
java
|
public OperationFuture<List<Server>> createSnapshot(Integer expirationDays, Server... serverRefs) {
return powerOperationResponse(
Arrays.asList(serverRefs),
"Create Snapshot",
client.createSnapshot(
new CreateSnapshotRequest()
.snapshotExpirationDays(expirationDays)
.serverIds(ids(serverRefs))
)
);
}
|
python
|
def main(_):
"""Run the sample attack"""
batch_shape = [FLAGS.batch_size, FLAGS.image_height, FLAGS.image_width, 3]
for filenames, images in load_images(FLAGS.input_dir, batch_shape):
save_images(images, filenames, FLAGS.output_dir)
|
java
|
public void checkFunctionOrMethodDeclaration(Decl.FunctionOrMethod d) {
// Construct initial environment
Environment environment = new Environment();
// Update environment so this within declared lifetimes
environment = FlowTypeUtils.declareThisWithin(d, environment);
// Check parameters and returns are not empty (i.e. are not equivalent
// to void, as this is non-sensical).
checkVariableDeclarations(d.getParameters(), environment);
checkVariableDeclarations(d.getReturns(), environment);
// Check any preconditions (i.e. requires clauses) provided.
checkConditions(d.getRequires(), true, environment);
// Check any postconditions (i.e. ensures clauses) provided.
checkConditions(d.getEnsures(), true, environment);
// FIXME: Add the "this" lifetime
if (d.getModifiers().match(Modifier.Native.class) == null) {
// Create scope representing this declaration
EnclosingScope scope = new FunctionOrMethodScope(d);
// Check type information throughout all statements in body.
Environment last = checkBlock(d.getBody(), environment, scope);
// Check return value
checkReturnValue(d, last);
} else {
// NOTE: we obviously don't need to check the body of a native function or
// method. Attempting to do so causes problems because checkReturnValue will
// fail.
}
}
|
java
|
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public MessageEvent createMessageEvent(Data data) {
return MessageEvent.builder(MessageEvent.Type.SENT, MESSAGE_ID).build();
}
|
java
|
public static boolean isLong(String number) {
boolean result = false;
try {
Long.parseLong(number);
result = true;
} catch (NumberFormatException e) {
}
return result;
}
|
python
|
def _from_binary_ea(cls, binary_stream):
"""See base class."""
_ea_list = []
offset = 0
#_MOD_LOGGER.debug(f"Creating Ea object from binary stream {binary_stream.tobytes()}...")
_MOD_LOGGER.debug("Creating Ea object from binary '%s'...", binary_stream.tobytes())
while True:
entry = EaEntry.create_from_binary(binary_stream[offset:])
offset += entry.offset_next_ea
_ea_list.append(entry)
if offset >= len(binary_stream):
break
nw_obj = cls(_ea_list)
_MOD_LOGGER.debug("Attempted to unpack EA from \"%s\"\nResult: %s", binary_stream.tobytes(), nw_obj)
return nw_obj
|
java
|
public static void discardStateFuture(RunnableFuture<? extends StateObject> stateFuture) throws Exception {
if (null != stateFuture) {
if (!stateFuture.cancel(true)) {
try {
// We attempt to get a result, in case the future completed before cancellation.
StateObject stateObject = FutureUtils.runIfNotDoneAndGet(stateFuture);
if (null != stateObject) {
stateObject.discardState();
}
} catch (CancellationException | ExecutionException ex) {
LOG.debug("Cancelled execution of snapshot future runnable. Cancellation produced the following " +
"exception, which is expected an can be ignored.", ex);
}
}
}
}
|
java
|
protected String urlEncodedValueForParameterName(String name, String value) {
// Special handling for access_token -
// '%7C' is the pipe character and will be present in any access_token
// parameter that's already URL-encoded. If we see this combination, don't
// URL-encode. Otherwise, URL-encode as normal.
return ACCESS_TOKEN_PARAM_NAME.equals(name) && value.contains("%7C") ? value : urlEncode(value);
}
|
python
|
def is_package_installed(distribution, pkg):
""" checks if a particular package is installed """
if ('centos' in distribution or
'el' in distribution or
'redhat' in distribution):
return(is_rpm_package_installed(pkg))
if ('ubuntu' in distribution or
'debian' in distribution):
return(is_deb_package_installed(pkg))
|
python
|
def get_index_declaration_sql(self, name, index):
"""
Obtains DBMS specific SQL code portion needed to set an index
declaration to be used in statements like CREATE TABLE.
:param name: The name of the index.
:type name: str
:param index: The index definition
:type index: Index
:return: DBMS specific SQL code portion needed to set an index.
:rtype: str
"""
columns = index.get_quoted_columns(self)
name = Identifier(name)
if not columns:
raise DBALException('Incomplete definition. "columns" required.')
return "%sINDEX %s (%s)%s" % (
self.get_create_index_sql_flags(index),
name.get_quoted_name(self),
self.get_index_field_declaration_list_sql(columns),
self.get_partial_index_sql(index),
)
|
python
|
def qual(args):
"""
%prog qual fastafile
Generate dummy .qual file based on FASTA file.
"""
from jcvi.formats.sizes import Sizes
p = OptionParser(qual.__doc__)
p.add_option("--qv", default=31, type="int",
help="Dummy qv score for extended bases")
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
fastafile, = args
sizes = Sizes(fastafile)
qvchar = str(opts.qv)
fw = must_open(opts.outfile, "w")
total = 0
for s, slen in sizes.iter_sizes():
print(">" + s, file=fw)
print(" ".join([qvchar] * slen), file=fw)
total += 1
fw.close()
logging.debug("Written {0} records in `{1}`.".format(total, opts.outfile))
|
python
|
def _process_cache(self, d, path=()):
"""Recusively walk a nested recon cache dict to obtain path/values"""
for k, v in d.iteritems():
if not isinstance(v, dict):
self.metrics.append((path + (k,), v))
else:
self._process_cache(v, path + (k,))
|
python
|
def rebin_coord_transform(factor, x_at_radec_0, y_at_radec_0, Mpix2coord, Mcoord2pix):
"""
adopt coordinate system and transformation between angular and pixel coordinates of a re-binned image
:param bin_size:
:param ra_0:
:param dec_0:
:param x_0:
:param y_0:
:param Matrix:
:param Matrix_inv:
:return:
"""
factor = int(factor)
Mcoord2pix_resized = Mcoord2pix / factor
Mpix2coord_resized = Mpix2coord * factor
x_at_radec_0_resized = (x_at_radec_0 + 0.5) / factor - 0.5
y_at_radec_0_resized = (y_at_radec_0 + 0.5) / factor - 0.5
ra_at_xy_0_resized, dec_at_xy_0_resized = util.map_coord2pix(-x_at_radec_0_resized, -y_at_radec_0_resized, 0, 0, Mpix2coord_resized)
return ra_at_xy_0_resized, dec_at_xy_0_resized, x_at_radec_0_resized, y_at_radec_0_resized, Mpix2coord_resized, Mcoord2pix_resized
|
python
|
def use_theme(theme, directory=None):
"""Switches to the specified theme. This returns False if switching to the already active theme."""
repo = require_repo(directory)
if theme not in list_themes(directory):
raise ThemeNotFoundError(theme)
old_theme = set_value(repo, 'theme', theme)
return old_theme != theme
|
java
|
@Override
public Object valAt(Object o) {
try {
if (o instanceof Keyword) {
return getValueByField(((Keyword) o).getName());
} else if (o instanceof String) {
return getValueByField((String) o);
}
} catch (IllegalArgumentException ignored) {
}
return null;
}
|
python
|
def weather_cells(self):
"""
Weather cells contained in grid
Returns
-------
list
list of weather cell ids contained in grid
"""
if not self._weather_cells:
# get all the weather cell ids
self._weather_cells = []
for gen in self.generators:
if hasattr(gen, 'weather_cell_id'):
self._weather_cells.append(gen.weather_cell_id)
# drop duplicates
self._weather_cells = list(set(self._weather_cells))
# no need to check for Nones in the list because None in
# gen.weather_cell_id is kicked out by the if hasattr() before
return self._weather_cells
|
java
|
public static void isInstanceOf(Class<?> type, Object obj, String message) {
notNull(type, "Type to check against must not be null");
if (!type.isInstance(obj)) {
instanceCheckFailed(type, obj, message);
}
}
|
python
|
def simple_response(self, status, msg=""):
"""Return a operation for writing simple response back to the client."""
status = str(status)
buf = ["%s %s\r\n" % (self.environ['ACTUAL_SERVER_PROTOCOL'], status),
"Content-Length: %s\r\n" % len(msg),
"Content-Type: text/plain\r\n"]
if status[:3] == "413" and self.response_protocol == 'HTTP/1.1':
# Request Entity Too Large
self.close_connection = True
buf.append("Connection: close\r\n")
buf.append("\r\n")
if msg:
buf.append(msg)
return sockets.SendAll(self.conn, "".join(buf))
|
java
|
protected <T> String getGroupType(T obj, String type, String name, Session session) throws CpoException {
String retType = type;
long objCount;
if (CpoAdapter.PERSIST_GROUP.equals(retType)) {
objCount = existsObject(name, obj, session, null);
if (objCount == 0) {
retType = CpoAdapter.CREATE_GROUP;
} else if (objCount == 1) {
retType = CpoAdapter.UPDATE_GROUP;
} else {
throw new CpoException("Persist can only UPDATE one record. Your EXISTS function returned 2 or more.");
}
}
return retType;
}
|
python
|
def DbDeleteAllDeviceAttributeProperty(self, argin):
""" Delete all attribute properties for the specified device attribute(s)
:param argin: str[0] = device name
Str[1]...str[n] = attribute name(s)
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
self._log.debug("In DbDeleteAllDeviceAttributeProperty()")
if len(argin) < 2:
self.warn_stream("DataBase::DbDeleteAllDeviceAttributeProperty(): insufficient number of arguments ")
th_exc(DB_IncorrectArguments,
"insufficient number of arguments to delete all device attribute(s) property",
"DataBase::DbDeleteAllDeviceAttributeProperty()")
dev_name = argin[0]
ret, d_name, dfm = check_device_name(dev_name)
if not ret:
th_exc(DB_IncorrectDeviceName,
"device name (" + argin + ") syntax error (should be [tango:][//instance/]domain/family/member)",
"DataBase::DbDeleteAllDeviceAttributeProperty()")
self.db.delete_all_device_attribute_property(dev_name, argin[1:])
|
java
|
@Override
public boolean configure(FeatureContext context) {
context.register(DefaultExceptionMapper.class)
.register(StatusMapper.class);
return true;
}
|
python
|
def get_image(roi_rec, short, max_size, mean, std):
"""
read, resize, transform image, return im_tensor, im_info, gt_boxes
roi_rec should have keys: ["image", "boxes", "gt_classes", "flipped"]
0 --- x (width, second dim of im)
|
y (height, first dim of im)
"""
im = imdecode(roi_rec['image'])
if roi_rec["flipped"]:
im = im[:, ::-1, :]
im, im_scale = resize(im, short, max_size)
height, width = im.shape[:2]
im_info = np.array([height, width, im_scale], dtype=np.float32)
im_tensor = transform(im, mean, std)
# gt boxes: (x1, y1, x2, y2, cls)
if roi_rec['gt_classes'].size > 0:
gt_inds = np.where(roi_rec['gt_classes'] != 0)[0]
gt_boxes = np.empty((len(gt_inds), 5), dtype=np.float32)
gt_boxes[:, 0:4] = roi_rec['boxes'][gt_inds, :]
gt_boxes[:, 4] = roi_rec['gt_classes'][gt_inds]
# scale gt_boxes
gt_boxes[:, 0:4] *= im_scale
else:
gt_boxes = np.empty((0, 5), dtype=np.float32)
return im_tensor, im_info, gt_boxes
|
java
|
private static FactorComparator<Executor> getCpuUsageComparator(final int weight) {
return FactorComparator.create(CPUUSAGE_COMPARATOR_NAME, weight, new Comparator<Executor>() {
@Override
public int compare(final Executor o1, final Executor o2) {
final ExecutorInfo stat1 = o1.getExecutorInfo();
final ExecutorInfo stat2 = o2.getExecutorInfo();
final int result = 0;
if (statisticsObjectCheck(stat1, stat2, CPUUSAGE_COMPARATOR_NAME)) {
return result;
}
// CPU usage , the lesser the value is, the better.
return ((Double) stat2.getCpuUsage()).compareTo(stat1.getCpuUsage());
}
});
}
|
java
|
public static HttpStatus grpcCodeToHttpStatus(Status.Code grpcStatusCode) {
switch (grpcStatusCode) {
case OK:
return HttpStatus.OK;
case CANCELLED:
return HttpStatus.CLIENT_CLOSED_REQUEST;
case UNKNOWN:
case INTERNAL:
case DATA_LOSS:
return HttpStatus.INTERNAL_SERVER_ERROR;
case INVALID_ARGUMENT:
case FAILED_PRECONDITION:
case OUT_OF_RANGE:
return HttpStatus.BAD_REQUEST;
case DEADLINE_EXCEEDED:
return HttpStatus.GATEWAY_TIMEOUT;
case NOT_FOUND:
return HttpStatus.NOT_FOUND;
case ALREADY_EXISTS:
case ABORTED:
return HttpStatus.CONFLICT;
case PERMISSION_DENIED:
return HttpStatus.FORBIDDEN;
case UNAUTHENTICATED:
return HttpStatus.UNAUTHORIZED;
case RESOURCE_EXHAUSTED:
return HttpStatus.TOO_MANY_REQUESTS;
case UNIMPLEMENTED:
return HttpStatus.NOT_IMPLEMENTED;
case UNAVAILABLE:
return HttpStatus.SERVICE_UNAVAILABLE;
default:
return HttpStatus.UNKNOWN;
}
}
|
python
|
def add_relationship_methods(self):
"""
Adds relationship methods to applicable model classes.
"""
Entry = apps.get_model('wagtailrelations', 'Entry')
@cached_property
def related(instance):
return instance.get_related()
@cached_property
def related_live(instance):
return instance.get_related_live()
@cached_property
def related_with_scores(instance):
return instance.get_related_with_scores()
def get_related(instance):
entry = Entry.objects.get_for_model(instance)[0]
return entry.get_related()
def get_related_live(instance):
entry = Entry.objects.get_for_model(instance)[0]
return entry.get_related_live()
def get_related_with_scores(instance):
try:
entry = Entry.objects.get_for_model(instance)[0]
return entry.get_related_with_scores()
except IntegrityError:
return []
for model in self.applicable_models:
model.add_to_class(
'get_related',
get_related
)
model.add_to_class(
'get_related_live',
get_related_live
)
model.add_to_class(
'get_related_with_scores',
get_related_with_scores
)
model.add_to_class(
'related',
related
)
model.add_to_class(
'related_live',
related_live
)
model.add_to_class(
'related_with_scores',
related_with_scores
)
|
java
|
public static void assertOneParameter(final Method method, Class<? extends Annotation> annotation)
{
if (method.getParameterTypes().length != 1)
{
throw annotation == null ? MESSAGES.methodHasToDeclareExactlyOneParameter(method) : MESSAGES.methodHasToDeclareExactlyOneParameter2(method, annotation);
}
}
|
java
|
@Override
public EClass getIfcRelConnectsWithEccentricity() {
if (ifcRelConnectsWithEccentricityEClass == null) {
ifcRelConnectsWithEccentricityEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(540);
}
return ifcRelConnectsWithEccentricityEClass;
}
|
python
|
def __show_categories_tree(self):
""" Show the category tree: list of categories and its subcategories """
for cat in self.categories_tree:
print("%s (%i)" % (self.categories[cat], cat))
for subcat in self.categories_tree[cat]:
print("-> %s (%i)" % (self.categories[subcat], subcat))
|
java
|
public int indexOf(CharSequence target, int fromIndex, int endIndex)
{
if (fromIndex < 0)
throw new IndexOutOfBoundsException("index out of range: " + fromIndex);
if (endIndex < 0)
throw new IndexOutOfBoundsException("index out of range: " + endIndex);
if (fromIndex > length())
throw new IndexOutOfBoundsException("fromIndex > length()");
if (fromIndex > endIndex)
throw new IndexOutOfBoundsException("fromIndex > endIndex");
if (endIndex >= builder.length())
{
endIndex = builder.length() - 1;
}
int targetCount = target.length();
if (targetCount == 0)
{
return fromIndex;
}
char strFirstChar = target.charAt(0);
int max = endIndex + targetCount - 1;
lastCharSearch:
for (int i = fromIndex; i <= max; i++)
{
if (builder.charAt(i) == strFirstChar)
{
for (int j = 1; j < targetCount; j++)
{
if (builder.charAt(i + j) != target.charAt(j))
{
continue lastCharSearch;
}
}
return i;
}
}
return -1;
}
|
python
|
def post_message(consumers, lti_key, url, body):
"""
Posts a signed message to LTI consumer
:param consumers: consumers from config
:param lti_key: key to find appropriate consumer
:param url: post url
:param body: xml body
:return: success
"""
content_type = 'application/xml'
method = 'POST'
(_, content) = _post_patched_request(
consumers,
lti_key,
body,
url,
method,
content_type,
)
is_success = b"<imsx_codeMajor>success</imsx_codeMajor>" in content
log.debug("is success %s", is_success)
return is_success
|
java
|
public int middleIndex()
{
int x = midPoint();
int r = rightMostIndex();
if (r < midPoint())
x = r;
return x;
}
|
java
|
private void updateTintFilter() {
if (mTint == null) {
mTintFilter = null;
return;
}
// setMode, setColor of PorterDuffColorFilter are not public method in SDK v7. (Thanks @Google still not accessible in API v24)
// Therefore we create a new one all the time here. Don't expect this is called often.
int color = mTint.getColorForState(getState(), Color.TRANSPARENT);
mTintFilter = new PorterDuffColorFilter(color, mTintMode);
}
|
java
|
public int indexOf(int ch, int fromIndex)
{
int max = m_start + m_length;
FastStringBuffer fsb = fsb();
if (fromIndex < 0)
{
fromIndex = 0;
}
else if (fromIndex >= m_length)
{
// Note: fromIndex might be near -1>>>1.
return -1;
}
for (int i = m_start + fromIndex; i < max; i++)
{
if (fsb.charAt(i) == ch)
{
return i - m_start;
}
}
return -1;
}
|
java
|
public static base_responses delete(nitro_service client, String trapclass[]) throws Exception {
base_responses result = null;
if (trapclass != null && trapclass.length > 0) {
snmptrap deleteresources[] = new snmptrap[trapclass.length];
for (int i=0;i<trapclass.length;i++){
deleteresources[i] = new snmptrap();
deleteresources[i].trapclass = trapclass[i];
}
result = delete_bulk_request(client, deleteresources);
}
return result;
}
|
python
|
def get_value(haystack, needle, key_attribute="n",
content_attribute="_content"):
""" Fetch a value from a zimbra-like json dict (keys are "n", values are
"_content"
This function may be slightly faster than zimbra_to_python(haystack)[
needle], because it doesn't necessarily iterate over the complete list.
:param haystack: The list in zimbra-dict format
:param needle: the key to search for
:return: the value or None, if the key is not found
"""
for value in haystack:
if value[key_attribute] == needle:
return value[content_attribute]
return None
|
java
|
public void serialize(DigitalObject in,
OutputStream out,
String format,
String encoding,
int transContext) throws ObjectIntegrityException,
StreamIOException, UnsupportedTranslationException, ServerException {
m_wrappedTranslator.serialize(in, out, format, encoding, transContext);
}
|
java
|
private boolean casTail(Node cmp, Node val) {
return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
}
|
java
|
public final void mGT() throws RecognitionException {
try {
int _type = GT;
int _channel = DEFAULT_TOKEN_CHANNEL;
// EventFilter.g:39:4: ( '>' )
// EventFilter.g:39:6: '>'
{
match('>');
}
state.type = _type;
state.channel = _channel;
}
finally {
// do for sure before leaving
}
}
|
java
|
private void handleJSIncludeNode(ReplayParseContext context, TagNode tagNode) {
String file = tagNode.getAttribute("SRC");
if (file != null) {
String result = jsBlockTrans.transform(context, file);
// URL rewrite is done by AttributeRewriter, which should ignore
// empty value.
if (result == null || result.isEmpty()) {
tagNode.setAttribute("SRC", "");
}
}
}
|
python
|
def _notify_change(self, model, attr, old, new, hint=None, setter=None, callback_invoker=None):
''' Called by Model when it changes
'''
# if name changes, update by-name index
if attr == 'name':
if old is not None:
self._all_models_by_name.remove_value(old, model)
if new is not None:
self._all_models_by_name.add_value(new, model)
if hint is None:
serializable_new = model.lookup(attr).serializable_value(model)
else:
serializable_new = None
event = ModelChangedEvent(self, model, attr, old, new, serializable_new, hint, setter, callback_invoker)
self._trigger_on_change(event)
|
java
|
public static void premain(String args, Instrumentation instrumentation) {
if (!PreMainUtil.isBeta() && !PreMainUtil.isEnableAgentPropertySet()) {
// if it's not beta, do nothing.
// this implementation should be changed when this will be in the production code.
return;
}
ObjectInputStreamTransformer transform = null;
if (ObjectInputStreamClassInjector.injectionNeeded()) {
// Install the transformer to modify ObjectInputStream.
if (PreMainUtil.isDebugEnabled()) {
System.out.println("Using class file transformer to modify ObjectInputStream.");
}
transform = new ObjectInputStreamTransformer();
instrumentation.addTransformer(transform);
}
try {
initialiseObjectInputStream();
} finally {
// Uninstall the class transformer.
if (transform != null) {
if (PreMainUtil.isDebugEnabled()) {
System.out.println("Removing class file transformer.");
}
instrumentation.removeTransformer(transform);
}
}
AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return System.setProperty(PreMainUtil.KEY_SERIALFILTER_AGENT_ACTIVE, "true");
}
});
}
|
python
|
def record_file_factory(pid, record, filename):
"""Get file from a record.
:param pid: Not used. It keeps the function signature.
:param record: Record which contains the files.
:param filename: Name of the file to be returned.
:returns: File object or ``None`` if not found.
"""
try:
if not (hasattr(record, 'files') and record.files):
return None
except MissingModelError:
return None
try:
return record.files[filename]
except KeyError:
return None
|
python
|
def sort_values(self, return_indexer=False, ascending=True):
"""
Return sorted copy of Index.
"""
if return_indexer:
_as = self.argsort()
if not ascending:
_as = _as[::-1]
sorted_index = self.take(_as)
return sorted_index, _as
else:
sorted_values = np.sort(self._ndarray_values)
attribs = self._get_attributes_dict()
freq = attribs['freq']
if freq is not None and not is_period_dtype(self):
if freq.n > 0 and not ascending:
freq = freq * -1
elif freq.n < 0 and ascending:
freq = freq * -1
attribs['freq'] = freq
if not ascending:
sorted_values = sorted_values[::-1]
return self._simple_new(sorted_values, **attribs)
|
python
|
def get_portal_type(brain_or_object):
"""Get the portal type for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Portal type
:rtype: string
"""
if not is_object(brain_or_object):
fail("{} is not supported.".format(repr(brain_or_object)))
return brain_or_object.portal_type
|
java
|
static public <C, T extends C> Value<C, T> percentHeight (Toolkit<C, T> toolkit, final float percent) {
return new TableValue<C, T>(toolkit) {
@Override
public float get (T table) {
return toolkit.getHeight(table) * percent;
}
};
}
|
java
|
public static CommerceOrder[] findByU_LtC_O_PrevAndNext(
long commerceOrderId, long userId, Date createDate, int orderStatus,
OrderByComparator<CommerceOrder> orderByComparator)
throws com.liferay.commerce.exception.NoSuchOrderException {
return getPersistence()
.findByU_LtC_O_PrevAndNext(commerceOrderId, userId,
createDate, orderStatus, orderByComparator);
}
|
java
|
public String getGeneName() {
if (uniprotDoc == null) {
return "";
}
try {
Element uniprotElement = uniprotDoc.getDocumentElement();
Element entryElement = XMLHelper.selectSingleElement(uniprotElement, "entry");
Element geneElement = XMLHelper.selectSingleElement(entryElement, "gene");
if (geneElement == null) {
return "";
}
Element nameElement = XMLHelper.selectSingleElement(geneElement, "name");
if (nameElement == null) {
return "";
}
return nameElement.getTextContent();
} catch (XPathExpressionException e) {
logger.error("Problems while parsing gene name in UniProt XML: {}. Gene name will be blank.",e.getMessage());
return "";
}
}
|
java
|
public static AsyncWork<Properties, Exception> loadPropertiesFile(
IO.Readable input, Charset charset, byte priority, IO.OperationType closeInputAtEnd, Listener<Properties> onDone
) {
if (!(input instanceof IO.Readable.Buffered))
input = new PreBufferedReadable(input, 512, priority, 1024, priority, 16);
return loadPropertiesFile((IO.Readable.Buffered)input, charset, priority, closeInputAtEnd, onDone);
}
|
java
|
protected void calibrate ()
{
long currentTimer = current();
long currentMillis = System.currentTimeMillis();
long elapsedTimer = currentTimer - _driftTimerStamp;
float elapsedMillis = currentMillis - _driftMilliStamp;
float drift = elapsedMillis / (elapsedTimer / _milliDivider);
if (_debugCalibrate.getValue()) {
log.warning("Calibrating", "timer", elapsedTimer, "millis", elapsedMillis,
"drift", drift, "timerstamp", _driftTimerStamp,
"millistamp", _driftMilliStamp, "current", currentTimer);
}
if (elapsedTimer < 0) {
log.warning("The timer has decided to live in the past, resetting drift" ,
"previousTimer", _driftTimerStamp, "currentTimer", currentTimer,
"previousMillis", _driftMilliStamp, "currentMillis", currentMillis);
_driftRatio = 1.0F;
} else if (drift > MAX_ALLOWED_DRIFT_RATIO || drift < MIN_ALLOWED_DRIFT_RATIO) {
log.warning("Calibrating", "drift", drift);
// Ignore the drift if it's hugely out of range. That indicates general clock insanity,
// and we just want to stay out of the way.
if (drift < 100 * MAX_ALLOWED_DRIFT_RATIO && drift > MIN_ALLOWED_DRIFT_RATIO / 100) {
_driftRatio = drift;
} else {
_driftRatio = 1.0F;
}
if (Math.abs(drift - 1.0) > Math.abs(_maxDriftRatio - 1.0)) {
_maxDriftRatio = drift;
}
} else if (_driftRatio != 1.0) {
log.warning("Calibrating", "drift", drift);
// If we're within bounds now but we weren't before, reset _driftFactor and log it
_driftRatio = 1.0F;
}
_driftMilliStamp = currentMillis;
_driftTimerStamp = currentTimer;
}
|
java
|
private void handleGetAllMMetricsName(final HttpServletRequest req,
final Map<String, Object> ret) {
if (MetricReportManager.isAvailable()) {
final MetricReportManager metricManager = MetricReportManager.getInstance();
final List<IMetric<?>> result = metricManager.getAllMetrics();
if (result.size() == 0) {
ret.put(RESPONSE_ERROR, "No Metric being tracked");
} else {
final List<String> metricNames = new LinkedList<>();
for (final IMetric<?> metric : result) {
metricNames.add(metric.getName());
}
ret.put("data", metricNames);
}
} else {
ret.put(RESPONSE_ERROR, "MetricReportManager is not available");
}
}
|
java
|
public BeanO preInvokeActivateBean(EJBThreadData threadData, ContainerTx tx, BeanId beanId) // d641259
throws RemoteException
{
return beanId.getActivationStrategy().atActivate(threadData, tx, beanId);
}
|
java
|
public void writeMessage( Writer writer, String targetOrigin ) throws IOException
{
writeMessage( writer, messageFormatter, targetOrigin );
}
|
java
|
@SuppressWarnings("unchecked")
@Override
public <T> T create(String aName, Object[] params)
{
if(aName == null || aName.length() == 0)
return null;
String factoryName = new StringBuilder(PROP_PREFIX).append(aName).toString();
Object serviceObj = null;
if(singletonCreation)
serviceObj = factoryMap.get(factoryName.toString());
if(serviceObj == null)
{
//create
String className = settings.getProperty(factoryName,aName);
serviceObj = ClassPath.newInstance(className,params);
if(setNestedProperties)
setProperties(factoryName, serviceObj);
if(singletonCreation)
factoryMap.put(factoryName, serviceObj);
}
return (T)serviceObj;
}
|
python
|
def data(self, index, role = QtCore.Qt.DisplayRole):
"""Reimplemented from QtCore.QAbstractItemModel
The value gets validated and is red if validation fails
and green if it passes.
"""
if not index.isValid():
return None
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
if index.column() == 0:
p = index.internalPointer()
k = self.get_key(p, index.row())
return k
if index.column() == 1:
v = self.get_value(index)
if not isinstance(v, Section):
return self._val_to_str(v)
if index.column() == 2:
return self.get_configspec_str(index)
if role == QtCore.Qt.ForegroundRole:
if index.column() == 1:
v = self.get_value(index)
if not isinstance(v, Section):
spec = self.get_configspec_str(index)
if spec is None or isinstance(spec, Section):
return
try:
self._vld.check(spec, v)
except ValidateError:
return QtGui.QBrush(self._invalid_col)
else:
return QtGui.QBrush(self._valid_col)
|
python
|
def ldGet(self, what, key):
"""List-aware get."""
if isListKey(key):
return what[listKeyIndex(key)]
else:
return what[key]
|
java
|
private static void doStormTranslation(Config heronConfig) {
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS)) {
heronConfig.put(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS,
heronConfig.get(org.apache.storm.Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS).toString());
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_WORKERS)) {
Integer nWorkers = Utils.getInt(heronConfig.get(org.apache.storm.Config.TOPOLOGY_WORKERS));
org.apache.heron.api.Config.setNumStmgrs(heronConfig, nWorkers);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS)) {
Integer nSecs =
Utils.getInt(heronConfig.get(org.apache.storm.Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS));
org.apache.heron.api.Config.setMessageTimeoutSecs(heronConfig, nSecs);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_MAX_SPOUT_PENDING)) {
Integer nPending =
Utils.getInt(
heronConfig.get(org.apache.storm.Config.TOPOLOGY_MAX_SPOUT_PENDING).toString());
org.apache.heron.api.Config.setMaxSpoutPending(heronConfig, nPending);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS)) {
Integer tSecs =
Utils.getInt(
heronConfig.get(org.apache.storm.Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS).toString());
org.apache.heron.api.Config.setTickTupleFrequency(heronConfig, tSecs);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_DEBUG)) {
Boolean dBg =
Boolean.parseBoolean(heronConfig.get(org.apache.storm.Config.TOPOLOGY_DEBUG).toString());
org.apache.heron.api.Config.setDebug(heronConfig, dBg);
}
if (heronConfig.containsKey(org.apache.storm.Config.TOPOLOGY_ENVIRONMENT)) {
org.apache.heron.api.Config.setEnvironment(heronConfig,
(Map) heronConfig.get(org.apache.storm.Config.TOPOLOGY_ENVIRONMENT));
}
}
|
java
|
public final void synpred43_DRL6Expressions_fragment() throws RecognitionException {
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:699:9: ( DOT ID )
// src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:699:10: DOT ID
{
match(input,DOT,FOLLOW_DOT_in_synpred43_DRL6Expressions4279); if (state.failed) return;
match(input,ID,FOLLOW_ID_in_synpred43_DRL6Expressions4281); if (state.failed) return;
}
}
|
java
|
public synchronized void cleanWaitTaskQueue() {
for (ParallelTask task : waitQ) {
task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);
task.getTaskErrorMetas().add(
new TaskErrorMeta(TaskErrorType.USER_CANCELED, "NA"));
logger.info(
"task {} removed from wait q. This task has been marked as USER CANCELED.",
task.getTaskId());
}
waitQ.clear();
}
|
python
|
def remove_ip(self, ip_id):
"""
Delete an Ip from the boughs ip list
@param (str) ip_id: a string representing the resource id of the IP
@return: True if json method had success else False
"""
ip_id = ' "IpAddressResourceId": %s' % ip_id
json_scheme = self.gen_def_json_scheme('SetRemoveIpAddress', ip_id)
json_obj = self.call_method_post(method='SetRemoveIpAddress', json_scheme=json_scheme)
pprint(json_obj)
return True if json_obj['Success'] is True else False
|
java
|
public boolean isSameFile(JimfsPath path, FileSystemView view2, JimfsPath path2)
throws IOException {
if (!isSameFileSystem(view2)) {
return false;
}
store.readLock().lock();
try {
File file = lookUp(path, Options.FOLLOW_LINKS).fileOrNull();
File file2 = view2.lookUp(path2, Options.FOLLOW_LINKS).fileOrNull();
return file != null && Objects.equals(file, file2);
} finally {
store.readLock().unlock();
}
}
|
python
|
def reader(stream, fieldnames=None):
"""Read Items from a stream containing TSV."""
if not fieldnames:
fieldnames = load_line(stream.readline())
for line in stream:
values = load_line(line)
item = Item()
item.__dict__ = dict(zip(fieldnames, values))
yield item
|
java
|
public void createIndex(String indexDefinition) {
assertNotEmpty(indexDefinition, "indexDefinition");
InputStream putresp = null;
URI uri = new DatabaseURIHelper(db.getDBUri()).path("_index").build();
try {
putresp = client.couchDbClient.executeToInputStream(createPost(uri, indexDefinition,
"application/json"));
String result = getAsString(putresp, "result");
if (result.equalsIgnoreCase("created")) {
log.info(String.format("Created Index: '%s'", indexDefinition));
} else {
log.warning(String.format("Index already exists : '%s'", indexDefinition));
}
} finally {
close(putresp);
}
}
|
java
|
public void mutate(float amount) {
for (int i = 0; i < numKnots; i++) {
int rgb = yKnots[i];
int r = ((rgb >> 16) & 0xff);
int g = ((rgb >> 8) & 0xff);
int b = (rgb & 0xff);
r = PixelUtils.clamp( (int)(r + amount * 255 * (Math.random()-0.5)) );
g = PixelUtils.clamp( (int)(g + amount * 255 * (Math.random()-0.5)) );
b = PixelUtils.clamp( (int)(b + amount * 255 * (Math.random()-0.5)) );
yKnots[i] = 0xff000000 | (r << 16) | (g << 8) | b;
knotTypes[i] = RGB|SPLINE;
}
sortKnots();
rebuildGradient();
}
|
python
|
def fundfeepool(ctx, symbol, amount, account):
""" Fund the fee pool of an asset
"""
print_tx(ctx.bitshares.fund_fee_pool(symbol, amount, account=account))
|
java
|
public static CounterMap parseCounters(byte[] prefix,
Map<byte[], byte[]> keyValues) {
CounterMap counterValues = new CounterMap();
byte[] counterPrefix = Bytes.add(prefix, Constants.SEP_BYTES);
for (Map.Entry<byte[], byte[]> entry : keyValues.entrySet()) {
byte[] key = entry.getKey();
if (Bytes.startsWith(key, counterPrefix)
&& key.length > counterPrefix.length) {
// qualifier should be in the format: g!countergroup!counterkey
byte[][] qualifierFields =
ByteUtil.split(Bytes.tail(key, key.length - counterPrefix.length),
Constants.SEP_BYTES);
if (qualifierFields.length != 2) {
throw new IllegalArgumentException(
"Malformed column qualifier for counter value: "
+ Bytes.toStringBinary(key));
}
Counter c = new Counter(Bytes.toString(qualifierFields[0]),
Bytes.toString(qualifierFields[1]), Bytes.toLong(entry.getValue()));
counterValues.add(c);
}
}
return counterValues;
}
|
java
|
public static JSONObject loadJSONAsset(Context context, final String asset) {
if (asset == null) {
return new JSONObject();
}
return getJsonObject(org.gearvrf.widgetlib.main.Utility.readTextFile(context, asset));
}
|
java
|
public boolean remove(Object o) {
boolean removed = false;
for (Set<T> s : sets)
if (s.remove(o))
removed = true;
return removed;
}
|
java
|
protected void reportCachePerformance ()
{
if (/* Log.getLevel() != Log.log.DEBUG || */
_improv == null ||
_cacheStatThrottle.throttleOp()) {
return;
}
// compute our estimated memory usage
long amem = 0;
int asize = 0;
synchronized (_atiles) {
// first total up the active tiles
Iterator<SoftReference<Tile>> iter = _atiles.values().iterator();
while (iter.hasNext()) {
SoftReference<Tile> sref = iter.next();
Tile tile = sref.get();
if (tile != null) {
asize++;
amem += tile.getEstimatedMemoryUsage();
}
}
}
log.info("Tile caches", "amem", (amem / 1024) + "k",
"tmem", (Tile._totalTileMemory / 1024) + "k", "seen", _atiles.size(), "asize", + asize);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.