language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | static ProductPartitionTreeImpl createAdGroupTree(AdWordsServicesInterface services,
AdWordsSession session, Long adGroupId) throws ApiException, RemoteException {
// Get the AdGroupCriterionService.
AdGroupCriterionServiceInterface criterionService =
services.get(session, AdGroupCriterionServiceInterface.class);
SelectorBuilder selectorBuilder = new SelectorBuilder()
.fields(REQUIRED_SELECTOR_FIELD_ENUMS.toArray(
new AdGroupCriterionField[REQUIRED_SELECTOR_FIELD_ENUMS.size()]))
.equals(AdGroupCriterionField.AdGroupId, adGroupId.toString())
.equals(AdGroupCriterionField.CriteriaType, "PRODUCT_PARTITION")
.in(
AdGroupCriterionField.Status,
UserStatus.ENABLED.getValue(),
UserStatus.PAUSED.getValue())
.limit(PAGE_SIZE);
AdGroupCriterionPage adGroupCriterionPage;
// A multimap from each product partition ID to its direct children.
ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
int offset = 0;
do {
// Get the next page of results.
adGroupCriterionPage = criterionService.get(selectorBuilder.build());
if (adGroupCriterionPage != null && adGroupCriterionPage.getEntries() != null) {
for (AdGroupCriterion adGroupCriterion : adGroupCriterionPage.getEntries()) {
ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
}
offset += adGroupCriterionPage.getEntries().length;
selectorBuilder.increaseOffsetBy(PAGE_SIZE);
}
} while (offset < adGroupCriterionPage.getTotalNumEntries());
// Construct the ProductPartitionTree from the parentIdMap.
if (!parentIdMap.containsKey(null)) {
Preconditions.checkState(parentIdMap.isEmpty(),
"No root criterion found in the tree but the tree is not empty");
return createEmptyAdGroupTree(adGroupId,
getAdGroupBiddingStrategyConfiguration(services, session, adGroupId));
}
return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
} |
python | def checkIfRemoteIsNewer(self, localfile, remote_size, remote_modify):
"""
Overrides checkIfRemoteIsNewer in Source class
:param localfile: str file path
:param remote_size: str bytes
:param remote_modify: str last modify date in the form 20160705042714
:return: boolean True if remote file is newer else False
"""
is_remote_newer = False
status = os.stat(localfile)
LOG.info(
"\nLocal file size: %i"
"\nLocal Timestamp: %s",
status[ST_SIZE], datetime.fromtimestamp(status.st_mtime))
remote_dt = Bgee._convert_ftp_time_to_iso(remote_modify)
if remote_dt != datetime.fromtimestamp(status.st_mtime) or \
status[ST_SIZE] != int(remote_size):
is_remote_newer = True
LOG.info(
"Object on server is has different size %i and/or date %s",
remote_size, remote_dt)
return is_remote_newer |
java | public void execute() throws ActivityException {
EventWaitInstance received = registerWaitEvents(false, true);
if (received!=null) {
setReturnCodeAndExitStatus(received.getCompletionCode());
processMessage(getExternalEventInstanceDetails(received.getMessageDocumentId()));
boolean toFinish = handleCompletionCode();
if (toFinish && exitStatus==null)
exitStatus = WorkStatus.STATUS_COMPLETED;
} else {
exitStatus = WorkStatus.STATUS_COMPLETED;
setReturnCode(null);
}
} |
python | def update(self, key, value):
"""
:param key: a string
:value: a string
"""
if not is_string(key):
raise Exception("Key must be string")
# if len(key) > 32:
# raise Exception("Max key length is 32")
if not is_string(value):
raise Exception("Value must be string")
# if value == '':
# return self.delete(key)
self.root_node = self._update_and_delete_storage(
self.root_node,
bin_to_nibbles(to_string(key)),
to_string(value))
self._update_root_hash() |
java | public int call(String sql, Object[] params) throws Exception {
return call(sql, Arrays.asList(params));
} |
python | def sync_in_records(self, force=False):
"""Synchronize from files to records"""
self.log('---- Sync Files ----')
for f in self.build_source_files:
f.record_to_objects()
# Only the metadata needs to be driven to the objects, since the other files are used as code,
# directly from the file record.
self.build_source_files.file(File.BSFILE.META).record_to_objects()
self.commit() |
python | def IOWR(type, nr, size):
"""
An ioctl with both read an writes parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
"""
return IOC(IOC_READ | IOC_WRITE, type, nr, IOC_TYPECHECK(size)) |
python | def _loadf16(ins):
""" Load a 32 bit (16.16) fixed point value from a memory address
If 2nd arg. start with '*', it is always treated as
an indirect value.
"""
output = _f16_oper(ins.quad[2])
output.append('push de')
output.append('push hl')
return output |
java | protected ProgressUpdate newProgressUpdate(QueryBatch batch, long startTime, long totalForThisUpdate, double timeSoFar) {
return new SimpleProgressUpdate(batch, startTime, totalForThisUpdate, timeSoFar);
} |
java | @Override
public void execute(final ActionEvent event) {
ExampleData data = (ExampleData) event.getActionObject();
WComponent source = (WComponent) event.getSource();
TreePicker picker = WebUtilities.getAncestorOfClass(TreePicker.class, source);
picker.selectExample(data);
MenuPanel panel = WebUtilities.getAncestorOfClass(MenuPanel.class, source);
if (panel != null) {
WTree tree = panel.getTree();
if (tree != null) {
tree.setSelectedRows(new HashSet<String>()); // null);
}
}
} |
python | def get_normalized_definition(self):
"""Please refer to the specification for details about normalized definitions."""
cast_mode = 'saturated' if self.cast_mode == PrimitiveType.CAST_MODE_SATURATED else 'truncated'
primary_type = {
PrimitiveType.KIND_BOOLEAN: 'bool',
PrimitiveType.KIND_UNSIGNED_INT: 'uint' + str(self.bitlen),
PrimitiveType.KIND_SIGNED_INT: 'int' + str(self.bitlen),
PrimitiveType.KIND_FLOAT: 'float' + str(self.bitlen)
}[self.kind]
return cast_mode + ' ' + primary_type |
java | public static <T> Optional<T> of(T value) {
return value == null ? (Optional<T>) EMPTY : new Optional<>(value);
} |
python | def slice_for_qubits_equal_to(target_qubit_axes: Sequence[int],
little_endian_qureg_value: int,
*, # Forces keyword args.
num_qubits: int = None
) -> Tuple[Union[slice, int, 'ellipsis'], ...]:
"""Returns an index corresponding to a desired subset of an np.ndarray.
It is assumed that the np.ndarray's shape is of the form (2, 2, 2, ..., 2).
Example:
```python
# A '4 qubit' tensor with values from 0 to 15.
r = np.array(range(16)).reshape((2,) * 4)
# We want to index into the subset where qubit #1 and qubit #3 are ON.
s = cirq.slice_for_qubits_equal_to([1, 3], 0b11)
print(s)
# (slice(None, None, None), 1, slice(None, None, None), 1, Ellipsis)
# Get that subset. It corresponds to numbers of the form 0b*1*1.
# where here '*' indicates any possible value.
print(r[s])
# [[ 5 7]
# [13 15]]
```
Args:
target_qubit_axes: The qubits that are specified by the index bits. All
other axes of the slice are unconstrained.
little_endian_qureg_value: An integer whose bits specify what value is
desired for of the target qubits. The integer is little endian
w.r.t. the target quit axes, meaning the low bit of the integer
determines the desired value of the first targeted qubit, and so
forth with the k'th targeted qubit's value set to
bool(qureg_value & (1 << k)).
num_qubits: If specified the slices will extend all the way up to
this number of qubits, otherwise if it is None, the final element
return will be Ellipsis. Optional and defaults to using Ellipsis.
Returns:
An index object that will slice out a mutable view of the desired subset
of a tensor.
"""
n = num_qubits if num_qubits is not None else (
max(target_qubit_axes) if target_qubit_axes else -1)
result = [slice(None)] * (n + 2 * (
num_qubits is None)) # type: List[Union[slice, int, ellipsis]]
for k, axis in enumerate(target_qubit_axes):
result[axis] = (little_endian_qureg_value >> k) & 1
if num_qubits is None:
result[-1] = Ellipsis
return tuple(result) |
python | def fetch_samples(proj, selector_attribute=None, selector_include=None, selector_exclude=None):
"""
Collect samples of particular protocol(s).
Protocols can't be both positively selected for and negatively
selected against. That is, it makes no sense and is not allowed to
specify both selector_include and selector_exclude protocols. On the other hand, if
neither is provided, all of the Project's Samples are returned.
If selector_include is specified, Samples without a protocol will be excluded,
but if selector_exclude is specified, protocol-less Samples will be included.
:param Project proj: the Project with Samples to fetch
:param Project str: the sample selector_attribute to select for
:param Iterable[str] | str selector_include: protocol(s) of interest;
if specified, a Sample must
:param Iterable[str] | str selector_exclude: protocol(s) to include
:return list[Sample]: Collection of this Project's samples with
protocol that either matches one of those in selector_include, or either
lacks a protocol or does not match one of those in selector_exclude
:raise TypeError: if both selector_include and selector_exclude protocols are
specified; TypeError since it's basically providing two arguments
when only one is accepted, so remain consistent with vanilla Python2
"""
if selector_attribute is None or (not selector_include and not selector_exclude):
# Simple; keep all samples. In this case, this function simply
# offers a list rather than an iterator.
return list(proj.samples)
# At least one of the samples has to have the specified attribute
if proj.samples and not any([hasattr(i, selector_attribute) for i in proj.samples]):
raise AttributeError("The Project samples do not have the attribute '{attr}'"
.format(attr=selector_attribute))
# Intersection between selector_include and selector_exclude is nonsense user error.
if selector_include and selector_exclude:
raise TypeError("Specify only selector_include or selector_exclude parameter, "
"not both.")
# Ensure that we're working with sets.
def make_set(items):
if isinstance(items, str):
items = [items]
return items
# Use the attr check here rather than exception block in case the
# hypothetical AttributeError would occur; we want such
# an exception to arise, not to catch it as if the Sample lacks "protocol"
if not selector_include:
# Loose; keep all samples not in the selector_exclude.
def keep(s):
return not hasattr(s, selector_attribute) or \
getattr(s, selector_attribute) not in make_set(selector_exclude)
else:
# Strict; keep only samples in the selector_include.
def keep(s):
return hasattr(s, selector_attribute) and \
getattr(s, selector_attribute) in make_set(selector_include)
return list(filter(keep, proj.samples)) |
java | @Override
public ImageSource apply(ImageSource input) {
if (input.isGrayscale()) {
return input;
}
if (!isAlgorithm) {
double r, g, b, gray;
for (int i = 0; i < EffectHelper.getSize(input); i++) {
r = EffectHelper.getRed(i, input);
g = EffectHelper.getGreen(i, input);
b = EffectHelper.getBlue(i, input);
int a = EffectHelper.getAlpha(i, input);
gray = (r * redCoefficient + g * greenCoefficient + b * blueCoefficient);
EffectHelper.setRGB(i, (int) gray, (int) gray, (int) gray, a, input);
}
return input;
} else {
return apply(input, grayscaleMethod);
}
} |
python | def get_subclass(self):
"""
get_subclass
"""
strbldr = """
class IArguments(Arguments):
\"\"\"
IArguments
\"\"\"
def __init__(self, doc=None, validateschema=None, argvalue=None, yamlstr=None, yamlfile=None, parse_arguments=True, persistoption=False, alwaysfullhelp=False, version=None, parent=None):
\"\"\"
@type doc: str, None
@type validateschema: Schema, None
@type yamlfile: str, None
@type yamlstr: str, None
@type parse_arguments: bool
@type argvalue: str, None
@return: None
\"\"\"
"""
strbldr = remove_extra_indentation(strbldr)
strbldr += "\n"
self.set_reprdict_from_attributes()
strbldr += self.write_members()
strbldr += 8 * " " + "super().__init__(doc, validateschema, argvalue, yamlstr, yamlfile, parse_arguments, persistoption, alwaysfullhelp, version, parent)\n\n"
strbldr2 = """
class IArguments(Arguments):
\"\"\"
IArguments
\"\"\"
def __init__(self, doc):
\"\"\"
__init__
\"\"\"
"""
strbldr2 = remove_extra_indentation(strbldr2)
strbldr2 += "\n"
strbldr2 += self.write_members()
strbldr2 += 8 * " " + "super().__init__(doc)\n\n"
return strbldr2 |
python | def getOutputName(self,name):
""" Return the name of the file or PyFITS object associated with that
name, depending on the setting of self.inmemory.
"""
val = self.outputNames[name]
if self.inmemory: # if inmemory was turned on...
# return virtualOutput object saved with that name
val = self.virtualOutputs[val]
return val |
java | static void setCurrentScene(@NonNull View view, @Nullable Scene scene) {
view.setTag(R.id.current_scene, scene);
} |
java | @Broadcast(writeEntity = false)
@POST
@Produces("application/json")
public Response broadcast(Message message) {
return new Response(message.getAuthor(), message.getMessage());
} |
python | def parse_options(self, kwargs):
"""Validate the provided kwargs and return options as json string."""
kwargs = {camelize(key): value for key, value in kwargs.items()}
for key in kwargs.keys():
assert key in self.valid_options, (
'The option {} is not in the available options: {}.'
.format(key, ', '.join(self.valid_options))
)
assert isinstance(kwargs[key], self.valid_options[key]), (
'The option {} must be one of the following types: {}.'
.format(key, self.valid_options[key])
)
return kwargs |
java | public Token peek() {
if (!splitTokens.isEmpty()) {
return splitTokens.peek();
}
final var value = stringIterator.peek();
if (argumentEscapeEncountered) {
return new ArgumentToken(value);
}
if (Objects.equals(value, argumentTerminator)) {
return new ArgumentToken(value);
}
if (argumentTerminator != null) {
return new ArgumentToken(value);
}
if (isArgumentEscape(value)) {
argumentEscapeEncountered = true;
return peek();
}
if (isSwitch(value)) {
if (isShortSwitchList(value)) {
var tokens = splitSwitchTokens(value);
return tokens.get(0);
} else {
return new SwitchToken(value.substring(2), value);
}
} else {
return new ArgumentToken(value);
}
} |
python | def _clean(c):
"""
Nuke docs build target directory so next build is clean.
"""
if isdir(c.sphinx.target):
rmtree(c.sphinx.target) |
java | public PutItemResponse putItem(PutItemRequest request) {
checkNotNull(request, "request should not be null.");
InternalRequest httpRequest = createRequestUnderInstance(HttpMethodName.PUT,
MolaDbConstants.URI_TABLE,
request.getTableName(),
MolaDbConstants.URI_ITEM);
fillInHeadAndBody(request, httpRequest);
PutItemResponse ret = this.invokeHttpClient(httpRequest, PutItemResponse.class);
return ret;
} |
java | @Override
public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) {
return commerceTierPriceEntryPersistence.findWithDynamicQuery(dynamicQuery);
} |
java | public EKBCommit addUpdate(Object update) {
if (update != null) {
checkIfModel(update);
updates.add((OpenEngSBModel) update);
}
return this;
} |
java | public int commandToDocType(String strCommand)
{
if (MessageLog.MESSAGE_SCREEN.equalsIgnoreCase(strCommand))
return MessageLog.MESSAGE_SCREEN_MODE;
if (MessageLog.SOURCE_SCREEN.equalsIgnoreCase(strCommand))
return MessageLog.SOURCE_SCREEN_MODE;
return super.commandToDocType(strCommand);
} |
java | public static boolean isContainmentProxy(DatabindContext ctxt, EObject owner, EObject contained) {
if (contained.eIsProxy())
return true;
Resource ownerResource = EMFContext.getResource(ctxt, owner);
Resource containedResource = EMFContext.getResource(ctxt, contained);
return ownerResource != null && ownerResource != containedResource;
} |
java | private byte[] doEncryptionOrDecryption(byte[] crypt, Key key, int mode) {
Cipher rsaCipher;
try {
rsaCipher = Cipher.getInstance(CIPHER);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw SeedException.wrap(e, CryptoErrorCode.UNABLE_TO_GET_CIPHER)
.put("alias", alias)
.put("cipher", CIPHER);
}
try {
rsaCipher.init(mode, key);
} catch (InvalidKeyException e) {
throw SeedException.wrap(e, CryptoErrorCode.INVALID_KEY)
.put("alias", alias);
}
try {
return rsaCipher.doFinal(crypt);
} catch (IllegalBlockSizeException | BadPaddingException e) {
throw SeedException.wrap(e, CryptoErrorCode.UNEXPECTED_EXCEPTION);
}
} |
python | def add_param_summary(*summary_lists, **kwargs):
"""
Add summary ops for all trainable variables matching the regex, under a
reused 'param-summary' name scope.
This function is a no-op if not calling from main training tower.
Args:
summary_lists (list): each is (regex, [list of summary type]).
Summary type is defined in :func:`add_tensor_summary`.
collections (list[str]): collections of the summary ops.
Example:
.. code-block:: python
add_param_summary(
('.*/W', ['histogram', 'rms']),
('.*/gamma', ['scalar']),
)
"""
collections = kwargs.pop('collections', None)
assert len(kwargs) == 0, "Unknown kwargs: " + str(kwargs)
ctx = get_current_tower_context()
if ctx is not None and not ctx.is_main_training_tower:
return
params = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
with cached_name_scope('param-summary'):
for p in params:
name = p.op.name
for rgx, actions in summary_lists:
if not rgx.endswith('$'):
rgx = rgx + '$'
if re.match(rgx, name):
add_tensor_summary(p, actions, name=name, collections=collections) |
python | def start_optimisation(self, rounds: int, max_angle: float,
max_distance: float, temp: float=298.15,
stop_when=None, verbose=None):
"""Starts the loop fitting protocol.
Parameters
----------
rounds : int
The number of Monte Carlo moves to be evaluated.
max_angle : float
The maximum variation in rotation that can moved per
step.
max_distance : float
The maximum distance the can be moved per step.
temp : float, optional
Temperature used during fitting process.
stop_when : float, optional
Stops fitting when energy is less than or equal to this value.
"""
self._generate_initial_score()
self._mmc_loop(rounds, max_angle, max_distance, temp=temp,
stop_when=stop_when, verbose=verbose)
return |
java | public static StringBuilder join(StringBuilder builder, String delim, Object... objects) {
return join(builder, delim, Arrays.asList(objects));
} |
python | def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(NfsCollector, self).get_default_config()
config.update({
'path': 'nfs'
})
return config |
java | public static sslcrl_binding get(nitro_service service, String crlname) throws Exception{
sslcrl_binding obj = new sslcrl_binding();
obj.set_crlname(crlname);
sslcrl_binding response = (sslcrl_binding) obj.get_resource(service);
return response;
} |
java | public static <D extends CalendarVariant<D>> Factory<D> on(
CalendarFamily<D> family,
String variant
) {
Class<D> chronoType = family.getChronoType();
TimeLine<D> timeLine = family.getTimeLine(variant);
CalendarSystem<D> calsys = family.getCalendarSystem(variant);
return new Factory<>(chronoType, variant, timeLine, calsys);
} |
java | public static String removeModifierSuffix(String fullName) {
int indexOfFirstOpeningToken = fullName.indexOf(MODIFIER_OPENING_TOKEN);
if (indexOfFirstOpeningToken == -1) {
return fullName;
}
int indexOfSecondOpeningToken = fullName.lastIndexOf(MODIFIER_OPENING_TOKEN);
if (indexOfSecondOpeningToken != indexOfFirstOpeningToken) {
throw new IllegalArgumentException("Attribute name '" + fullName
+ "' is not valid as it contains more than one " + MODIFIER_OPENING_TOKEN);
}
int indexOfFirstClosingToken = fullName.indexOf(MODIFIER_CLOSING_TOKEN);
if (indexOfFirstClosingToken != fullName.length() - 1) {
throw new IllegalArgumentException("Attribute name '" + fullName
+ "' is not valid as the last character is not " + MODIFIER_CLOSING_TOKEN);
}
return fullName.substring(0, indexOfFirstOpeningToken);
} |
python | def write_out(self, message, verbosity_level=1):
"""
Convenient method for outputing.
"""
if self.verbosity and self.verbosity >= verbosity_level:
sys.stdout.write(smart_str(message))
sys.stdout.flush() |
python | def execute(self, arg_list):
"""Main function to parse and dispatch commands by given ``arg_list``
:param arg_list: all arguments provided by the command line
:param type: list
"""
arg_map = self.parser.parse_args(arg_list).__dict__
command = arg_map.pop(self._COMMAND_FLAG)
return command(**arg_map) |
python | def get_chromosomes_summary(snps):
""" Summary of the chromosomes of SNPs.
Parameters
----------
snps : pandas.DataFrame
Returns
-------
str
human-readable listing of chromosomes (e.g., '1-3, MT'), empty str if no chromosomes
"""
if isinstance(snps, pd.DataFrame):
chroms = list(pd.unique(snps["chrom"]))
int_chroms = [int(chrom) for chrom in chroms if chrom.isdigit()]
str_chroms = [chrom for chrom in chroms if not chrom.isdigit()]
# https://codereview.stackexchange.com/a/5202
def as_range(iterable):
l = list(iterable)
if len(l) > 1:
return "{0}-{1}".format(l[0], l[-1])
else:
return "{0}".format(l[0])
# create str representations
int_chroms = ", ".join(
as_range(g)
for _, g in groupby(int_chroms, key=lambda n, c=count(): n - next(c))
)
str_chroms = ", ".join(str_chroms)
if int_chroms != "" and str_chroms != "":
int_chroms += ", "
return int_chroms + str_chroms
else:
return "" |
python | def ray_spheres_intersection(origin, direction, centers, radii):
"""Calculate the intersection points between a ray and multiple
spheres.
**Returns**
intersections
distances
Ordered by closest to farther
"""
b_v = 2.0 * ((origin - centers) * direction).sum(axis=1)
c_v = ((origin - centers)**2).sum(axis=1) - radii ** 2
det_v = b_v * b_v - 4.0 * c_v
inters_mask = det_v >= 0
intersections = (inters_mask).nonzero()[0]
distances = (-b_v[inters_mask] - np.sqrt(det_v[inters_mask])) / 2.0
# We need only the thing in front of us, that corresponts to
# positive distances.
dist_mask = distances > 0.0
# We correct this aspect to get an absolute distance
distances = distances[dist_mask]
intersections = intersections[dist_mask].tolist()
if intersections:
distances, intersections = zip(*sorted(zip(distances, intersections)))
return list(intersections), list(distances)
else:
return [], [] |
python | def get_dssp_annotations(self, representative_only=True, force_rerun=False):
"""Run DSSP on structures and store calculations.
Annotations are stored in the protein structure's chain sequence at:
``<chain_prop>.seq_record.letter_annotations['*-dssp']``
Args:
representative_only (bool): If analysis should only be run on the representative structure
force_rerun (bool): If calculations should be rerun even if an output file exists
Todo:
* Some errors arise from storing annotations for nonstandard amino acids, need to run DSSP separately for those
"""
if representative_only:
if self.representative_structure:
try:
self.representative_structure.get_dssp_annotations(outdir=self.structure_dir, force_rerun=force_rerun)
except PDBException as e:
log.error('{}: Biopython error, issue matching sequences with {}'.format(self.id, self.representative_structure))
print(e)
except TypeError as e:
log.error('{}: Biopython error, DSSP SeqRecord length mismatch with {}'.format(self.id, self.representative_structure))
print(e)
except Exception as e:
log.error('{}: DSSP failed to run on {}'.format(self.id, self.representative_structure))
print(e)
else:
log.warning('{}: no representative structure set, cannot run DSSP'.format(self.id))
else:
for s in self.structures:
try:
s.get_dssp_annotations(outdir=self.structure_dir)
except PDBException as e:
log.error('{}: Biopython error, issue matching sequences with {}'.format(self.id, s.id))
print(e)
except TypeError as e:
log.error('{}: Biopython error, DSSP SeqRecord length mismatch with {}'.format(self.id, s.id))
print(e)
except Exception as e:
log.error('{}: DSSP failed to run on {}'.format(self.id, s.id))
print(e) |
python | def param_request_read_encode(self, target_system, target_component, param_id, param_index):
'''
Request to read the onboard parameter with the param_id string id.
Onboard parameters are stored as key[const char*] ->
value[float]. This allows to send a parameter to any
other component (such as the GCS) without the need of
previous knowledge of possible parameter names. Thus
the same GCS can store different parameters for
different autopilots. See also
http://qgroundcontrol.org/parameter_interface for a
full documentation of QGroundControl and IMU code.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
param_id : Onboard parameter id, terminated by NULL if the length is less than 16 human-readable chars and WITHOUT null termination (NULL) byte if the length is exactly 16 chars - applications have to provide 16+1 bytes storage if the ID is stored as string (char)
param_index : Parameter index. Send -1 to use the param ID field as identifier (else the param id will be ignored) (int16_t)
'''
return MAVLink_param_request_read_message(target_system, target_component, param_id, param_index) |
java | protected ObjectElement getObjectElement(IResource resource, SecurityEventObjectLifecycleEnum lifecycle, byte[] query) throws InstantiationException, IllegalAccessException {
String resourceType = resource.getResourceName();
if (myAuditableResources.containsKey(resourceType)) {
log.debug("Found auditable resource of type: " + resourceType);
@SuppressWarnings("unchecked")
IResourceAuditor<IResource> auditableResource = (IResourceAuditor<IResource>) myAuditableResources.get(resourceType).newInstance();
auditableResource.setResource(resource);
if (auditableResource.isAuditable()) {
ObjectElement object = new ObjectElement();
object.setReference(new ResourceReferenceDt(resource.getId()));
object.setLifecycle(lifecycle);
object.setQuery(query);
object.setName(auditableResource.getName());
object.setIdentifier((IdentifierDt) auditableResource.getIdentifier());
object.setType(auditableResource.getType());
object.setDescription(auditableResource.getDescription());
Map<String, String> detailMap = auditableResource.getDetail();
if (detailMap != null && !detailMap.isEmpty()) {
List<ObjectDetail> details = new ArrayList<SecurityEvent.ObjectDetail>();
for (Entry<String, String> entry : detailMap.entrySet()) {
ObjectDetail detail = makeObjectDetail(entry.getKey(), entry.getValue());
details.add(detail);
}
object.setDetail(details);
}
if (auditableResource.getSensitivity() != null) {
CodingDt coding = object.getSensitivity().addCoding();
coding.setSystem(auditableResource.getSensitivity().getSystemElement().getValue());
coding.setCode(auditableResource.getSensitivity().getCodeElement().getValue());
coding.setDisplay(auditableResource.getSensitivity().getDisplayElement().getValue());
}
return object;
} else {
log.debug("Resource is not auditable");
}
} else {
log.debug("No auditor configured for resource type " + resourceType);
}
return null; // not something we care to audit
} |
java | public static UploadAttachmentResponse postUploadAttachment(
StringEntity input) {
String pageToken = FbBotMillContext.getInstance().getPageToken();
// If the page token is invalid, returns.
if (!validatePageToken(pageToken)) {
return null;
}
String url = FbBotMillNetworkConstants.FACEBOOK_BASE_URL
+ FbBotMillNetworkConstants.FACEBOOK_UPLOAD_API_URL + pageToken;
BotMillNetworkResponse response = postInternal(url, input);
// Parses the response as a UploadAttachmentResponse and returns it.
return FbBotMillJsonUtils.fromJson(response.getResponse(),
UploadAttachmentResponse.class);
} |
java | public int decide(final LoggingEvent event) {
calendar.setTimeInMillis(event.timeStamp);
//
// get apparent number of milliseconds since midnight
// (ignores extra or missing hour on daylight time changes).
//
long apparentOffset = calendar.get(Calendar.HOUR_OF_DAY) * HOUR_MS +
calendar.get(Calendar.MINUTE) * MINUTE_MS +
calendar.get(Calendar.SECOND) * SECOND_MS +
calendar.get(Calendar.MILLISECOND);
if (apparentOffset >= start && apparentOffset < end) {
if (acceptOnMatch) {
return Filter.ACCEPT;
} else {
return Filter.DENY;
}
}
return Filter.NEUTRAL;
} |
java | public void identify(
final @Nullable String userId,
final @Nullable Traits newTraits,
final @Nullable Options options) {
assertNotShutdown();
if (isNullOrEmpty(userId) && isNullOrEmpty(newTraits)) {
throw new IllegalArgumentException("Either userId or some traits must be provided.");
}
analyticsExecutor.submit(
new Runnable() {
@Override
public void run() {
Traits traits = traitsCache.get();
if (!isNullOrEmpty(userId)) {
traits.putUserId(userId);
}
if (!isNullOrEmpty(newTraits)) {
traits.putAll(newTraits);
}
traitsCache.set(traits); // Save the new traits
analyticsContext.setTraits(traits); // Update the references
final Options finalOptions;
if (options == null) {
finalOptions = defaultOptions;
} else {
finalOptions = options;
}
IdentifyPayload.Builder builder =
new IdentifyPayload.Builder().traits(traitsCache.get());
fillAndEnqueue(builder, finalOptions);
}
});
} |
java | public static String createSubsetPrefix() {
StringBuilder sb = new StringBuilder(8);
for (int k = 0; k < 6; ++k) {
sb.append( (char)(Math.random() * 26 + 'A') );
}
sb.append("+");
return sb.toString();
} |
java | @Override
public void authorizeEJB(EJBRequestData request, Subject subject) throws EJBAccessDeniedException {
auditManager = new AuditManager();
Object req = auditManager.getHttpServletRequest();
Object webRequest = auditManager.getWebRequest();
String realm = auditManager.getRealm();
EJBMethodMetaData methodMetaData = request.getEJBMethodMetaData();
Object[] methodArguments = request.getMethodArguments();
String applicationName = methodMetaData.getEJBComponentMetaData().getJ2EEName().getApplication();
String moduleName = methodMetaData.getEJBComponentMetaData().getJ2EEName().getModule();
String methodName = methodMetaData.getMethodName();
String methodInterface = methodMetaData.getEJBMethodInterface().specName();
String methodSignature = methodMetaData.getMethodSignature();
String beanName = methodMetaData.getEJBComponentMetaData().getJ2EEName().getComponent();
List<Object> methodParameters = null;
populateAuditEJBHashMap(request);
Object bean = request.getBeanInstance();
EnterpriseBean ejb = null;
if (bean instanceof EnterpriseBean) {
ejb = (EnterpriseBean) bean;
}
if (methodArguments != null && methodArguments.length > 0) {
methodParameters = Arrays.asList(methodArguments);
}
boolean isAuthorized = jaccServiceRef.getService().isAuthorized(applicationName, moduleName, beanName, methodName, methodInterface, methodSignature, methodParameters, ejb,
subject);
String authzUserName = subject.getPrincipals(WSPrincipal.class).iterator().next().getName();
if (!isAuthorized) {
Tr.audit(tc, "EJB_JACC_AUTHZ_FAILED", authzUserName, methodName, applicationName);
AuditAuthenticationResult auditAuthResult = new AuditAuthenticationResult(AuditAuthResult.FAILURE, authzUserName, AuditEvent.CRED_TYPE_BASIC, null, AuditEvent.OUTCOME_FAILURE);
Audit.audit(Audit.EventID.SECURITY_AUTHZ_03, auditAuthResult, ejbAuditHashMap, req, webRequest, realm, subject, Integer.valueOf("403"));
throw new EJBAccessDeniedException(TraceNLS.getFormattedMessage(this.getClass(),
TraceConstants.MESSAGE_BUNDLE,
"EJB_JACC_AUTHZ_FAILED",
new Object[] { authzUserName, methodName, applicationName },
"CWWKS9406A: Authorization by the JACC provider failed. The user is not granted access to any of the required roles."));
} else {
AuditAuthenticationResult auditAuthResult = new AuditAuthenticationResult(AuditAuthResult.SUCCESS, authzUserName, AuditEvent.CRED_TYPE_BASIC, null, AuditEvent.OUTCOME_SUCCESS);
Audit.audit(Audit.EventID.SECURITY_AUTHZ_03, auditAuthResult, ejbAuditHashMap, req, webRequest, realm, subject, Integer.valueOf("200"));
}
} |
java | @Override
public Optional<T> findById(final ID id) {
return arangoOperations.find(id, domainClass);
} |
java | public ServiceFuture<ComputePolicyInner> createOrUpdateAsync(String resourceGroupName, String accountName, String computePolicyName, CreateOrUpdateComputePolicyParameters parameters, final ServiceCallback<ComputePolicyInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, computePolicyName, parameters), serviceCallback);
} |
java | private <T> InternalProviderImpl<? extends T> getUnBoundProvider(Class<T> clazz, String bindingName) {
return getInternalProvider(clazz, bindingName, false);
} |
java | static Predicate<CtClass> createExcludePredicate(@Nullable final String[] classes) {
final Set<PathMatcher> excludeSet;
if (classes != null && classes.length != 0) {
excludeSet = createPathMatcherSet(classes);
} else {
return ctClass -> false;
}
return createMatchingPredicate(excludeSet);
} |
python | def lazy_imap(data_processor, data_generator, n_cpus=1, stepsize=None):
"""A variant of multiprocessing.Pool.imap that supports lazy evaluation
As with the regular multiprocessing.Pool.imap, the processes are spawned
off asynchronously while the results are returned in order. In contrast to
multiprocessing.Pool.imap, the iterator (here: data_generator) is not
consumed at once but evaluated lazily which is useful if the iterator
(for example, a generator) contains objects with a large memory footprint.
Parameters
==========
data_processor : func
A processing function that is applied to objects in `data_generator`
data_generator : iterator or generator
A python iterator or generator that yields objects to be fed into the
`data_processor` function for processing.
n_cpus=1 : int (default: 1)
Number of processes to run in parallel.
- If `n_cpus` > 0, the specified number of CPUs will be used.
- If `n_cpus=0`, all available CPUs will be used.
- If `n_cpus` < 0, all available CPUs - `n_cpus` will be used.
stepsize : int or None (default: None)
The number of items to fetch from the iterator to pass on to the
workers at a time.
If `stepsize=None` (default), the stepsize size will
be set equal to `n_cpus`.
Returns
=========
list : A Python list containing the *n* results returned
by the `data_processor` function when called on
elements by the `data_generator` in
sorted order; *n* is equal to the size of `stepsize`. If `stepsize`
is None, *n* is equal to `n_cpus`.
"""
if not n_cpus:
n_cpus = mp.cpu_count()
elif n_cpus < 0:
n_cpus = mp.cpu_count() - n_cpus
if stepsize is None:
stepsize = n_cpus
with mp.Pool(processes=n_cpus) as p:
while True:
r = p.map(data_processor, islice(data_generator, stepsize))
if r:
yield r
else:
break |
java | public static void transpose(DMatrixSparseCSC A , DMatrixSparseCSC C , @Nullable IGrowArray gw ) {
int []work = adjust(gw,A.numRows,A.numRows);
C.reshape(A.numCols,A.numRows,A.nz_length);
// compute the histogram for each row in 'a'
int idx0 = A.col_idx[0];
for (int j = 1; j <= A.numCols; j++) {
int idx1 = A.col_idx[j];
for (int i = idx0; i < idx1; i++) {
if( A.nz_rows.length <= i)
throw new RuntimeException("Egads");
work[A.nz_rows[i]]++;
}
idx0 = idx1;
}
// construct col_idx in the transposed matrix
C.histogramToStructure(work);
System.arraycopy(C.col_idx,0,work,0,C.numCols);
// fill in the row indexes
idx0 = A.col_idx[0];
for (int j = 1; j <= A.numCols; j++) {
int col = j-1;
int idx1 = A.col_idx[j];
for (int i = idx0; i < idx1; i++) {
int row = A.nz_rows[i];
int index = work[row]++;
C.nz_rows[index] = col;
C.nz_values[index] = A.nz_values[i];
}
idx0 = idx1;
}
} |
python | def process(self, batch):
"""Process a single, partitioned query or read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_query_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet`
:returns: a result set instance which can be used to consume rows.
:raises ValueError: if batch does not contain either 'read' or 'query'
"""
if "query" in batch:
return self.process_query_batch(batch)
if "read" in batch:
return self.process_read_batch(batch)
raise ValueError("Invalid batch") |
python | def h(values):
"""
Function calculates entropy.
values: list of integers
"""
ent = np.true_divide(values, np.sum(values))
return -np.sum(np.multiply(ent, np.log2(ent))) |
java | public IFeatureAlphabet rebuildFeatureAlphabet(String name) {
IFeatureAlphabet alphabet = null;
if (maps.containsKey(name)) {
alphabet = (IFeatureAlphabet) maps.get(name);
alphabet.clear();
}else{
return buildFeatureAlphabet(name,defaultFeatureType);
}
return alphabet;
} |
python | def django_js(context, jquery=True, i18n=True, csrf=True, init=True):
'''Include Django.js javascript library in the page'''
return {
'js': {
'minified': not settings.DEBUG,
'jquery': _boolean(jquery),
'i18n': _boolean(i18n),
'csrf': _boolean(csrf),
'init': _boolean(init),
}
} |
java | void handleFileItemClick(ItemClickEvent event) {
if (isEditing()) {
stopEdit();
} else if (!event.isCtrlKey() && !event.isShiftKey()) {
// don't interfere with multi-selection using control key
String itemId = (String)event.getItemId();
CmsUUID structureId = getUUIDFromItemID(itemId);
boolean openedFolder = false;
if (event.getButton().equals(MouseButton.RIGHT)) {
handleSelection(itemId);
openContextMenu(event);
} else {
if ((event.getPropertyId() == null)
|| CmsResourceTableProperty.PROPERTY_TYPE_ICON.equals(event.getPropertyId())) {
handleSelection(itemId);
openContextMenu(event);
} else {
if (m_actionColumnProperty.equals(event.getPropertyId())) {
Boolean isFolder = (Boolean)event.getItem().getItemProperty(
CmsResourceTableProperty.PROPERTY_IS_FOLDER).getValue();
if ((isFolder != null) && isFolder.booleanValue()) {
if (m_folderSelectHandler != null) {
m_folderSelectHandler.onFolderSelect(structureId);
}
openedFolder = true;
} else {
try {
CmsObject cms = A_CmsUI.getCmsObject();
CmsResource res = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
m_currentResources = Collections.singletonList(res);
I_CmsDialogContext context = m_contextProvider.getDialogContext();
I_CmsDefaultAction action = OpenCms.getWorkplaceAppManager().getDefaultAction(
context,
m_menuBuilder);
if (action != null) {
action.executeAction(context);
return;
}
} catch (CmsVfsResourceNotFoundException e) {
LOG.info(e.getLocalizedMessage(), e);
} catch (CmsException e) {
LOG.error(e.getLocalizedMessage(), e);
}
}
} else {
I_CmsDialogContext context = m_contextProvider.getDialogContext();
if ((m_currentResources.size() == 1)
&& m_currentResources.get(0).getStructureId().equals(structureId)
&& (context instanceof I_CmsEditPropertyContext)
&& ((I_CmsEditPropertyContext)context).isPropertyEditable(event.getPropertyId())) {
((I_CmsEditPropertyContext)context).editProperty(event.getPropertyId());
}
}
}
}
// update the item on click to show any available changes
if (!openedFolder) {
update(Collections.singletonList(structureId), false);
}
}
} |
java | public CRestBuilder extractsEntityAuthParamsWith(String entityContentType, EntityParamExtractor entityParamExtractor){
this.httpEntityParamExtrators.put(entityContentType, entityParamExtractor);
return this;
} |
java | public void getWvWMatchOverview(int worldID, Callback<WvWMatchOverview> callback) throws NullPointerException {
gw2API.getWvWMatchOverviewUsingWorld(Integer.toString(worldID)).enqueue(callback);
} |
java | public Grammar register(@NonNull ParserTokenType type, @NonNull PrefixHandler handler) {
prefixHandlers.put(type, handler);
return this;
} |
java | @XmlElementDecl(namespace = "http://www.opengis.net/citygml/relief/1.0", name = "_GenericApplicationPropertyOfTinRelief")
public JAXBElement<Object> create_GenericApplicationPropertyOfTinRelief(Object value) {
return new JAXBElement<Object>(__GenericApplicationPropertyOfTinRelief_QNAME, Object.class, null, value);
} |
java | public void add(MultidimensionalReward other) {
for (Map.Entry<Integer, Float> entry : other.map.entrySet()) {
Integer dimension = entry.getKey();
Float reward_value = entry.getValue();
this.add(dimension.intValue(), reward_value.floatValue());
}
} |
java | @Deprecated
public java.util.List<Clip> getComposition() {
if (composition == null) {
composition = new com.amazonaws.internal.SdkInternalList<Clip>();
}
return composition;
} |
java | private void checkNonNullParam(Location location, ConstantPoolGen cpg, TypeDataflow typeDataflow,
InvokeInstruction invokeInstruction, BitSet nullArgSet, BitSet definitelyNullArgSet) {
if (inExplicitCatchNullBlock(location)) {
return;
}
boolean caught = inIndirectCatchNullBlock(location);
if (caught && skipIfInsideCatchNull()) {
return;
}
if (invokeInstruction instanceof INVOKEDYNAMIC) {
return;
}
XMethod m = XFactory.createXMethod(invokeInstruction, cpg);
INullnessAnnotationDatabase db = AnalysisContext.currentAnalysisContext().getNullnessAnnotationDatabase();
SignatureParser sigParser = new SignatureParser(invokeInstruction.getSignature(cpg));
for (int i = nullArgSet.nextSetBit(0); i >= 0; i = nullArgSet.nextSetBit(i + 1)) {
if (db.parameterMustBeNonNull(m, i)) {
boolean definitelyNull = definitelyNullArgSet.get(i);
if (DEBUG_NULLARG) {
System.out.println("Checking " + m);
System.out.println("QQQ2: " + i + " -- " + i + " is null");
System.out.println("QQQ nullArgSet: " + nullArgSet);
System.out.println("QQQ dnullArgSet: " + definitelyNullArgSet);
}
BugAnnotation variableAnnotation = null;
try {
ValueNumberFrame vnaFrame = classContext.getValueNumberDataflow(method).getFactAtLocation(location);
ValueNumber valueNumber = vnaFrame.getArgument(invokeInstruction, cpg, i, sigParser);
variableAnnotation = ValueNumberSourceInfo.findAnnotationFromValueNumber(method, location, valueNumber,
vnaFrame, "VALUE_OF");
} catch (DataflowAnalysisException e) {
AnalysisContext.logError("error", e);
} catch (CFGBuilderException e) {
AnalysisContext.logError("error", e);
}
int priority = definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY;
if (caught) {
priority++;
}
if (m.isPrivate() && priority == HIGH_PRIORITY) {
priority = NORMAL_PRIORITY;
}
String description = definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG";
WarningPropertySet<WarningProperty> propertySet = new WarningPropertySet<>();
Set<Location> derefLocationSet = Collections.singleton(location);
addPropertiesForDereferenceLocations(propertySet, derefLocationSet, false);
boolean duplicated = isDuplicated(propertySet, location.getHandle().getPosition(), false);
if (duplicated) {
return;
}
BugInstance warning = new BugInstance(this, "NP_NONNULL_PARAM_VIOLATION", priority)
.addClassAndMethod(classContext.getJavaClass(), method).addMethod(m)
.describe(MethodAnnotation.METHOD_CALLED).addParameterAnnotation(i, description)
.addOptionalAnnotation(variableAnnotation).addSourceLine(classContext, method, location);
propertySet.decorateBugInstance(warning);
bugReporter.reportBug(warning);
}
}
} |
python | def write_position(fp, position, value, fmt='I'):
"""
Writes a value to the specified position.
:param fp: file-like object
:param position: position of the value marker
:param value: value to write
:param fmt: format of the value
:return: written byte size
"""
current_position = fp.tell()
fp.seek(position)
written = write_bytes(fp, struct.pack(str('>' + fmt), value))
fp.seek(current_position)
return written |
python | def sjuncChunk(key, chunk):
"""
Parse Super Junction (SJUNC) Chunk Method
"""
schunk = chunk[0].strip().split()
result = {'sjuncNumber': schunk[1],
'groundSurfaceElev': schunk[2],
'invertElev': schunk[3],
'manholeSA': schunk[4],
'inletCode': schunk[5],
'linkOrCellI': schunk[6],
'nodeOrCellJ': schunk[7],
'weirSideLength': schunk[8],
'orificeDiameter': schunk[9]}
return result |
java | @Override
public T findOne(final I id) {
return inTransaction(new Callable<T>() {
@Override
public T call() throws Exception {
return entityManager.find(entity, id);
}
});
} |
java | private boolean isImplementationOf(@SlashedClassName String clsName, JavaClass inf) {
try {
if (clsName.startsWith("java/lang/")) {
return false;
}
JavaClass cls = Repository.lookupClass(clsName);
return isImplementationOf(cls, inf);
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
}
return false;
} |
java | protected void abortPublishJob(CmsUUID userId, CmsPublishJobEnqueued publishJob, boolean removeJob)
throws CmsException, CmsPublishException {
// abort event should be raised before the job is removed implicitly
m_listeners.fireAbort(userId, publishJob);
if ((m_currentPublishThread == null)
|| !publishJob.m_publishJob.equals(m_currentPublishThread.getPublishJob())) {
// engine is currently publishing another job or is not publishing
if (!m_publishQueue.abortPublishJob(publishJob.m_publishJob)) {
// job not found
throw new CmsPublishException(
Messages.get().container(Messages.ERR_PUBLISH_ENGINE_MISSING_PUBLISH_JOB_0));
}
} else if (!m_shuttingDown) {
// engine is currently publishing the job to abort
m_currentPublishThread.abort();
} else if (m_shuttingDown && (m_currentPublishThread != null)) {
// aborting the current job during shut down
I_CmsReport report = m_currentPublishThread.getReport();
report.println();
report.println();
report.println(
Messages.get().container(Messages.RPT_PUBLISH_JOB_ABORT_SHUTDOWN_0),
I_CmsReport.FORMAT_ERROR);
report.println();
}
// unlock all resources
if (publishJob.getPublishList() != null) {
unlockPublishList(publishJob.m_publishJob);
}
// keep job if requested
if (!removeJob) {
// set finish info
publishJob.m_publishJob.finish();
getPublishHistory().add(publishJob.m_publishJob);
} else {
getPublishQueue().remove(publishJob.m_publishJob);
}
} |
java | private void initializeColAndRowComponentLists() {
colComponents = new List[getColumnCount()];
for (int i = 0; i < getColumnCount(); i++) {
colComponents[i] = new ArrayList<Component>();
}
rowComponents = new List[getRowCount()];
for (int i = 0; i < getRowCount(); i++) {
rowComponents[i] = new ArrayList<Component>();
}
for (Object element : constraintMap.entrySet()) {
Map.Entry entry = (Map.Entry) element;
Component component = (Component) entry.getKey();
CellConstraints constraints = (CellConstraints) entry.getValue();
if (takeIntoAccount(component, constraints)) {
if (constraints.gridWidth == 1) {
colComponents[constraints.gridX - 1].add(component);
}
if (constraints.gridHeight == 1) {
rowComponents[constraints.gridY - 1].add(component);
}
}
}
} |
python | def delete(self, cascade=False, delete_shares=False):
"""
Deletes the video.
"""
if self.id:
self.connection.post('delete_video', video_id=self.id,
cascade=cascade, delete_shares=delete_shares)
self.id = None |
python | def get_sdc_by_ip(self, ip):
"""
Get ScaleIO SDC object by its ip
:param name: IP address of SDC
:return: ScaleIO SDC object
:raise KeyError: No SDC with specified IP found
:rtype: SDC object
"""
if self.conn.is_ip_addr(ip):
for sdc in self.sdc:
if sdc.sdcIp == ip:
return sdc
raise KeyError("SDS of that name not found")
else:
raise ValueError("Malformed IP address - get_sdc_by_ip()") |
python | def _checkAndConvertIndex(self, index):
"""Check integer index, convert from less than zero notation
"""
if index < 0:
index = len(self) + index
if index < 0 or index >= self._doc.blockCount():
raise IndexError('Invalid block index', index)
return index |
java | public final Mono<ByteBuffer> asByteBuffer() {
return handle((bb, sink) -> {
try {
sink.next(bb.nioBuffer());
}
catch (IllegalReferenceCountException e) {
sink.complete();
}
});
} |
java | public void refreshCredentials() {
if (this.credsProvider == null)
return;
try {
AlibabaCloudCredentials creds = this.credsProvider.getCredentials();
this.accessKeyID = creds.getAccessKeyId();
this.accessKeySecret = creds.getAccessKeySecret();
if (creds instanceof BasicSessionCredentials) {
this.securityToken = ((BasicSessionCredentials) creds).getSessionToken();
}
} catch (Exception e) {
e.printStackTrace();
}
} |
java | @Override
public com.liferay.commerce.model.CommerceOrderItem getCommerceOrderItem(
long commerceOrderItemId)
throws com.liferay.portal.kernel.exception.PortalException {
return _commerceOrderItemLocalService.getCommerceOrderItem(commerceOrderItemId);
} |
python | def van_dec_2d(x, skip_connections, output_shape, first_depth, hparams=None):
"""The VAN decoder.
Args:
x: The analogy information to decode.
skip_connections: The encoder layers which can be used as skip connections.
output_shape: The shape of the desired output image.
first_depth: The depth of the first layer of the van image encoder.
hparams: The python hparams.
Returns:
The decoded image prediction.
"""
with tf.variable_scope('van_dec'):
dec = tf.layers.conv2d_transpose(
x, first_depth * 4, 3, padding='same', activation=tf.nn.relu, strides=2)
dec = tf.nn.dropout(dec, hparams.van_keep_prob)
dec = tf.contrib.layers.layer_norm(dec)
dec = tf.layers.conv2d_transpose(
dec,
first_depth * 4,
3,
padding='same',
activation=tf.nn.relu,
strides=1)
dec = tf.nn.dropout(dec, hparams.van_keep_prob)
dec = tf.layers.conv2d_transpose(
dec,
first_depth * 2,
3,
padding='same',
activation=tf.nn.relu,
strides=1)
dec = tf.nn.dropout(dec, hparams.van_keep_prob)
dec = tf.contrib.layers.layer_norm(dec)
dec = tf.layers.conv2d_transpose(
dec,
first_depth * 2,
3,
padding='same',
activation=tf.nn.relu,
strides=2)
dec = tf.nn.dropout(dec, hparams.van_keep_prob)
dec = tf.layers.conv2d_transpose(
dec, first_depth, 3, padding='same', activation=tf.nn.relu, strides=1)
dec = tf.nn.dropout(dec, hparams.van_keep_prob)
dec = tf.contrib.layers.layer_norm(dec)
dec = tf.layers.conv2d_transpose(
dec,
output_shape[3] + 1,
3,
padding='same',
activation=tf.nn.relu,
strides=2)
dec = tf.nn.dropout(dec, hparams.van_keep_prob)
out_mask = tf.layers.conv2d_transpose(
dec, output_shape[3] + 1, 3, strides=1, padding='same', activation=None)
mask = tf.nn.sigmoid(out_mask[:, :, :, 3:4])
out = out_mask[:, :, :, :3]
return out * mask + skip_connections[0] * (1 - mask) |
python | def comparator_eval(comparator_params):
"""Gets BUFF score for interaction between two AMPAL objects
"""
top1, top2, params1, params2, seq1, seq2, movements = comparator_params
xrot, yrot, zrot, xtrans, ytrans, ztrans = movements
obj1 = top1(*params1)
obj2 = top2(*params2)
obj2.rotate(xrot, [1, 0, 0])
obj2.rotate(yrot, [0, 1, 0])
obj2.rotate(zrot, [0, 0, 1])
obj2.translate([xtrans, ytrans, ztrans])
model = obj1 + obj2
model.relabel_all()
model.pack_new_sequences(seq1 + seq2)
return model.buff_interaction_energy.total_energy |
python | def dale_chall(self, diff_count, words, sentences):
"""Calculate Dale-Chall readability score."""
pdw = diff_count / words * 100
asl = words / sentences
raw = 0.1579 * (pdw) + 0.0496 * asl
if pdw > 5:
return raw + 3.6365
return raw |
python | def local_position_ned_cov_encode(self, time_boot_ms, time_utc, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance):
'''
The filtered local position (e.g. fused computer vision and
accelerometers). Coordinate frame is right-handed,
Z-axis down (aeronautical frame, NED / north-east-down
convention)
time_boot_ms : Timestamp (milliseconds since system boot). 0 for system without monotonic timestamp (uint32_t)
time_utc : Timestamp (microseconds since UNIX epoch) in UTC. 0 for unknown. Commonly filled by the precision time source of a GPS receiver. (uint64_t)
estimator_type : Class id of the estimator this estimate originated from. (uint8_t)
x : X Position (float)
y : Y Position (float)
z : Z Position (float)
vx : X Speed (m/s) (float)
vy : Y Speed (m/s) (float)
vz : Z Speed (m/s) (float)
ax : X Acceleration (m/s^2) (float)
ay : Y Acceleration (m/s^2) (float)
az : Z Acceleration (m/s^2) (float)
covariance : Covariance matrix upper right triangular (first nine entries are the first ROW, next eight entries are the second row, etc.) (float)
'''
return MAVLink_local_position_ned_cov_message(time_boot_ms, time_utc, estimator_type, x, y, z, vx, vy, vz, ax, ay, az, covariance) |
python | def do_reconfig(self, params):
"""
\x1b[1mNAME\x1b[0m
reconfig - Reconfigures a ZooKeeper cluster (adds/removes members)
\x1b[1mSYNOPSIS\x1b[0m
reconfig <add|remove> <arg> [from_config]
\x1b[1mDESCRIPTION\x1b[0m
reconfig add <members> [from_config]
adds the given members (i.e.: 'server.100=10.0.0.10:2889:3888:observer;0.0.0.0:2181').
reconfig remove <members_ids> [from_config]
removes the members with the given ids (i.e.: '2,3,5').
\x1b[1mEXAMPLES\x1b[0m
> reconfig add server.100=0.0.0.0:56954:37866:observer;0.0.0.0:42969
server.1=localhost:20002:20001:participant
server.2=localhost:20012:20011:participant
server.3=localhost:20022:20021:participant
server.100=0.0.0.0:56954:37866:observer;0.0.0.0:42969
version=100000003
> reconfig remove 100
server.1=localhost:20002:20001:participant
server.2=localhost:20012:20011:participant
server.3=localhost:20022:20021:participant
version=100000004
"""
if params.cmd not in ["add", "remove"]:
raise ValueError("Bad command: %s" % params.cmd)
joining, leaving, from_config = None, None, params.from_config
if params.cmd == "add":
joining = params.args
elif params.cmd == "remove":
leaving = params.args
try:
value, _ = self._zk.reconfig(
joining=joining, leaving=leaving, new_members=None, from_config=from_config)
self.show_output(value)
except NewConfigNoQuorumError:
self.show_output("No quorum available to perform reconfig.")
except ReconfigInProcessError:
self.show_output("There's a reconfig in process.") |
python | def _get_prop_from_modelclass(modelclass, name):
"""Helper for FQL parsing to turn a property name into a property object.
Args:
modelclass: The model class specified in the query.
name: The property name. This may contain dots which indicate
sub-properties of structured properties.
Returns:
A Property object.
Raises:
KeyError if the property doesn't exist and the model clas doesn't
derive from Expando.
"""
if name == '__key__':
return modelclass._key
parts = name.split('.')
part, more = parts[0], parts[1:]
prop = modelclass._properties.get(part)
if prop is None:
if issubclass(modelclass, model.Expando):
prop = model.GenericProperty(part)
else:
raise TypeError('Model %s has no property named %r' %
(modelclass._get_kind(), part))
while more:
part = more.pop(0)
if not isinstance(prop, model.StructuredProperty):
raise TypeError('Model %s has no property named %r' %
(modelclass._get_kind(), part))
maybe = getattr(prop, part, None)
if isinstance(maybe, model.Property) and maybe._name == part:
prop = maybe
else:
maybe = prop._modelclass._properties.get(part)
if maybe is not None:
# Must get it this way to get the copy with the long name.
# (See StructuredProperty.__getattr__() for details.)
prop = getattr(prop, maybe._code_name)
else:
if issubclass(prop._modelclass, model.Expando) and not more:
prop = model.GenericProperty()
prop._name = name # Bypass the restriction on dots.
else:
raise KeyError('Model %s has no property named %r' %
(prop._modelclass._get_kind(), part))
return prop |
python | def line_cross(x1, y1, x2, y2, x3, y3, x4, y4):
""" 判断两条线段是否交叉 """
# out of the rect
if min(x1, x2) > max(x3, x4) or max(x1, x2) < min(x3, x4) or \
min(y1, y2) > max(y3, y4) or max(y1, y2) < min(y3, y4):
return False
# same slope rate
if ((y1 - y2) * (x3 - x4) == (x1 - x2) * (y3 - y4)):
return False
if cross_product(x3, y3, x2, y2, x4, y4) * cross_product(x3, y3, x4, y4, x1, y1) < 0 or \
cross_product(x1, y1, x4, y4, x2, y2) * cross_product(x1, y1, x2, y2, x3, y3) < 0:
return False
# get collide point
b1 = (y2 - y1) * x1 + (x1 - x2) * y1
b2 = (y4 - y3) * x3 + (x3 - x4) * y3
D = (x2 - x1) * (y4 - y3) - (x4 - x3) * (y2 - y1)
D1 = b2 * (x2 - x1) - b1 * (x4 - x3)
D2 = b2 * (y2 - y1) - b1 * (y4 - y3)
return P(D1 / D, D2 / D) |
python | def get_value(self, row, column):
"""Return the value of the DataFrame."""
# To increase the performance iat is used but that requires error
# handling, so fallback uses iloc
try:
value = self.df.iat[row, column]
except OutOfBoundsDatetime:
value = self.df.iloc[:, column].astype(str).iat[row]
except:
value = self.df.iloc[row, column]
return value |
java | public OvhBackendHttp serviceName_http_farm_POST(String serviceName, OvhBalanceHTTPEnum balance, String displayName, Long port, OvhBackendProbe probe, OvhStickinessHTTPEnum stickiness, Long vrackNetworkId, String zone) throws IOException {
String qPath = "/ipLoadbalancing/{serviceName}/http/farm";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "balance", balance);
addBody(o, "displayName", displayName);
addBody(o, "port", port);
addBody(o, "probe", probe);
addBody(o, "stickiness", stickiness);
addBody(o, "vrackNetworkId", vrackNetworkId);
addBody(o, "zone", zone);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhBackendHttp.class);
} |
python | def save_image(self, outname):
"""
Save the image data.
This is probably only useful if the image data has been blanked.
Parameters
----------
outname : str
Name for the output file.
"""
hdu = self.global_data.img.hdu
hdu.data = self.global_data.img._pixels
hdu.header["ORIGIN"] = "Aegean {0}-({1})".format(__version__, __date__)
# delete some axes that we aren't going to need
for c in ['CRPIX3', 'CRPIX4', 'CDELT3', 'CDELT4', 'CRVAL3', 'CRVAL4', 'CTYPE3', 'CTYPE4']:
if c in hdu.header:
del hdu.header[c]
hdu.writeto(outname, overwrite=True)
self.log.info("Wrote {0}".format(outname))
return |
python | def find_divisors(n):
""" Find all the positive divisors of the given integer n.
Args:
n (int): strictly positive integer
Returns:
A generator of all the positive divisors of n
Raises:
TypeError: if n is not an integer
ValueError: if n is negative
"""
if not isinstance(n, int):
raise TypeError("Expecting a strictly positive integer")
if n <= 0:
raise ValueError("Expecting a strictly positive integer")
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors = {i, n//i}
for divisor in divisors:
yield divisor |
python | def imgAverage(images, copy=True):
'''
returns an image average
works on many, also unloaded images
minimises RAM usage
'''
i0 = images[0]
out = imread(i0, dtype='float')
if copy and id(i0) == id(out):
out = out.copy()
for i in images[1:]:
out += imread(i, dtype='float')
out /= len(images)
return out |
python | def _validate_config(config_path):
'''
Validate that the configuration file exists and is readable.
:param str config_path: The path to the configuration file for the aptly instance.
:return: None
:rtype: None
'''
log.debug('Checking configuration file: %s', config_path)
if not os.path.isfile(config_path):
message = 'Unable to get configuration file: {}'.format(config_path)
log.error(message)
raise SaltInvocationError(message)
log.debug('Found configuration file: %s', config_path) |
java | public void addHandler(Handler handler, Stage stage)
{
if (!startStopLock.tryLock()) {
throw new ISE("Cannot add a handler in the process of Lifecycle starting or stopping");
}
try {
if (!state.get().equals(State.NOT_STARTED)) {
throw new ISE("Cannot add a handler after the Lifecycle has started, it doesn't work that way.");
}
handlers.get(stage).add(handler);
}
finally {
startStopLock.unlock();
}
} |
java | public String decode(byte[] encodedString, int offset, int length) throws IOException {
return new String(encodedString, offset, length, encoding);
} |
python | def project(self, term_doc_mat, x_dim=0, y_dim=1):
'''
Returns a projection of the categories
:param term_doc_mat: a TermDocMatrix
:return: CategoryProjection
'''
return self._project_category_corpus(self._get_category_metadata_corpus(term_doc_mat),
x_dim, y_dim) |
java | private void populateStep2() {
this.insertRoadmapItem(1, true, I18nLabelsLoader.REPORT_STEP_FALSE_ERRORS, 2);
// Bad intervention
int y = 6;
this.insertFixedTextBold(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, STEP_FALSE_ERRORS, I18nLabelsLoader.REPORT_STEP_FALSE_ERRORS);
y += 12;
// help text
this.insertMultilineFixedText(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, 8*4 , STEP_FALSE_ERRORS, I18nLabelsLoader.ADDON_BADINT_INFO);
y += 8*3 + 4;
// label ADDON_BADINT_ERRORSLIST
this.insertMultilineFixedText(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, 8*2, STEP_FALSE_ERRORS, I18nLabelsLoader.ADDON_BADINT_ERRORSLIST);
y += 8 + 12;
// list BadInt
this.badIntListBox = this.insertListBox(new BadIntListSelectonListener(), DEFAULT_PosX, y, 3*12, DEFAULT_WIDTH_LARGE, STEP_FALSE_ERRORS, theCommunityLogic.getBadInterventions());
y += 3*12 + 4;
// label ADDON_BADINT_ERRORSFOUND
this.insertFixedText(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, STEP_FALSE_ERRORS, I18nLabelsLoader.ADDON_BADINT_ERRORSFOUND);
y += 8; // plus one line
// field TEXT
this.badIntErrorsText = this.insertMultilineEditField(this, this, DEFAULT_PosX, y, 3*12, DEFAULT_WIDTH_LARGE, STEP_FALSE_ERRORS, "", true);
y += 3*12 + 4;
// label ADDON_BADINT_DETAILS
this.insertFixedText(this, DEFAULT_PosX, y, DEFAULT_WIDTH_LARGE, STEP_FALSE_ERRORS, I18nLabelsLoader.ADDON_BADINT_DETAILS);
y += 8; // plus one line
// field Details
this.badIntDetails = this.insertMultilineEditField(this, this, DEFAULT_PosX, y, 3*12, DEFAULT_WIDTH_LARGE, STEP_FALSE_ERRORS, "", true);
y += 3*12 + 4;
// label / field ADDON_BADINT_TYPE
this.insertFixedText(this, DEFAULT_PosX, y + 2, 40, STEP_FALSE_ERRORS, I18nLabelsLoader.ADDON_BADINT_TYPE);
this.badIntClassificationDropBox = this.insertDropBox(new BadIntClassificationDropBoxSelectionListener(), DEFAULT_PosX + 40, y, DEFAULT_WIDTH_LARGE - 40, STEP_FALSE_ERRORS, theCommunityLogic.getClassifications());
y += 14;
// label ADDON_BADINT_COMMENTS
this.badIntCommentsLabel = this.insertFixedText(this, DEFAULT_PosX, y, 40, STEP_FALSE_ERRORS, I18nLabelsLoader.ADDON_BADINT_COMMENTS);
y += 12;
// field Comments
this.badIntComments = this.insertMultilineEditField(new BadIntCommentsTextListener(), this, DEFAULT_PosX, y, 2*12, DEFAULT_WIDTH_LARGE, STEP_FALSE_ERRORS, "", false);
y += 2*12 + 4;
// button Apply
this.badIntApplyButton = this.insertButton(new BadIntApplyButtonListener(), DEFAULT_PosX + DEFAULT_WIDTH_LARGE - 40, y, 40, STEP_FALSE_ERRORS, I18nLabelsLoader.ADDON_BADINT_APPLY, ((short) PushButtonType.STANDARD_value));
setIsControlEnable(badIntApplyButton, false);
} |
python | def build_options(self):
"""The package build options.
:returns: :func:`set` of build options strings.
"""
if self.version.build_metadata:
return set(self.version.build_metadata.split('.'))
else:
return set() |
python | def get_all(self, key, fallback=None):
"""returns all header values for given key"""
if key in self.headers:
value = self.headers[key]
else:
value = fallback or []
return value |
java | public void put(String name, String value) {
List<String> list = new ArrayList<>();
list.add(value);
getMap().put(name, list);
} |
python | async def create_key(wallet_handle: int,
key_json: str) -> str:
"""
Creates keys pair and stores in the wallet.
:param wallet_handle: Wallet handle (created by open_wallet).
:param key_json: Key information as json. Example:
{
"seed": string, (optional) Seed that allows deterministic key creation (if not set random one will be created).
Can be UTF-8, base64 or hex string.
"crypto_type": string, // Optional (if not set then ed25519 curve is used);
Currently only 'ed25519' value is supported for this field.
}
:return: verkey: Ver key of generated key pair, also used as key identifier
"""
logger = logging.getLogger(__name__)
logger.debug("create_key: >>> wallet_handle: %r, key_json: %r",
wallet_handle,
key_json)
if not hasattr(create_key, "cb"):
logger.debug("create_key: Creating callback")
create_key.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p))
c_wallet_handle = c_int32(wallet_handle)
c_key_json = c_char_p(key_json.encode('utf-8'))
verkey = await do_call('indy_create_key',
c_wallet_handle,
c_key_json,
create_key.cb)
res = verkey.decode()
logger.debug("create_key: <<< res: %r", res)
return res |
java | public Date getTime() {
if (utc == null) {
return null;
}
Date date = null;
try {
date = XmppDateTime.parseDate(utc);
}
catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error getting local time", e);
}
return date;
} |
java | private static List<String> readLines(Option option) {
String optionStr = GsonUtil.format(option);
InputStream is = null;
InputStreamReader iReader = null;
BufferedReader bufferedReader = null;
List<String> lines = new ArrayList<String>();
String line;
try {
is = OptionUtil.class.getResourceAsStream("/template");
iReader = new InputStreamReader(is, "UTF-8");
bufferedReader = new BufferedReader(iReader);
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("##option##")) {
line = line.replace("##option##", optionStr);
}
lines.add(line);
}
} catch (Exception e) {
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
//ignore
}
}
}
return lines;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.