language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def color_replace(image, color):
"""Replace black with other color
:color: custom color (r,g,b,a)
:image: image to replace color
:returns: TODO
"""
pixels = image.load()
size = image.size[0]
for width in range(size):
for height in range(size):
r, g, b, a = pixels[wi... |
python | def softmax(explainer, op, *grads):
""" Just decompose softmax into its components and recurse, we can handle all of them :)
We assume the 'axis' is the last dimension because the TF codebase swaps the 'axis' to
the last dimension before the softmax op if 'axis' is not already the last dimension.
We al... |
java | void addCache(Path hdfsPath, Path localPath, long size) throws IOException {
localMetrics.numAdd++;
CacheEntry c = new CacheEntry(hdfsPath, localPath, size);
CacheEntry found = cacheMap.putIfAbsent(hdfsPath, c);
if (found != null) {
// If entry was already in the cache, update its timestamp
... |
java | public Blacklist generateBlacklist(Model model) throws IOException
{
Map<String, String> nameMapping = readNameMapping();
if (nameMapping == null)
{
generateNameMappingFileToCurate(model);
throw new RuntimeException("Small molecule name mapping file not found. Generated a " +
"mapping file, but it need... |
java | private void validateTimestampProtocol(String protocolString, String timestampFormat, String shape2) {
if (!StringUtils.isNullOrEmpty(timestampFormat) && isNonJsonProtocol(protocolString)) {
throw new IllegalArgumentException(String.format(
"Shape %s has timestamp format provided. Ti... |
java | public PrecompileDef createPrecompile() throws BuildException {
final Project p = getProject();
if (isReference()) {
throw noChildrenAllowed();
}
final PrecompileDef precomp = new PrecompileDef();
precomp.setProject(p);
this.precompileDefs.addElement(precomp);
return precomp;
} |
java | public Observable<Suggestions> autoSuggestAsync(String query, AutoSuggestOptionalParameter autoSuggestOptionalParameter) {
return autoSuggestWithServiceResponseAsync(query, autoSuggestOptionalParameter).map(new Func1<ServiceResponse<Suggestions>, Suggestions>() {
@Override
public Suggest... |
python | def lookup_generic(self, obj, as_of_date, country_code):
"""
Convert an object into an Asset or sequence of Assets.
This method exists primarily as a convenience for implementing
user-facing APIs that can handle multiple kinds of input. It should
not be used for internal code w... |
python | def ssn(self):
"""
Returns a 13 digits Swiss SSN named AHV (German) or
AVS (French and Italian)
See: http://www.bsv.admin.ch/themen/ahv/00011/02185/
"""
def _checksum(digits):
evensum = sum(digits[:-1:2])
oddsum ... |
java | public String getFromRemote(String uri){
// clear cache
fileSystem.getFilesCache().close();
String remoteContent ;
String remoteEncoding = "utf-8";
log.debug("getFromRemote: Loading remote URI=" + uri);
FileContent fileContent ;
try {
FileSystemOp... |
java | public void setSecurityHandlers(Set<IScopeSecurityHandler> handlers) {
if (securityHandlers == null) {
securityHandlers = new CopyOnWriteArraySet<>();
}
// add the specified set of security handlers
securityHandlers.addAll(handlers);
if (log.isDebugEnabled()) {
... |
java | private void monitorForChanges() {
if (monitorRunning) {
return;
}
final Path path;
try {
path = Paths.get(configPath);
} catch (final Exception e) {
LOGGER.warn("Cannot monitor configuration {}, disabling monitoring; {}", configPath, e.getMes... |
java | protected boolean processEntryEventFilter(EventFilter filter, Data dataKey) {
EntryEventFilter eventFilter = (EntryEventFilter) filter;
return eventFilter.eval(dataKey);
} |
python | def remove_writer(self, address):
""" Remove a writer address from the routing table, if present.
"""
log_debug("[#0000] C: <ROUTING> Removing writer %r", address)
self.routing_table.writers.discard(address)
log_debug("[#0000] C: <ROUTING> table=%r", self.routing_table) |
python | def _aprint2(self, *values, **kwargs):
"""
ANSI formatting-aware print().
This method is a version of print() (function) that understands
additional ansi control parameters.
:param value:
The values to print, same as with ``print()``
:param sep:
... |
java | public static List<NamespaceDto> transformToDto(List<Namespace> namespaces) {
if (namespaces == null) {
throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR);
}
List<NamespaceDto> result = new ArrayList<>();
... |
java | @Override
public List<CommerceDiscountRule> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} |
python | def pendulum_to_utc_datetime_without_tz(x: DateTime) -> datetime.datetime:
"""
Converts a Pendulum ``DateTime`` (which will have timezone information) to
a ``datetime.datetime`` that (a) has no timezone information, and (b) is
in UTC.
Example:
.. code-block:: python
import pendulum
... |
java | private void finshButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_finshButtonActionPerformed
if (parentGUI != null) {
parentGUI.setSourceDirecs(foundModel);
}
if (discover != null && discover.isAlive()) {
discover.stop();
}
dispos... |
java | public void encrypt(final String userName, final String password) {
encrypt(userName, password.getBytes(Charsets.UTF_8), MessageEncryption.NONE);
} |
java | public void addGridDetail()
{
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
m_panelGrid.setLayout(gridbag);
this.addGridDetailItems(this.getModel(), gridbag, c);
} |
python | def seek(self, offset, whence=os.SEEK_SET):
"""Seeks to an offset within the file-like object.
Args:
offset (int): offset to seek to.
whence (Optional(int)): value that indicates whether offset is an absolute
or relative position within the file.
Raises:
IOError: if the seek fa... |
python | def copy(src, dst, merge, write_v1=True, excluded_tags=None, verbose=False):
"""Returns 0 on success"""
if excluded_tags is None:
excluded_tags = []
try:
id3 = mutagen.id3.ID3(src, translate=False)
except mutagen.id3.ID3NoHeaderError:
print_(u"No ID3 header found in ", src, fil... |
java | public void updateNClob(final String columnLabel, final java.sql.NClob nClob) throws SQLException {
throw SQLExceptionMapper.getFeatureNotSupportedException("Updates are not supported");
} |
java | public VirtualMachineScaleSetInner createOrUpdate(String resourceGroupName, String vmScaleSetName, VirtualMachineScaleSetInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, parameters).toBlocking().last().body();
} |
java | public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case FULL_CLASS_NAME:
return is_set_full_class_name();
case ARGS_LIST:
return is_set_args_list();
}
throw new IllegalStateException();
} |
java | @Nonnull
public BugInstance addMethod(JavaClassAndMethod classAndMethod) {
return addMethod(classAndMethod.getJavaClass(), classAndMethod.getMethod());
} |
java | public ServiceFuture<HybridConnectionInner> getHybridConnectionAsync(String resourceGroupName, String name, String namespaceName, String relayName, final ServiceCallback<HybridConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(getHybridConnectionWithServiceResponseAsync(resourceGroupName, nam... |
java | public boolean meets( Object result )
{
Object expectedValue = canCoerceTo( result ) ? coerceTo( result ) : expected;
return ShouldBe.equal( expectedValue ).meets( result );
} |
python | def cached_method(func):
""" Memoize for class methods """
@functools.wraps(func)
def wrapper(self, *args):
if not hasattr(self, "_cache"):
self._cache = {}
key = _argstring((func.__name__,) + args)
if key not in self._cache:
self._cache[key] = func(self, *arg... |
java | @Override
public synchronized ManagedChannel shutdown() {
for (ManagedChannel channelWrapper : channels) {
channelWrapper.shutdown();
}
this.shutdown = true;
return this;
} |
java | public PagedList<FeatureResultInner> list1(final String resourceProviderNamespace) {
ServiceResponse<Page<FeatureResultInner>> response = list1SinglePageAsync(resourceProviderNamespace).toBlocking().single();
return new PagedList<FeatureResultInner>(response.body()) {
@Override
p... |
python | def to_dict(cls, acl):
""" transform an ACL to a dict """
return {
"perms": acl.perms,
"id": {
"scheme": acl.id.scheme,
"id": acl.id.id
}
} |
java | public static List<CommerceAccountOrganizationRel> findAll(int start,
int end,
OrderByComparator<CommerceAccountOrganizationRel> orderByComparator) {
return getPersistence().findAll(start, end, orderByComparator);
} |
python | def _resource_deletion(resource):
""" Recalculate consumption details and save resource details """
if resource.__class__ not in CostTrackingRegister.registered_resources:
return
new_configuration = {}
price_estimate = models.PriceEstimate.update_resource_estimate(resource, new_configuration)
... |
python | def set_light_state(self, hue, saturation, brightness, kelvin,
bulb=ALL_BULBS, timeout=None):
"""
Sets the light state of one or more bulbs.
Hue is a float from 0 to 360, saturation and brightness are floats from
0 to 1, and kelvin is an integer.
"""
... |
java | public String getKernelDefinition(BootstrapConfig bootProps) {
String kernelDef = bootProps.get(BOOTPROP_KERNEL);
if (kernelDef == null)
kernelDef = defaults.getProperty(MANIFEST_KERNEL);
if (kernelDef != null)
bootProps.put(BOOTPROP_KERNEL, kernelDef);
return ... |
java | @Override
public M getMonitor(L location) {
M monitor = getMonitorOnce(location);
// In case monitor was removed from manager, we retry
if (monitor == null) {
removeMonitorInformation(location);
monitor = getMonitorOnce(location);
}
return monitor;
} |
python | def incr(self, key, value, default=0, time=1000000):
"""
Increment a key, if it exists, returns its actual value, if it doesn't, return 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be incremented
:type value: int
:param default: D... |
python | def get_node_at_path(query_path, context):
"""Return the SqlNode associated with the query path."""
if query_path not in context.query_path_to_node:
raise AssertionError(
u'Unable to find SqlNode for query path {} with context {}.'.format(
query_path, context))
node = con... |
python | def login(self):
"""
This method performs the login on TheTVDB given the api key, user name and account identifier.
:return: None
"""
auth_data = dict()
auth_data['apikey'] = self.api_key
auth_data['username'] = self.username
auth_data['userkey'] = self.a... |
python | def predict(self, data):
"""
Predict a new data set based on an estimated model.
Parameters
----------
data : pandas.DataFrame
Data to use for prediction. Must contain all the columns
referenced by the right-hand side of the `model_expression`.
R... |
python | def pins(swlat, swlng, nelat, nelng, pintypes='stop', *, raw=False):
"""
DVB Map Pins
(GET https://www.dvb.de/apps/map/pins)
:param swlat: South-West Bounding Box Latitude
:param swlng: South-West Bounding Box Longitude
:param nelat: North-East Bounding Box Latitude
:param nelng: North-East... |
java | private static final int nextSpaceIndex(StringBuffer sb, int seek, int lastIndex) {
seek++;
char c;
while (seek < lastIndex) {
c = sb.charAt(seek);
if (c == ' ' || c == '\n') {
while (sb.length() > seek + 1 && sb.charAt(seek + 1) == ' ')
seek++;
return seek;
}
... |
java | public DescribeScalingPlansRequest withApplicationSources(ApplicationSource... applicationSources) {
if (this.applicationSources == null) {
setApplicationSources(new java.util.ArrayList<ApplicationSource>(applicationSources.length));
}
for (ApplicationSource ele : applicationSources)... |
python | def set_id(device, minor, system_id):
'''
Sets the system ID for the partition. Some typical values are::
b: FAT32 (vfat)
7: HPFS/NTFS
82: Linux Swap
83: Linux
8e: Linux LVM
fd: Linux RAID Auto
CLI Example:
.. code-block:: bash
salt '*' parti... |
python | def create(self, ex):
"helper for apply_sql in CreateX case"
if ex.name in self:
if ex.nexists: return
raise ValueError('table_exists',ex.name)
if any(c.pkey for c in ex.cols):
if ex.pkey:
raise sqparse2.SQLSyntaxError("don't mix table-level and column-level pkeys",ex)
... |
python | def create_design_matrix_2(Z, data, Y_len, lag_no):
"""
For Python 2.7 - cythonized version only works for 3.5
"""
row_count = 1
for lag in range(1, lag_no+1):
for reg in range(Y_len):
Z[row_count, :] = data[reg][(lag_no-lag):-lag]
row_count += 1
return Z |
java | private void repmatIncrement(TensorBase other, double multiplier) {
// Maps a key of other into a partial key of this.
int[] dimensionMapping = getDimensionMapping(other.getDimensionNumbers());
int[] partialKey = ArrayUtils.copyOf(getDimensionSizes(), getDimensionSizes().length);
for (int i = 0; i < dim... |
python | def ddspmt(t, peak_delay=6, under_delay=16, peak_disp=1, under_disp=1,
p_u_ratio=6):
""" SPM canonical HRF dispersion derivative, values for time values `t`
Parameters
----------
t : array-like
vector of times at which to sample HRF
Returns
-------
hrf : array
ve... |
java | private @CheckForNull
ValueNumber findValueKnownNonnullOnBranch(UnconditionalValueDerefSet fact, Edge edge) {
IsNullValueFrame invFrame = invDataflow.getResultFact(edge.getSource());
if (!invFrame.isValid()) {
return null;
}
IsNullConditionDecision decision = invFrame.ge... |
python | def run(self, *args):
"""Merge unique identities using a matching algorithm."""
params = self.parser.parse_args(args)
code = self.unify(params.matching, params.sources,
params.fast_matching, params.no_strict,
params.interactive, params.recove... |
java | static TarArchiveEntry defaultFileEntryWithName( final String fileName ) {
TarArchiveEntry entry = new TarArchiveEntry(fileName, true);
entry.setUserId(ROOT_UID);
entry.setUserName(ROOT_NAME);
entry.setGroupId(ROOT_UID);
entry.setGroupName(ROOT_NAME);
entry.setMode(TarArc... |
python | def main():
'''Main function.'''
usage = ('\n\n %prog [options] XML_PATH\n\nArguments:\n\n '
'XML_PATH the directory containing the '
'GermaNet .xml files')
parser = optparse.OptionParser(usage=usage)
parser.add_option('--host', default=None,
... |
python | def is_correct(self):
"""Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool
"""
state = True
# Inter... |
python | def should_reuse_driver(self, scope, test_passed, context=None):
"""Check if the driver should be reused
:param scope: execution scope (function, module, class or session)
:param test_passed: True if the test has passed
:param context: behave context
:returns: True if the driver... |
python | def bundle_lambda(zipfile):
"""Write zipfile contents to file.
:param zipfile:
:return: exit_code
"""
# TODO have 'bundle.zip' as default config
if not zipfile:
return 1
with open('bundle.zip', 'wb') as zfile:
zfile.write(zipfile)
log.info('Finished - a bundle.zip is wai... |
java | @Override
public CompletableFuture<Acknowledge> updateTaskExecutionState(
final TaskExecutionState taskExecutionState) {
checkNotNull(taskExecutionState, "taskExecutionState");
if (executionGraph.updateState(taskExecutionState)) {
return CompletableFuture.completedFuture(Acknowledge.get());
} else {
re... |
python | def select_contains(self, viewer, x, y):
"""For backward compatibility. TO BE DEPRECATED--DO NOT USE.
Use select_contains_pt() instead.
"""
return self.select_contains_pt(viewer, (x, y)) |
java | String readHTMLDocumentation(InputStream input, FileObject filename) throws IOException {
byte[] filecontents = new byte[input.available()];
try {
DataInputStream dataIn = new DataInputStream(input);
dataIn.readFully(filecontents);
} finally {
input.close();
... |
java | public Set<IPersonAttributesGroupDefinition> getPagsDefinitions(IPerson person) {
Set<IPersonAttributesGroupDefinition> rslt = new HashSet<>();
for (IPersonAttributesGroupDefinition def :
pagsGroupDefDao.getPersonAttributesGroupDefinitions()) {
if (hasPermission(
... |
java | @JsonIgnore
public String getIdentifier() {
String tags = "";
Map<String, String> sortedTags = new TreeMap<>();
sortedTags.putAll(getTags());
if(!sortedTags.isEmpty()) {
StringBuilder tagListBuffer = new StringBuilder("{");
for (String tagKey : sortedTags.keySet()) {
tagListBuffer.append(tagKey).ap... |
python | def write(self, data, debug_info=None):
"""
Write data to YHSM device.
"""
self.num_write_bytes += len(data)
if self.debug:
if not debug_info:
debug_info = str(len(data))
sys.stderr.write("%s: WRITE %s:\n%s\n" % (
self.__cla... |
python | def get_image_code(self, id_code, access_token=None, user_id=None):
"""
Get the image of a code, by its id
"""
if access_token:
self.req.credential.set_token(access_token)
if user_id:
self.req.credential.set_user_id(user_id)
if not self.check_crede... |
java | public File getAbsolutePath(String filename)
{
if (pathenv == null || pathSep == null || fileSep == null)
{
return null;
}
int val = -1;
String classvalue = pathenv + pathSep;
while (((val = classvalue.indexOf(pathSep)) >= 0) &&
classvalue.length() > 0) {
... |
python | def get_network_resource_property_entry(resource, prop):
""" Factory method for creating get functions. """
def get_func(cmd, resource_group_name, resource_name, item_name):
client = getattr(network_client_factory(cmd.cli_ctx), resource)
items = getattr(client.get(resource_group_name, resource_... |
java | public void toNotContainValue(final V value) {
expectNotNull(this.getValue(), "Expected null to not contain the value '%s'", value);
expectTrue(!this.getValue().containsValue(value), "Expected '%s' to not contain value '%s'", this.getValue(), value);
} |
python | def ui_iiif_image_url(obj, version='v2', region='full', size='full',
rotation=0, quality='default', image_format='png'):
"""Generate IIIF image URL from the UI application."""
return u'{prefix}{version}/{identifier}/{region}/{size}/{rotation}/' \
u'{quality}.{image_format}'.format(... |
python | def subcellular_locations(self):
"""Distinct subcellular locations (``location`` in :class:`.models.SubcellularLocation`)
:return: all distinct subcellular locations
:rtype: list[str]
"""
return [x[0] for x in self.session.query(models.SubcellularLocation.location).all()] |
python | def _init_middlewares(self):
"""Initialize hooks and middlewares
If you have another Middleware, like BrokeMiddleware for e.x
You can append this to middleware:
self.middleware.append(BrokeMiddleware())
"""
self.middleware = [DeserializeMiddleware()]
self.middlewa... |
java | public static int getButtonWidthHint(Button button) {
button.setFont(JFaceResources.getDialogFont());
PixelConverter converter= new PixelConverter(button);
int widthHint= converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAUL... |
java | public synchronized BaseBuffer move(int iRelPosition, FieldTable table) throws DBException
{
int iKeyOrder = table.getRecord().getDefaultOrder();
if (iKeyOrder == -1)
iKeyOrder = Constants.MAIN_KEY_AREA;
KeyAreaInfo keyArea = table.getRecord().getKeyArea(iKeyOrder);
PKeyA... |
python | def dump(obj, fp, **kwargs):
"""
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)
"""
return json.dump(obj, fp, cls=BioCJSONEncoder, **kwargs) |
python | def authenticate(self, is_global=True):
"""Authenticates against the API server.
:param is_global: If True, authenticate globally. Local login if False.
:raise AuthenticationException: Raises if there was an issue with authenticating or logging in.
:raise MyGeotabException: Raises when ... |
java | public static java.util.Set<String> all() {
java.util.Set<String> set = new java.util.HashSet<String>();
set.add(CLOUD_PLATFORM);
set.add(SERVICECONTROL);
return java.util.Collections.unmodifiableSet(set);
} |
python | def slot_remove_nio_binding(self, slot_number, port_number):
"""
Removes a slot NIO binding.
:param slot_number: slot number
:param port_number: port number
:returns: removed NIO instance
"""
try:
adapter = self._slots[slot_number]
except In... |
java | public void addError(String text, CSTNode context, SourceUnit source) throws CompilationFailedException {
addError(new LocatedMessage(text, context, source));
} |
python | def add_attempts(self, attempts):
"""stub"""
if attempts is None:
raise NullArgument('attempts cannot be None')
if not self.my_osid_object_form._is_valid_integer(
attempts, self.get_attempts_metadata()):
raise InvalidArgument('attempts')
self.my_os... |
python | def can_update_topics_to_announces(self, forum, user):
""" Given a forum, checks whether the user can change its topic types to announces. """
return (
self._perform_basic_permission_check(forum, user, 'can_edit_posts') and
self._perform_basic_permission_check(forum, user, 'can_p... |
java | public ResponseBuilder addAudioPlayerClearQueueDirective(ClearBehavior clearBehavior) {
ClearQueueDirective clearQueueDirective = ClearQueueDirective.builder()
.withClearBehavior(clearBehavior)
.build();
return addDirective(clearQueueDirective);
} |
python | def device_text_string_request(self):
"""Get FX Username.
Only required for devices that support FX Commands.
FX Addressee responds with an ED 0x0301 FX Username Response message.
"""
msg = StandardSend(self._address, COMMAND_FX_USERNAME_0X03_0X01)
self._send_msg(msg) |
java | public void setDistribution( final CharSequence distribution) {
if ( distribution != null) format.getHeader().createEntry( DISTRIBUTION, distribution);
} |
python | def emp_hessian(pars, x, y):
"""
Calculate the hessian matrix empirically.
Create a hessian matrix corresponding to the source model 'pars'
Only parameters that vary will contribute to the hessian.
Thus there will be a total of nvar x nvar entries, each of which is a
len(x) x len(y) array.
... |
java | @Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case XbasePackage.XVARIABLE_DECLARATION__TYPE:
setType((JvmTypeReference)newValue);
return;
case XbasePackage.XVARIABLE_DECLARATION__NAME:
setName((String)newValue);
return;
case XbasePackage.XVARIABLE_DECLA... |
python | def __save(self, b):
'''
saves the given data to the buffer
:param b:
'''
newbufferidx = (self.__bufferidx + len(b))
self.__buffer[self.__bufferidx:newbufferidx] = b
#update buffer index
self.__bufferidx = newbufferidx |
python | def _extract_docs_return(self):
"""Extract return description and type"""
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
self.docs['in']['return'] = self.dst.numpydoc.ge... |
java | public void showEmojiLayout() {
hideSoftInput(getContext(), this);
int keyboardHeight;
if (mCurrentContentHeight == 0) {
keyboardHeight = getDefaultEmojiHeight();
mCurrentContentHeight = mRawLayoutHeight - keyboardHeight;
} else {
keyboardHeight = mRaw... |
python | def compute_transitive_deps_by_target(self, targets):
"""Map from target to all the targets it depends on, transitively."""
# Sort from least to most dependent.
sorted_targets = reversed(sort_targets(targets))
transitive_deps_by_target = defaultdict(set)
# Iterate in dep order, to accumulate the tra... |
python | def set_branding(self, asset_ids):
"""Sets the branding.
arg: asset_ids (osid.id.Id[]): the new assets
raise: InvalidArgument - ``asset_ids`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``asset_ids`` is ``null``
*complia... |
java | public static byte[] encode(byte[] input, int inOffset, int inLen)
{
final byte[] output = new byte[((inLen + 2) / 3) * 4];
encode(input, inOffset, inLen, output, 0);
return output;
} |
java | @Override
public Request<DescribeFpgaImagesRequest> getDryRunRequest() {
Request<DescribeFpgaImagesRequest> request = new DescribeFpgaImagesRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;
} |
python | def get_accounts(self, fetch=False):
"""Return this Wallet's accounts object, populating it if fetch is True."""
return Accounts(self.resource.accounts, self.client, wallet=self, populate=fetch) |
java | public void setToBeginningWithNoEnd(final int numPartitions) {
if (numPartitions > MAX_PARTITIONS) {
throw new IllegalArgumentException("Can only hold " + MAX_PARTITIONS + " partitions, " + numPartitions
+ "supplied as initializer.");
}
for (int i = 0; i < numPartitions; i++) {
Partit... |
python | def _daily_suns(self, datetimes):
"""Get sun curve for multiple days of the year."""
for dt in datetimes:
# calculate sunrise sunset and noon
nss = self.calculate_sunrise_sunset(dt.month, dt.day)
dts = tuple(nss[k] for k in ('sunrise', 'noon', 'sunset'))
i... |
java | public void getSequence(int seq,
List<Attribute> nextAttrs, IntArrayList nextOfss, IntArrayList nextSeqs, AgBuffer cb) {
int i;
int max;
max = alternatives.size();
for (i = 0; i < max; i++) {
getSequence(alternatives.get(i), seq, nextAttrs, nextOf... |
python | def _timer(self, state_transition_event=None):
"""Timer loop used to keep track of the time while roasting or
cooling. If the time remaining reaches zero, the roaster will call the
supplied state transistion function or the roaster will be set to
the idle state."""
while not self... |
java | @Indexable(type = IndexableType.DELETE)
@Override
public CommerceNotificationTemplate deleteCommerceNotificationTemplate(
CommerceNotificationTemplate commerceNotificationTemplate)
throws PortalException {
return commerceNotificationTemplatePersistence.remove(commerceNotificationTemplate);
} |
python | def encompasses(self, span):
"""
Returns true if the given span fits inside this one
"""
if isinstance(span, list):
return [sp for sp in span if self._encompasses(sp)]
return self._encompasses(span) |
java | public static int getPixelFromDp(Context context, int dp) {
// Get the screen's density scale
float scale = context.getResources().getDisplayMetrics().density;
// Convert the dps to pixels, based on density scale
// because dp*scale is cast as an integer value, this will cause the result to be truncated.
/... |
python | def makedir(self, dir_name, mode=PERM_DEF):
"""Create a leaf Fake directory.
Args:
dir_name: (str) Name of directory to create.
Relative paths are assumed to be relative to '/'.
mode: (int) Mode to create directory with. This argument defaults
to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.