language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def render_secrets(
config_path,
secret_path,
):
"""combine a jinja template with a secret .ini file
Args:
config_path (str): path to .cfg file with jinja templating
secret_path (str): path to .ini-like secrets file
Returns:
ProsperConfig: rendered configuration object
"""
with open(secret_path, 'r') as s_fh:
secret_ini = anyconfig.load(s_fh, ac_parser='ini')
with open(config_path, 'r') as c_fh:
raw_cfg = c_fh.read()
rendered_cfg = anytemplate.renders(raw_cfg, secret_ini, at_engine='jinja2')
p_config = ProsperConfig(config_path)
local_config = configparser.ConfigParser()
local_config.optionxform = str
local_config.read_string(rendered_cfg)
p_config.local_config = local_config
return p_config |
java | public java.util.List<PublicIpv4PoolRange> getPoolAddressRanges() {
if (poolAddressRanges == null) {
poolAddressRanges = new com.amazonaws.internal.SdkInternalList<PublicIpv4PoolRange>();
}
return poolAddressRanges;
} |
java | public void removeDeleted(String entryId) {
CmsListItem item = getDeleted().getItem(entryId);
if (item != null) {
// remove
getDeleted().removeItem(item);
}
if (getDeleted().getWidgetCount() == 0) {
m_clipboardButton.enableClearDeleted(false);
}
} |
python | def load_movies(data_home, size):
"""Load movie genres as a context.
Returns:
dict of movie vectors: item_id -> numpy array (n_genre,)
"""
all_genres = ['Action',
'Adventure',
'Animation',
"Children's",
'Comedy',
'Crime',
'Documentary',
'Drama',
'Fantasy',
'Film-Noir',
'Horror',
'Musical',
'Mystery',
'Romance',
'Sci-Fi',
'Thriller',
'War',
'Western']
n_genre = len(all_genres)
movies = {}
if size == '100k':
with open(os.path.join(data_home, 'u.item'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('|'), f.readlines()))
for line in lines:
movie_vec = np.zeros(n_genre)
for i, flg_chr in enumerate(line[-n_genre:]):
if flg_chr == '1':
movie_vec[i] = 1.
movie_id = int(line[0])
movies[movie_id] = movie_vec
elif size == '1m':
with open(os.path.join(data_home, 'movies.dat'), encoding='ISO-8859-1') as f:
lines = list(map(lambda l: l.rstrip().split('::'), f.readlines()))
for item_id_str, title, genres in lines:
movie_vec = np.zeros(n_genre)
for genre in genres.split('|'):
i = all_genres.index(genre)
movie_vec[i] = 1.
item_id = int(item_id_str)
movies[item_id] = movie_vec
return movies |
python | def headers(headerDict={}, **headerskwargs):
'''
This function is the decorator which is used to wrap a Flask route with.
Either pass a dictionary of headers to be set as the headerDict keyword
argument, or pass header values as keyword arguments. Or, do both :-)
The key and value of items in a dictionary will be converted to strings using
the `str` method, ensure both keys and values are serializable thusly.
:param headerDict: A dictionary of headers to be injected into the response
headers. Note, the supplied dictionary is first copied then mutated.
:type origins: dict
:param headerskwargs: The headers to be injected into the response headers.
:type headerskwargs: identical to the `dict` constructor.
'''
_headerDict = headerDict.copy()
_headerDict.update(headerskwargs)
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
resp = make_response(f(*args, **kwargs))
h = resp.headers
for header, value in _headerDict.items():
h[str(header)] = str(value)
return resp
return decorated_function
return decorator |
java | @Contract(pure = false)
public String asString(@NotNull Charset charset) {
String string = getString(charset);
recycle();
return string;
} |
python | def style(self, style):
"""
Set val attribute of <w:pStyle> child element to *style*, adding a
new element if necessary. If *style* is |None|, remove the <w:pStyle>
element if present.
"""
if style is None:
self._remove_pStyle()
return
pStyle = self.get_or_add_pStyle()
pStyle.val = style |
python | def elements(self):
"""Return the BIC's Party Prefix, Country Code, Party Suffix and
Branch Code as a tuple."""
return (self.party_prefix, self.country_code, self.party_suffix,
self.branch_code) |
python | def GetMissingChunks(self, fd, length, offset):
"""Return which chunks a file doesn't have.
Specifically, we return a list of the chunks specified by a
length-offset range which are not in the datastore.
Args:
fd: The database object to read chunks from.
length: Length to read.
offset: File offset to read from.
Returns:
A list of chunk numbers.
"""
start_chunk = offset // fd.chunksize
end_chunk = (offset + length - 1) // fd.chunksize
relevant_chunks = range(start_chunk, end_chunk + 1)
missing_chunks = set(relevant_chunks)
for idx, metadata in iteritems(fd.ChunksMetadata(relevant_chunks)):
if not self.DataRefreshRequired(last=metadata.get("last", None)):
missing_chunks.remove(idx)
return sorted(missing_chunks) |
java | protected boolean doesParentMatch(final CSNodeWrapper parent, final CSNodeWrapper entityParent) {
if (parent != null && entityParent != null) {
if (parent.getId() != null && parent.getId().equals(entityParent.getId())) {
return true;
} else if (parent.getId() == null && entityParent.getId() == null && parent == entityParent) {
return true;
} else {
return false;
}
} else if (parent == null && entityParent == null) {
return true;
} else {
return false;
}
} |
java | private void addPostParams(final Request request) {
if (name != null) {
request.addPostParam("Name", name);
}
if (codeLength != null) {
request.addPostParam("CodeLength", codeLength.toString());
}
} |
java | static public FileSystemManager getManager(){
StandardFileSystemManager fsManager = new StandardFileSystemManager();
try {
fsManager.init();
} catch (FileSystemException e) {
log.error("Cannot initialize StandardFileSystemManager.", e);
}
return fsManager;
} |
python | def _validateIterCommonParams(MaxObjectCount, OperationTimeout):
"""
Validate common parameters for an iter... operation.
MaxObjectCount must be a positive non-zero integer or None.
OperationTimeout must be positive integer or zero
Raises:
ValueError: if these parameters are invalid
"""
if MaxObjectCount is None or MaxObjectCount <= 0:
raise ValueError(
_format("MaxObjectCount must be > 0 but is {0}", MaxObjectCount))
if OperationTimeout is not None and OperationTimeout < 0:
raise ValueError(
_format("OperationTimeout must be >= 0 but is {0}",
OperationTimeout)) |
java | public void removeRelationship(ExtendedRelation extendedRelation) {
try {
if (extendedRelationsDao.isTableExists()) {
geoPackage.deleteTable(extendedRelation.getMappingTableName());
extendedRelationsDao.delete(extendedRelation);
}
} catch (SQLException e) {
throw new GeoPackageException("Failed to remove relationship '"
+ extendedRelation.getRelationName() + "' between "
+ extendedRelation.getBaseTableName() + " and "
+ extendedRelation.getRelatedTableName()
+ " with mapping table "
+ extendedRelation.getMappingTableName(), e);
}
} |
java | public ActionListDialogBuilder addAction(final String label, final Runnable action) {
return addAction(new Runnable() {
@Override
public String toString() {
return label;
}
@Override
public void run() {
action.run();
}
});
} |
java | public PactDslJsonArray maxArrayLike(Integer size, PactDslJsonRootValue value, int numberExamples) {
if (numberExamples > size) {
throw new IllegalArgumentException(String.format("Number of example %d is more than the maximum size of %d",
numberExamples, size));
}
matchers.addRule(rootPath + appendArrayIndex(1), matchMax(size));
PactDslJsonArray parent = new PactDslJsonArray(rootPath, "", this, true);
parent.setNumberExamples(numberExamples);
parent.putObject(value);
return (PactDslJsonArray) parent.closeArray();
} |
python | def get_site_coordination_environments_fractions(self, site, isite=None, dequivsite=None, dthissite=None,
mysym=None, ordered=True, min_fraction=0.0, return_maps=True,
return_strategy_dict_info=False):
"""
Applies the strategy to the structure_environments object in order to define the coordination environment of
a given site.
:param site: Site for which the coordination environment is looked for
:return: The coordination environment of the site. For complex strategies, where one allows multiple
solutions, this can return a list of coordination environments for the site
"""
raise NotImplementedError() |
java | public ServiceFuture<ImagePrediction> predictImageWithNoStoreAsync(UUID projectId, byte[] imageData, PredictImageWithNoStoreOptionalParameter predictImageWithNoStoreOptionalParameter, final ServiceCallback<ImagePrediction> serviceCallback) {
return ServiceFuture.fromResponse(predictImageWithNoStoreWithServiceResponseAsync(projectId, imageData, predictImageWithNoStoreOptionalParameter), serviceCallback);
} |
python | def yank(self):
""" Yank back the most recently killed text.
"""
text = self._ring.yank()
if text:
self._skip_cursor = True
cursor = self._text_edit.textCursor()
cursor.insertText(text)
self._prev_yank = text |
java | public Set<PhysicalEntity> getNonUbiques(Set<PhysicalEntity> entities, RelType ctx)
{
Collection<SmallMolecule> ubiques = getUbiques(entities, ctx);
if (ubiques.isEmpty()) return entities;
Set<PhysicalEntity> result = new HashSet<PhysicalEntity>(entities);
result.removeAll(ubiques);
return result;
} |
java | public KeyOperationResult decrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) {
return decryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body();
} |
python | def logger(self) -> Logger:
"""A :class:`logging.Logger` logger for the app.
This can be used to log messages in a format as defined in the
app configuration, for example,
.. code-block:: python
app.logger.debug("Request method %s", request.method)
app.logger.error("Error, of some kind")
"""
if self._logger is None:
self._logger = create_logger(self)
return self._logger |
java | @Override
public DetectDocumentTextResult detectDocumentText(DetectDocumentTextRequest request) {
request = beforeClientExecution(request);
return executeDetectDocumentText(request);
} |
java | @Override
public boolean removeTrigger(final TriggerKey triggerKey) throws JobPersistenceException {
return doWithLock(new LockCallback<Boolean>() {
@Override
public Boolean doWithLock(JedisCommands jedis) throws JobPersistenceException {
try {
return storage.removeTrigger(triggerKey, jedis);
} catch (ClassNotFoundException e) {
throw new JobPersistenceException("Error removing trigger: " + e.getMessage(), e);
}
}
}, "Could not remove trigger.");
} |
java | public double[] getColumn(int column) {
column = getIndexFromMap(colMaskMap, column);
double[] values = new double[rows()];
for (int r = 0; r < rows(); ++r)
values[r] = matrix.get(getIndexFromMap(rowMaskMap, r), column);
return values;
} |
java | public static RawData escapeRegex(Object o) {
if (null == o) return RawData.NULL;
if (o instanceof RawData)
return (RawData) o;
String s = o.toString();
return new RawData(s.replaceAll("([\\/\\*\\{\\}\\<\\>\\-\\\\\\!])", "\\\\$1"));
} |
python | def identify_names(filename):
"""Builds a codeobj summary by identifying and resolving used names."""
node, _ = parse_source_file(filename)
if node is None:
return {}
# Get matches from the code (AST)
finder = NameFinder()
finder.visit(node)
names = list(finder.get_mapping())
names += extract_object_names_from_docs(filename)
example_code_obj = collections.OrderedDict()
for name, full_name in names:
if name in example_code_obj:
continue # if someone puts it in the docstring and code
# name is as written in file (e.g. np.asarray)
# full_name includes resolved import path (e.g. numpy.asarray)
splitted = full_name.rsplit('.', 1)
if len(splitted) == 1:
# module without attribute. This is not useful for
# backreferences
continue
module, attribute = splitted
# get shortened module name
module_short = get_short_module_name(module, attribute)
cobj = {'name': attribute, 'module': module,
'module_short': module_short}
example_code_obj[name] = cobj
return example_code_obj |
java | private void updateGridListDensity()
{
for (Map.Entry<DensityGrid, CharacteristicVector> grid : grid_list.entrySet())
{
DensityGrid dg = grid.getKey();
CharacteristicVector cvOfG = grid.getValue();
dg.setVisited(false);
cvOfG.updateGridDensity(this.getCurrTime(), this.getDecayFactor(), this.getDL(), this.getDM());
this.grid_list.put(dg, cvOfG);
}
} |
python | async def await_reply(self, correlation_id, timeout=None):
"""Wait for a reply to a given correlation id. If a timeout is
provided, it will raise a asyncio.TimeoutError.
"""
try:
result = await asyncio.wait_for(
self._futures[correlation_id], timeout=timeout)
return result
finally:
del self._futures[correlation_id] |
java | public void set(TafResp tafResp, Lur lur) {
principal = tafResp.getPrincipal();
access = tafResp.getAccess();
this.lur = lur;
} |
python | def patch_csi_node(self, name, body, **kwargs):
"""
partially update the specified CSINode
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_csi_node(name, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the CSINode (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. This field is required for apply requests (application/apply-patch) but optional for non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param bool force: Force is going to \"force\" Apply requests. It means user will re-acquire conflicting fields owned by other people. Force flag must be unset for non-apply patch requests.
:return: V1beta1CSINode
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_csi_node_with_http_info(name, body, **kwargs)
else:
(data) = self.patch_csi_node_with_http_info(name, body, **kwargs)
return data |
python | def json_2_team(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 Team object
"""
LOGGER.debug("Team.json_2_team")
return Team(teamid=json_obj['teamID'],
name=json_obj['teamName'],
description=json_obj['teamDescription'],
color_code=json_obj['teamColorCode'],
app_ids=json_obj['teamApplicationsID'],
osi_ids=json_obj['teamOSInstancesID']) |
python | def get_uri(dir_name):
"""
Returns the URI path for a directory. This allows files hosted on
different file servers to have distinct locations.
Args:
dir_name:
A directory name.
Returns:
Full URI path, e.g., fileserver.host.com:/full/path/of/dir_name.
"""
fullpath = os.path.abspath(dir_name)
try:
hostname = socket.gethostbyaddr(socket.gethostname())[0]
except:
hostname = socket.gethostname()
return "{}:{}".format(hostname, fullpath) |
python | def example_delete_topics(a, topics):
""" delete topics """
# Call delete_topics to asynchronously delete topics, a future is returned.
# By default this operation on the broker returns immediately while
# topics are deleted in the background. But here we give it some time (30s)
# to propagate in the cluster before returning.
#
# Returns a dict of <topic,future>.
fs = a.delete_topics(topics, operation_timeout=30)
# Wait for operation to finish.
for topic, f in fs.items():
try:
f.result() # The result itself is None
print("Topic {} deleted".format(topic))
except Exception as e:
print("Failed to delete topic {}: {}".format(topic, e)) |
python | def folder_name(self):
'''The name of the build folders containing this recipe.'''
name = self.site_packages_name
if name is None:
name = self.name
return name |
python | def load_repo_addons(_globals):
'''Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos
as git repositories.
Args:
_globals(dict): the globals() namespace of the fabric script.
Return: None
'''
repos_dir = os.path.expanduser('~/.fabsetup-addon-repos')
if os.path.isdir(repos_dir):
basedir, repos, _ = next(os.walk(repos_dir))
for repo_dir in [os.path.join(basedir, repo)
for repo in repos
# omit dot dirs like '.rope'
# or 'fabsetup-theno-termdown.disabled'
if '.' not in repo]:
sys.path.append(repo_dir)
package_name, username = package_username(repo_dir.split('/')[-1])
load_addon(username, package_name, _globals) |
java | public static void packEntries(File[] filesToPack, File destZipFile, NameMapper mapper, int compressionLevel) {
log.debug("Compressing '{}' into '{}'.", filesToPack, destZipFile);
ZipOutputStream out = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(destZipFile);
out = new ZipOutputStream(new BufferedOutputStream(fos));
out.setLevel(compressionLevel);
for (int i = 0; i < filesToPack.length; i++) {
File fileToPack = filesToPack[i];
ZipEntry zipEntry = ZipEntryUtil.fromFile(mapper.map(fileToPack.getName()), fileToPack);
out.putNextEntry(zipEntry);
FileUtils.copy(fileToPack, out);
out.closeEntry();
}
}
catch (IOException e) {
throw ZipExceptionUtil.rethrow(e);
}
finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(fos);
}
} |
java | public boolean deleteLedgerMetadata(EditLogLedgerMetadata ledger, int version)
throws IOException {
String ledgerPath = fullyQualifiedPathForLedger(ledger);
try {
zooKeeper.delete(ledgerPath, version);
return true;
} catch (KeeperException.NoNodeException e) {
LOG.warn(ledgerPath + " does not exist. Returning false, ignoring " +
e);
} catch (KeeperException.BadVersionException e) {
keeperException("Unable to delete " + ledgerPath + ", version does not match." +
" Updated by another process?", e);
} catch (KeeperException e) {
keeperException("Unrecoverable ZooKeeper error deleting " + ledgerPath,
e);
} catch (InterruptedException e) {
interruptedException("Interrupted deleting " + ledgerPath, e);
}
return false;
} |
python | def backup_watched(plex, opts):
""" Backup watched status to the specified filepath. """
data = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Fetching watched status for %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
if not opts.watchedonly or item.isWatched:
ikey = _item_key(item)
data[skey][ikey] = item.isWatched
import pprint; pprint.pprint(item.__dict__); break
print('Writing backup file to %s' % opts.filepath)
with open(opts.filepath, 'w') as handle:
json.dump(dict(data), handle, sort_keys=True, indent=2) |
java | public Coordinate snap(Coordinate coordinate, double distance) {
// Some initialization:
calculatedDistance = distance;
hasSnapped = false;
Coordinate snappingPoint = coordinate;
// Calculate the distances for all coordinate arrays:
for (Coordinate[] coordinateArray : coordinates) {
if (coordinateArray.length > 1) {
for (int j = 1; j < coordinateArray.length; j++) {
double d = MathService.distance(coordinateArray[j], coordinateArray[j - 1], coordinate);
if (d < calculatedDistance || (d == calculatedDistance && !hasSnapped)) {
snappingPoint = MathService.nearest(coordinateArray[j], coordinateArray[j - 1], coordinate);
calculatedDistance = d;
hasSnapped = true;
}
}
} else if (coordinateArray.length == 1) {
// In the case of Points, see if we can snap to them:
double d = MathService.distance(coordinateArray[0], coordinate);
if (d < calculatedDistance) {
snappingPoint = coordinateArray[0];
calculatedDistance = d;
hasSnapped = true;
}
}
}
return snappingPoint;
} |
java | @Override
public synchronized ChainData[] getAllChains(Class<?> factoryClass) throws InvalidChannelFactoryException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.entry(tc, "getAllChains(factory)");
}
if (null == factoryClass) {
throw new InvalidChannelFactoryException("Null factory class found");
}
String inputFactoryClassName = factoryClass.getName();
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "factory=" + inputFactoryClassName);
}
// Collect all chains referring to the channel
List<ChainData> chainDataList = new ArrayList<ChainData>();
ChannelData[] channels = null;
for (ChainData chainData : this.chainDataMap.values()) {
// Look at each channel associated with this chain.
channels = chainData.getChannelList();
for (int i = 0; i < channels.length; i++) {
if (channels[i].getFactoryType().getName().equals(inputFactoryClassName)) {
chainDataList.add(chainData);
}
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
Tr.exit(tc, "getAllChains");
}
return chainDataList.toArray(new ChainData[chainDataList.size()]);
} |
python | def truncate_to(self, cert):
"""
Remove all certificates in the path after the cert specified
:param cert:
An asn1crypto.x509.Certificate object to find
:raises:
LookupError - when the certificate could not be found
:return:
The current ValidationPath object, for chaining
"""
cert_index = None
for index, entry in enumerate(self):
if entry.issuer_serial == cert.issuer_serial:
cert_index = index
break
if cert_index is None:
raise LookupError('Unable to find the certificate specified')
while len(self) > cert_index + 1:
self.pop()
return self |
python | def inspect_obj(obj):
'''Learn what there is to be learned from our target.
Given an object at `obj`, which must be a function, method or
class, return a configuration *discovered* from the name of
the object and its parameter list. This function is
responsible for doing runtime reflection and providing
understandable failure modes.
The return value is a dictionary with three keys: ``name``,
``required`` and ``defaults``. ``name`` is the name of the
function/method/class. ``required`` is a list of parameters
*without* default values. ``defaults`` is a dictionary mapping
parameter names to default values. The sets of parameter names in
``required`` and ``defaults`` are disjoint.
When given a class, the parameters are taken from its ``__init__``
method.
Note that this function is purposefully conservative in the things
that is will auto-configure. All of the following things will result
in a :exc:`yakonfig.ProgrammerError` exception being raised:
1. A parameter list that contains tuple unpacking. (This is invalid
syntax in Python 3.)
2. A parameter list that contains variable arguments (``*args``) or
variable keyword words (``**kwargs``). This restriction forces
an auto-configurable to explicitly state all configuration.
Similarly, if given an object that isn't a function/method/class, a
:exc:`yakonfig.ProgrammerError` will be raised.
If reflection cannot be performed on ``obj``, then a ``TypeError``
is raised.
'''
skip_params = 0
if inspect.isfunction(obj):
name = obj.__name__
inspect_obj = obj
skip_params = 0
elif inspect.ismethod(obj):
name = obj.im_func.__name__
inspect_obj = obj
skip_params = 1 # self
elif inspect.isclass(obj):
inspect_obj = None
if hasattr(obj, '__dict__') and '__new__' in obj.__dict__:
inspect_obj = obj.__new__
elif hasattr(obj, '__init__'):
inspect_obj = obj.__init__
else:
raise ProgrammerError(
'Class "%s" does not have a "__new__" or "__init__" '
'method, so it cannot be auto configured.' % str(obj))
name = obj.__name__
if hasattr(obj, 'config_name'):
name = obj.config_name
if not inspect.ismethod(inspect_obj) \
and not inspect.isfunction(inspect_obj):
raise ProgrammerError(
'"%s.%s" is not a method/function (it is a "%s").'
% (str(obj), inspect_obj.__name__, type(inspect_obj)))
skip_params = 1 # self
else:
raise ProgrammerError(
'Expected a function, method or class to '
'automatically configure, but got a "%s" '
'(type: "%s").' % (repr(obj), type(obj)))
argspec = inspect.getargspec(inspect_obj)
if argspec.varargs is not None or argspec.keywords is not None:
raise ProgrammerError(
'The auto-configurable "%s" cannot contain '
'"*args" or "**kwargs" in its list of '
'parameters.' % repr(obj))
if not all(isinstance(arg, string_types) for arg in argspec.args):
raise ProgrammerError(
'Expected an auto-configurable with no nested '
'parameters, but "%s" seems to contain some '
'tuple unpacking: "%s"'
% (repr(obj), argspec.args))
defaults = argspec.defaults or []
# The index into `argspec.args` at which keyword arguments with default
# values starts.
i_defaults = len(argspec.args) - len(defaults)
return {
'name': name,
'required': argspec.args[skip_params:i_defaults],
'defaults': dict([(k, defaults[i])
for i, k in enumerate(argspec.args[i_defaults:])]),
} |
python | def getAttrWithFallback(info, attr):
"""
Get the value for *attr* from the *info* object.
If the object does not have the attribute or the value
for the atribute is None, this will either get a
value from a predefined set of attributes or it
will synthesize a value from the available data.
"""
if hasattr(info, attr) and getattr(info, attr) is not None:
value = getattr(info, attr)
else:
if attr in specialFallbacks:
value = specialFallbacks[attr](info)
else:
value = staticFallbackData[attr]
return value |
python | def alphanum_key(s):
"""Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [int(c) if c.isdigit() else c for c in _RE_INT.split(s)] |
java | @Indexable(type = IndexableType.REINDEX)
@Override
public CommerceWishList updateCommerceWishList(
CommerceWishList commerceWishList) {
return commerceWishListPersistence.update(commerceWishList);
} |
python | def display_event(div, attributes=[]):
"""
Function to build a suitable CustomJS to display the current event
in the div model.
"""
style = 'float: left; clear: left; font-size: 10pt'
return CustomJS(args=dict(div=div), code="""
var attrs = %s;
var args = [];
for (var i = 0; i<attrs.length; i++ ) {
var val = JSON.stringify(cb_obj[attrs[i]], function(key, val) {
return val.toFixed ? Number(val.toFixed(2)) : val;
})
args.push(attrs[i] + '=' + val)
}
var line = "<span style=%r><b>" + cb_obj.event_name + "</b>(" + args.join(", ") + ")</span>\\n";
var text = div.text.concat(line);
var lines = text.split("\\n")
if (lines.length > 35)
lines.shift();
div.text = lines.join("\\n");
""" % (attributes, style)) |
python | def _open_fix(file):
"""Takes in a fits file name, open the file in binary mode and creates an HDU.
Will attempt to fix some of the header keywords to match the standard FITS format.
"""
import pyfits, re, string
temp = pyfits.HDUList()
hdu = pyfits.PrimaryHDU()
hdu._file=open(file,'rb')
_number_RE = re.compile(
r'(?P<sign>[+-])?0*(?P<digt>(\.\d+|\d+(\.\d*)?)([deDE][+-]?\d+)?)')
### here's the real difference between pyFits and cfh12kFits.
### I'm more flexible on the format of the header file so that allows me
### read more files.
card_RE=re.compile(r"""
(?P<KEY>[-A-Z0-9_a-za ]{8}) ### keyword is the first 8 bytes... i'll allow small letters
(
(
(?P<VALUE>=\s) ### =\s indicats a value coming.
(\s*
(
(?P<STRING>\'[^\']*[\'/]) ### a string
|
(?P<FLOAT>([+-]?(\.\d+|\d+\.\d*)([dDEe][+-]?\d+)?)) ### a floating point number
|
(?P<INT>[+-]?\d+) ### an integer
|
(?P<BOOL>[TFtf]) ### perhaps value is boolian
)
\s*
(( / )?(?P<COMMENT>.*))? ### value related comment.
)
)
|
(?P<C2>.*) ### strickly a comment field
)
""",re.VERBOSE)
done=0
while ( not done):
### read a line of 80 characters up to a new line from the file.
block=hdu._file.readline(80)
string_end=79
if len(block)== 0:
done=1
continue
if block[-1]=='\n':
string_end=len(block)-2
line = re.match(r'[ -~]{0,'+str(string_end)+'}',block)
line = string.ljust(line.group(0),80)[0:79]
if line[0:8] == 'END ':
done=1
break
card=card_RE.match(line)
if not card or not card.group('KEY'):
print card.groups()
raise SyntaxError("Failed to get keyword from FITS Card %s" % line)
key=card.group('KEY')
value=None
if card.group('INT'):
try:
value=int(card.group('INT'))
except:
value=card.group('INT')
elif card.group('FLOAT'):
try:
value=float(card.group('FLOAT'))
except:
value=float(card.group('FLOAT'))
elif card.group('BOOL'):
value=pyfits.Boolean(card.group('BOOL'))
elif card.group('STRING'):
value=card.group('STRING')[1:-1]
if card.group('COMMENT'):
_comment=card.group('COMMENT')
elif card.group('C2'):
_comment=card.group('C2')
else:
_comment=None
try:
if key =='COMMENT ':
hdu.header.add_comment(_comment)
elif key =='HISTORY ':
hdu.header.add_history(_comment)
elif key ==' ':
hdu.header.add_blank(_comment)
elif key:
if key =='DATE-OBS' and value:
value=string.replace(value,'/','-')
hdu.header.update(key,value,comment=_comment)
except:
raise SyntaxError("Failed to convert line to FITS Card %s" % line)
### set some internal variables to decided on data flow.
hdu._bzero=hdu.header.get('BZERO',0)
hdu._bscale=hdu.header.get('BSCALE',1)
hdu._bitpix=hdu.header.get('BITPIX',-16)
if hdu.header.get('NAXIS',0)>0:
naxis1=hdu.header.get('NAXIS1',1)
naxis2=hdu.header.get('NAXIS2',1)
### now read the data... this is a HACK from pyfits.py
import numarray as num
code = pyfits._ImageBaseHDU.NumCode[hdu._bitpix]
dims = tuple([naxis2,naxis1])
raw_data = num.fromfile(hdu._file,type=code,shape=dims)
raw_data._byteorder='big'
if ( hdu._bzero != 0
or hdu._bscale!=1 ):
if hdu._bitpix > 0 :
hdu.data=num.array(raw_data,type=num.Float32)
else:
hdu.data=raw_data
if hdu._bscale != 1:
num.multiply(hdu.data,hdu._bscale,hdu.data)
if hdu._bzero!=0:
hdu.data=hdu.data + hdu._bzero
del hdu.header['BSCALE']
del hdu.header['BZERO']
hdu.header['BITPIX']=pyfits._ImageBaseHDU.ImgCode[hdu.data.type()]
temp.append(hdu)
return temp |
python | def get_groups(self, **kwargs):
"""Obtain line types and details.
Args:
lang (str): Language code (*es* or *en*).
Returns:
Status boolean and parsed response (list[GeoGroupItem]), or message
string in case of error.
"""
# Endpoint parameters
params = {
'cultureInfo': util.language_code(kwargs.get('lang'))
}
# Request
result = self.make_request('geo', 'get_groups', **params)
if not util.check_result(result):
return False, result.get('resultDescription', 'UNKNOWN ERROR')
# Parse
values = util.response_list(result, 'resultValues')
return True, [emtype.GeoGroupItem(**a) for a in values] |
java | public Chunk setRemoteGoto(String filename, int page) {
return setAttribute(REMOTEGOTO, new Object[] { filename, Integer.valueOf(page) });
} |
java | public void setData(byte[] data) {
// There are always two bytes of payload in the message -- the
// slave ID and the run status indicator.
if (data == null) {
m_length = 2;
m_data = new byte[0];
return;
}
if (data.length > 249) {
throw new IllegalArgumentException("data length limit exceeded");
}
m_length = data.length + 2;
m_data = new byte[data.length];
System.arraycopy(data, 0, m_data, 0, data.length);
} |
python | def until_not_synced(self, timeout=None):
"""Convenience method to wait (with Future) until client is not synced"""
not_synced_states = [state for state in self._state.valid_states
if state != 'synced']
not_synced_futures = [self._state.until_state(state)
for state in not_synced_states]
return until_any(*not_synced_futures, timeout=timeout) |
java | public List<SearchResult> search(String query) throws MovieMeterException {
String url = buildSearchUrl(query);
try {
return mapper.readValue(requestWebPage(url), new TypeReference<List<SearchResult>>() {
});
} catch (IOException ex) {
throw new MovieMeterException(ApiExceptionType.MAPPING_FAILED, "Failed to map search results", url, ex);
}
} |
java | public com.squareup.okhttp.Call getObjectAsync(String objectType, String dnType, List<String> dnGroups, String groupType, Integer limit, Integer offset, String searchTerm, String searchKey, String matchMethod, String sortKey, Boolean sortAscending, String sortMethod, String dbids, Boolean inUse, final ApiCallback<GetObjectsSuccessResponse> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = getObjectValidateBeforeCall(objectType, dnType, dnGroups, groupType, limit, offset, searchTerm, searchKey, matchMethod, sortKey, sortAscending, sortMethod, dbids, inUse, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<GetObjectsSuccessResponse>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} |
python | def modifyModlist(
old_entry: dict, new_entry: dict, ignore_attr_types: Optional[List[str]] = None,
ignore_oldexistent: bool = False) -> Dict[str, Tuple[str, List[bytes]]]:
"""
Build differential modify list for calling LDAPObject.modify()/modify_s()
:param old_entry:
Dictionary holding the old entry
:param new_entry:
Dictionary holding what the new entry should be
:param ignore_attr_types:
List of attribute type names to be ignored completely
:param ignore_oldexistent:
If true attribute type names which are in old_entry
but are not found in new_entry at all are not deleted.
This is handy for situations where your application
sets attribute value to '' for deleting an attribute.
In most cases leave zero.
:return: List of tuples suitable for
:py:meth:`ldap:ldap.LDAPObject.modify`.
This function is the same as :py:func:`ldap:ldap.modlist.modifyModlist`
except for the following changes:
* MOD_DELETE/MOD_DELETE used in preference to MOD_REPLACE when updating
an existing value.
"""
ignore_attr_types = _list_dict(map(str.lower, (ignore_attr_types or [])))
modlist: Dict[str, Tuple[str, List[bytes]]] = {}
attrtype_lower_map = {}
for a in old_entry.keys():
attrtype_lower_map[a.lower()] = a
for attrtype in new_entry.keys():
attrtype_lower = attrtype.lower()
if attrtype_lower in ignore_attr_types:
# This attribute type is ignored
continue
# Filter away null-strings
new_value = list(filter(lambda x: x is not None, new_entry[attrtype]))
if attrtype_lower in attrtype_lower_map:
old_value = old_entry.get(attrtype_lower_map[attrtype_lower], [])
old_value = list(filter(lambda x: x is not None, old_value))
del attrtype_lower_map[attrtype_lower]
else:
old_value = []
if not old_value and new_value:
# Add a new attribute to entry
modlist[attrtype] = (ldap3.MODIFY_ADD, escape_list(new_value))
elif old_value and new_value:
# Replace existing attribute
old_value_dict = _list_dict(old_value)
new_value_dict = _list_dict(new_value)
delete_values = []
for v in old_value:
if v not in new_value_dict:
delete_values.append(v)
add_values = []
for v in new_value:
if v not in old_value_dict:
add_values.append(v)
if len(delete_values) > 0 or len(add_values) > 0:
modlist[attrtype] = (
ldap3.MODIFY_REPLACE, escape_list(new_value))
elif old_value and not new_value:
# Completely delete an existing attribute
modlist[attrtype] = (ldap3.MODIFY_DELETE, [])
if not ignore_oldexistent:
# Remove all attributes of old_entry which are not present
# in new_entry at all
for a in attrtype_lower_map.keys():
if a in ignore_attr_types:
# This attribute type is ignored
continue
attrtype = attrtype_lower_map[a]
modlist[attrtype] = (ldap3.MODIFY_DELETE, [])
return modlist |
java | private UploadRequestProcessor getUploadRequestProcessor(TransferContext transferContext) {
LOGGER.entering(transferContext);
String contentType = transferContext.getHttpServletRequest().getContentType() != null ? transferContext
.getHttpServletRequest().getContentType().toLowerCase() : "unknown";
if (contentType.contains(AbstractUploadRequestProcessor.MULTIPART_CONTENT_TYPE)) {
// Return a Multipart request processor
UploadRequestProcessor uploadRequestProcessor = new MultipartUploadRequestProcessor(
transferContext);
LOGGER.exiting(uploadRequestProcessor);
return uploadRequestProcessor;
}
if (contentType.contains(AbstractUploadRequestProcessor.APPLICATION_URLENCODED_CONTENT_TYPE)) {
// Return normal Urlencoded request processor
UploadRequestProcessor uploadRequestProcessor = new ApplicationUploadRequestProcessor(
transferContext);
LOGGER.exiting(uploadRequestProcessor);
return uploadRequestProcessor;
}
throw new ArtifactUploadException("Content-Type should be either: "
+ AbstractUploadRequestProcessor.MULTIPART_CONTENT_TYPE + " or: "
+ AbstractUploadRequestProcessor.APPLICATION_URLENCODED_CONTENT_TYPE + " for file uploads");
} |
python | def bads_report(bads, path_prefix=None):
""" Return a nice report of bad architectures in `bads`
Parameters
----------
bads : set
set of length 2 or 3 tuples. A length 2 tuple is of form
``(depending_lib, missing_archs)`` meaning that an arch in
`require_archs` was missing from ``depending_lib``. A length 3 tuple
is of form ``(depended_lib, depending_lib, missing_archs)`` where
``depended_lib`` is the filename of the library depended on,
``depending_lib`` is the library depending on ``depending_lib`` and
``missing_archs`` is a set of missing architecture strings giving
architectures present in ``depending_lib`` and missing in
``depended_lib``. An empty set means all architectures were present as
required.
path_prefix : None or str, optional
Path prefix to strip from ``depended_lib`` and ``depending_lib``. None
means do not strip anything.
Returns
-------
report : str
A nice report for printing
"""
path_processor = ((lambda x : x) if path_prefix is None
else get_rp_stripper(path_prefix))
reports = []
for result in bads:
if len(result) == 3:
depended_lib, depending_lib, missing_archs = result
reports.append("{0} needs {1} {2} missing from {3}".format(
path_processor(depending_lib),
'archs' if len(missing_archs) > 1 else 'arch',
', '.join(sorted(missing_archs)),
path_processor(depended_lib)))
elif len(result) == 2:
depending_lib, missing_archs = result
reports.append("Required {0} {1} missing from {2}".format(
'archs' if len(missing_archs) > 1 else 'arch',
', '.join(sorted(missing_archs)),
path_processor(depending_lib)))
else:
raise ValueError('Report tuple should be length 2 or 3')
return '\n'.join(sorted(reports)) |
java | public void setDomainsAlwaysInScope(List<DomainAlwaysInScopeMatcher> domainsAlwaysInScope) {
if (domainsAlwaysInScope == null || domainsAlwaysInScope.isEmpty()) {
this.domainsAlwaysInScope = Collections.emptyList();
} else {
this.domainsAlwaysInScope = domainsAlwaysInScope;
}
} |
python | def send(self, sendspec):
"""Send string as a shell command, and wait until the expected output
is seen (either a string or any from a list of strings) before
returning. The expected string will default to the currently-set
default expected string (see get_default_shutit_pexpect_session_expect)
Returns the pexpect return value (ie which expected string in the list
matched)
@return: The pexpect return value (ie which expected
string in the list matched).
If return is -1, the task was backgrounded. See also multisend.
@rtype: int
"""
shutit = self.shutit
shutit.log('In session: ' + self.pexpect_session_id + ', trying to send: ' + str(sendspec.send), level=logging.DEBUG)
if self._check_blocked(sendspec):
shutit.log('In send for ' + str(sendspec.send) + ', check_blocked called and returned True.', level=logging.DEBUG)
# _check_blocked will add to the list of background tasks and handle dupes, so leave there.
return -1
shutit = self.shutit
cfg = shutit.cfg
# Set up what we expect.
sendspec.expect = sendspec.expect or self.default_expect
assert sendspec.send is not None, shutit_util.print_debug()
if sendspec.send.strip() == '':
sendspec.fail_on_empty_before=False
sendspec.check_exit=False
if isinstance(sendspec.expect, dict):
return self.multisend(ShutItSendSpec(self,
send=sendspec.send,
send_dict=sendspec.expect,
expect=shutit.get_default_shutit_pexpect_session_expect(),
timeout=sendspec.timeout,
check_exit=sendspec.check_exit,
fail_on_empty_before=sendspec.fail_on_empty_before,
record_command=sendspec.record_command,
exit_values=sendspec.exit_values,
echo=sendspec.echo,
note=sendspec.note,
secret=sendspec.secret,
check_sudo=sendspec.check_sudo,
nonewline=sendspec.nonewline,
loglevel=sendspec.loglevel))
# Before gathering expect, detect whether this is a sudo command and act accordingly.
command_list = sendspec.send.strip().split()
# If there is a first command, there is a sudo in there (we ignore
# whether it's quoted in the command), and we do not have sudo rights
# cached...
# TODO: check for sudo in pipelines, eg 'cmd | sudo' or 'cmd |sudo' but not 'echo " sudo "'
if sendspec.check_sudo and command_list and command_list[0] == 'sudo' and not self.check_sudo():
sudo_pass = self.get_sudo_pass_if_needed(shutit)
# Turn expect into a dict.
return self.multisend(ShutItSendSpec(self,
send=sendspec.send,
send_dict={'assword':[sudo_pass, True]},
expect=shutit.get_default_shutit_pexpect_session_expect(),
timeout=sendspec.timeout,
check_exit=sendspec.check_exit,
fail_on_empty_before=sendspec.fail_on_empty_before,
record_command=sendspec.record_command,
exit_values=sendspec.exit_values,
echo=sendspec.echo,
note=sendspec.note,
check_sudo=False,
nonewline=sendspec.nonewline,
loglevel=sendspec.loglevel))
shutit.handle_note(sendspec.note, command=str(sendspec.send), training_input=str(sendspec.send))
if sendspec.timeout is None:
sendspec.timeout = 3600
sendspec.echo = shutit.get_echo_override(sendspec.echo)
# Handle OSX to get the GNU version of the command
if sendspec.assume_gnu:
sendspec.send = shutit.get_send_command(sendspec.send)
# If check_exit is not passed in
# - if the expect matches the default, use the default check exit
# - otherwise, default to doing the check
if sendspec.check_exit is None:
# If we are in video mode, ignore exit value
if (shutit.build['video'] != -1 or shutit.build['video'] is True) or shutit.build['training'] or shutit.build['walkthrough'] or shutit.build['exam']:
sendspec.check_exit = False
elif sendspec.expect == shutit.get_default_shutit_pexpect_session_expect():
sendspec.check_exit = shutit.get_default_shutit_pexpect_session_check_exit()
else:
# If expect given doesn't match the defaults and no argument
# was passed in (ie check_exit was passed in as None), set
# check_exit to true iff it matches a prompt.
expect_matches_prompt = False
for prompt in shutit.expect_prompts:
if prompt == sendspec.expect:
expect_matches_prompt = True
if not expect_matches_prompt:
sendspec.check_exit = False
else:
sendspec.check_exit = True
# Determine whether we record this command.
ok_to_record = False
if not sendspec.echo and sendspec.record_command is None:
sendspec.record_command = False
if sendspec.record_command is None or sendspec.record_command:
ok_to_record = True
for i in cfg.keys():
if isinstance(cfg[i], dict):
for j in cfg[i].keys():
if (j == 'password' or j == 'passphrase') and cfg[i][j] == sendspec.send:
shutit.build['shutit_command_history'].append ('#redacted command, password')
ok_to_record = False
break
if not ok_to_record or sendspec.send in shutit_global.shutit_global_object.secret_words_set:
sendspec.secret = True
break
if ok_to_record:
shutit.build['shutit_command_history'].append(sendspec.send)
# Log - tho not if secret.
if sendspec.send != None:
shutit.log('================================================================================', level=logging.DEBUG)
send_and_expect_summary_msg = ''
if not sendspec.echo and not sendspec.secret:
send_and_expect_summary_msg += 'Sending: ' + sendspec.send
elif not sendspec.echo and sendspec.secret:
send_and_expect_summary_msg += 'Sending: ' + sendspec.send
if not sendspec.secret:
send_and_expect_summary_msg += 'Sending>>>' + sendspec.send + '<<<'
else:
send_and_expect_summary_msg += 'Sending>>>[SECRET]<<<'
send_and_expect_summary_msg += ', expecting>>>' + str(sendspec.expect) + '<<<'
shutit.log(send_and_expect_summary_msg, level=logging.DEBUG)
while sendspec.retry > 0:
if sendspec.escape:
escaped_str = "eval $'"
_count = 7
for char in sendspec.send:
if char in string.ascii_letters:
escaped_str += char
_count += 1
else:
escaped_str += shutit_util.get_wide_hex(char)
_count += 4
if _count > shutit_global.shutit_global_object.line_limit:
# The newline here is deliberate!
escaped_str += r"""'\
$'"""
_count = 0
escaped_str += "'"
if sendspec.secret:
shutit.log('The string was sent safely.', level=logging.DEBUG)
else:
shutit.log('This string was sent safely: ' + sendspec.send, level=logging.DEBUG)
string_to_send = escaped_str
else:
string_to_send = sendspec.send
if string_to_send is not None:
if len(string_to_send) > shutit_global.shutit_global_object.line_limit:
fname = self._create_command_file(sendspec.expect,string_to_send)
res = self.send(ShutItSendSpec(self,
send=' command source ' + fname,
expect=sendspec.expect,
timeout=sendspec.timeout,
check_exit=sendspec.check_exit,
fail_on_empty_before=False,
record_command=False,
exit_values=sendspec.exit_values,
echo=False,
escape=False,
retry=sendspec.retry,
loglevel=sendspec.loglevel,
follow_on_commands=sendspec.follow_on_commands,
delaybeforesend=sendspec.delaybeforesend,
nonewline=sendspec.nonewline,
run_in_background=sendspec.run_in_background,
ignore_background=True,
block_other_commands=sendspec.block_other_commands))
if not self.sendline(ShutItSendSpec(self,
send=' rm -f ' + fname,
nonewline=sendspec.nonewline,
run_in_background=sendspec.run_in_background,
echo=False,
ignore_background=True)):
self.expect(sendspec.expect,
searchwindowsize=sendspec.searchwindowsize,
maxread=sendspec.maxread)
# Before returning, determine whether we are now in a shell by comparing the expect we have with the originally-created 'shell_expect'.
self.in_shell = sendspec.expect == self.shell_expect
return res
else:
if sendspec.echo:
shutit.divert_output(sys.stdout)
if not self.sendline(sendspec):
expect_res = shutit.expect_allow_interrupt(self.pexpect_child, sendspec.expect, sendspec.timeout)
else:
expect_res = -1
if sendspec.echo:
shutit.divert_output(None)
else:
expect_res = shutit.expect_allow_interrupt(self.pexpect_child, sendspec.expect, sendspec.timeout)
if isinstance(self.pexpect_child.after, type) or isinstance(self.pexpect_child.before, type):
shutit.log('End of pexpect session detected, bailing.', level=logging.CRITICAL)
shutit_global.shutit_global_object.handle_exit(exit_code=1)
# Massage the output for summary sending.
logged_output = ''.join((self.pexpect_child.before + str(self.pexpect_child.after)).split('\n')).replace(sendspec.send,'',1).replace('\r','')[:160] + ' [...]'
if not sendspec.secret:
if not sendspec.echo:
shutit.log('Output (squashed): ' + logged_output, level=logging.DEBUG)
if shutit_global.shutit_global_object.ispy3:
shutit.log('pexpect: buffer: ' + str(base64.b64encode(bytes(self.pexpect_child.buffer,shutit_global.shutit_global_object.default_encoding))) + ' before: ' + str(base64.b64encode(bytes(self.pexpect_child.before,shutit_global.shutit_global_object.default_encoding))) + ' after: ' + str(base64.b64encode(bytes(self.pexpect_child.after,shutit_global.shutit_global_object.default_encoding))), level=logging.DEBUG)
else:
shutit.log('pexpect: buffer: ' + base64.b64encode(self.pexpect_child.buffer) + ' before: ' + base64.b64encode(self.pexpect_child.before) + ' after: ' + base64.b64encode(self.pexpect_child.after), level=logging.DEBUG)
else:
shutit.log('[Send was marked secret; getting output debug will require code change]', level=logging.DEBUG)
if sendspec.fail_on_empty_before:
if self.pexpect_child.before.strip() == '':
shutit.fail('before empty after sending: ' + str(sendspec.send) + '\n\nThis is expected after some commands that take a password.\nIf so, add fail_on_empty_before=False to the send call.\n\nIf that is not the problem, did you send an empty string to a prompt by mistake?', shutit_pexpect_child=self.pexpect_child) # pragma: no cover
else:
# Don't check exit if fail_on_empty_before is False
sendspec.check_exit = False
for prompt in shutit.expect_prompts:
if prompt == sendspec.expect:
# Reset prompt
self.setup_prompt('reset_tmp_prompt')
self.revert_prompt('reset_tmp_prompt', sendspec.expect)
break
# Last output - remove the first line, as it is the previous command.
# Get this before we check exit.
last_output = '\n'.join(self.pexpect_child.before.split('\n')[1:])
if sendspec.check_exit:
# store the output
if not self.check_last_exit_values(sendspec.send,
check_exit=sendspec.check_exit,
expect=sendspec.expect,
exit_values=sendspec.exit_values,
retry=sendspec.retry):
if not sendspec.secret:
shutit.log('Sending: ' + sendspec.send + ' : failed, retrying', level=logging.DEBUG)
else:
shutit.log('Send failed, retrying', level=logging.DEBUG)
sendspec.retry -= 1
assert sendspec.retry > 0, shutit_util.print_debug()
continue
break
# check self.pexpect_child.before for matches for follow-on commands
if sendspec.follow_on_commands is not None:
for match in sendspec.follow_on_commands:
sendspec.send = sendspec.follow_on_commands[match]
if shutit.match_string(last_output, match):
# send (with no follow-on commands)
self.send(ShutItSendSpec(self,
send=sendspec.send,
expect=sendspec.expect,
timeout=sendspec.timeout,
check_exit=sendspec.check_exit,
fail_on_empty_before=False,
record_command=sendspec.record_command,
exit_values=sendspec.exit_values,
echo=sendspec.echo,
escape=sendspec.escape,
retry=sendspec.retry,
loglevel=sendspec.loglevel,
delaybeforesend=sendspec.delaybeforesend,
run_in_background=False,
ignore_background=True,
block_other_commands=sendspec.block_other_commands))
if shutit.build['step_through']:
self.pause_point('pause point: stepping through')
if shutit.build['ctrlc_stop']:
shutit.build['ctrlc_stop'] = False
self.pause_point('pause point: interrupted by CTRL-c')
shutit.handle_note_after(note=sendspec.note, training_input=str(sendspec.send))
# Before returning, determine whether we are now in a shell by comparing the expect we have with the originally-created 'shell_expect'.
self.in_shell = sendspec.expect == self.shell_expect
return expect_res |
python | def GroupBy(self: Iterable, f=None):
"""
[
{
'self': [1, 2, 3],
'f': lambda x: x%2,
'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3]
}
]
"""
if f and is_to_destruct(f):
f = destruct_func(f)
return _group_by(self, f) |
python | def asin(x, context=None):
"""
Return the inverse sine of ``x``.
The mathematically exact result lies in the range [-π/2, π/2]. However,
note that as a result of rounding to the current context, it's possible
for the actual value to lie just outside this range.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_asin,
(BigFloat._implicit_convert(x),),
context,
) |
python | def validate(self, value):
"""Validates that `value` can be assigned to this Property.
Parameters:
value: The value to validate.
Raises:
TypeError: If the type of the assigned value is invalid.
Returns:
The value that should be assigned to the entity.
"""
if isinstance(value, self._types):
return value
elif self.optional and value is None:
return [] if self.repeated else None
elif self.repeated and isinstance(value, (tuple, list)) and all(isinstance(x, self._types) for x in value):
return value
else:
raise TypeError(f"Value of type {classname(value)} assigned to {classname(self)} property.") |
java | @Nonnull
public static ACLContext as(@Nonnull Authentication auth) {
final ACLContext context = new ACLContext(SecurityContextHolder.getContext());
SecurityContextHolder.setContext(new NonSerializableSecurityContext(auth));
return context;
} |
python | def theano_compiler(model):
"""Take a triflow model and return optimized theano routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(theano function, theano_function):
Optimized routine that compute the evolution equations and their
jacobian matrix.
"""
from theano import tensor as T
from theano.ifelse import ifelse
import theano.sparse as ths
from theano import function
def th_Min(a, b):
if isinstance(a, T.TensorVariable) or isinstance(b, T.TensorVariable):
return T.where(a < b, a, b)
return min(a, b)
def th_Max(a, b):
if isinstance(a, T.TensorVariable) or isinstance(b, T.TensorVariable):
return T.where(a < b, b, a)
return max(a, b)
def th_Heaviside(a):
if isinstance(a, T.TensorVariable):
return T.where(a < 0, 1, 1)
return 0 if a < 0 else 1
mapargs = {arg: T.vector(arg)
for arg, sarg
in zip(model._args, model._symbolic_args)}
to_feed = mapargs.copy()
x_th = mapargs['x']
N = x_th.size
L = x_th[-1] - x_th[0]
dx = L / (N - 1)
to_feed['dx'] = dx
periodic = T.scalar("periodic", dtype="int32")
middle_point = int((model._window_range - 1) / 2)
th_args = [mapargs[key]
for key
in [*model._indep_vars,
*model._dep_vars,
*model._help_funcs,
*model._pars]] + [periodic]
map_extended = {}
for (varname, discretisation_tree) in \
model._symb_vars_with_spatial_diff_order.items():
pad_left, pad_right = model._bounds
th_arg = mapargs[varname]
per_extended_var = T.concatenate([th_arg[pad_left:],
th_arg,
th_arg[:pad_right]])
edge_extended_var = T.concatenate([[th_arg[0]] * middle_point,
th_arg,
[th_arg[-1]] * middle_point])
extended_var = ifelse(periodic,
per_extended_var,
edge_extended_var)
map_extended[varname] = extended_var
for order in range(pad_left, pad_right + 1):
if order != 0:
var = ("{}_{}{}").format(varname,
'm' if order < 0 else 'p',
np.abs(order))
else:
var = varname
new_var = extended_var[order - pad_left:
extended_var.size +
order - pad_right]
to_feed[var] = new_var
F = lambdify((model._symbolic_args),
expr=model.F_array.tolist(),
modules=[T, {"Max": th_Max,
"Min": th_Min,
"Heaviside": th_Heaviside}])(
*[to_feed[key]
for key
in model._args]
)
F = T.concatenate(F, axis=0).reshape((model._nvar, N)).T
F = T.stack(F).flatten()
J = lambdify((model._symbolic_args),
expr=model.J_array.tolist(),
modules=[T, {"Max": th_Max,
"Min": th_Min,
"Heaviside": th_Heaviside}])(
*[to_feed[key]
for key
in model._args]
)
J = [j if j != 0 else T.constant(0.)
for j in J]
J = [j if not isinstance(j, (int, float)) else T.constant(j)
for j in J]
J = T.stack([T.repeat(j, N) if j.ndim == 0 else j
for j in J])
J = J[model._sparse_indices[0]].T.squeeze()
i = T.arange(N).dimshuffle([0, 'x'])
idx = T.arange(N * model._nvar).reshape((N, model._nvar)).T
edge_extended_idx = T.concatenate([T.repeat(idx[:, :1],
middle_point,
axis=1),
idx,
T.repeat(idx[:, -1:],
middle_point,
axis=1)],
axis=1).T.flatten()
per_extended_idx = T.concatenate([idx[:, -middle_point:],
idx,
idx[:, :middle_point]],
axis=1).T.flatten()
extended_idx = ifelse(periodic,
per_extended_idx,
edge_extended_idx)
rows = T.tile(T.arange(model._nvar),
model._window_range * model._nvar) + i * model._nvar
cols = T.repeat(T.arange(model._window_range * model._nvar),
model._nvar) + i * model._nvar
rows = rows[:, model._sparse_indices].reshape(J.shape).flatten()
cols = extended_idx[cols][:, model._sparse_indices] \
.reshape(J.shape).flatten()
permutation = T.argsort(cols)
J = J.flatten()[permutation]
rows = rows[permutation]
cols = cols[permutation]
count = T.zeros((N * model._nvar + 1,), dtype=int)
uq, cnt = T.extra_ops.Unique(False, False, True)(cols)
count = T.set_subtensor(count[uq + 1], cnt)
indptr = T.cumsum(count)
shape = T.stack([N * model._nvar, N * model._nvar])
sparse_J = ths.CSC(J, rows, indptr, shape)
F_theano_function = function(inputs=th_args,
outputs=F,
on_unused_input='ignore',
allow_input_downcast=True)
J_theano_function = function(inputs=th_args,
outputs=sparse_J,
on_unused_input='ignore',
allow_input_downcast=True)
return F_theano_function, J_theano_function |
java | private FetchPath getPathProperties(JsonGenerator jsonGenerator) {
FetchPath fetchPath = EbeanUtils.getRequestFetchPath();
if (fetchPath != null) {
JsonStreamContext context = jsonGenerator.getOutputContext();
JsonStreamContext parent = context.getParent();
if (parent == null) {
return fetchPath;
}
StringBuilder path = new StringBuilder();
while (parent != null && !parent.inRoot()) {
if (parent != context.getParent()) {
path.insert(0, '.');
}
path.insert(0, parent.getCurrentName());
parent = parent.getParent();
}
String fp = path.toString();
PathProperties fetch = new PathProperties();
EbeanPathProps src = (EbeanPathProps) fetchPath;
String cp = fp + ".";
for (BeanPathProperties.Props prop : src.getPathProps()) {
String pp = prop.getPath();
if (pp != null) {
if (pp.equals(fp)) {
addToFetchPath(fetch, null, prop);
} else if (pp.startsWith(cp)) {
addToFetchPath(fetch, pp.substring(cp.length()), prop);
}
}
}
return fetch;
}
return null;
} |
java | public <K> JavaPairRDD<K, INDArray> feedForwardWithMaskAndKey(JavaPairRDD<K, Tuple2<INDArray,INDArray>> featuresDataAndMask, int batchSize) {
return featuresDataAndMask
.mapPartitionsToPair(new FeedForwardWithKeyFunction<K>(sc.broadcast(network.params()),
sc.broadcast(conf.toJson()), batchSize));
} |
python | def cluster_add_slots(self, slot, *slots):
"""Assign new hash slots to receiving node."""
slots = (slot,) + slots
if not all(isinstance(s, int) for s in slots):
raise TypeError("All parameters must be of type int")
fut = self.execute(b'CLUSTER', b'ADDSLOTS', *slots)
return wait_ok(fut) |
java | public static TBSCertificateStructure getTBSCertificateStructure(
X509Certificate cert)
throws CertificateEncodingException, IOException {
ASN1Primitive obj = toASN1Primitive(cert.getTBSCertificate());
return TBSCertificateStructure.getInstance(obj);
} |
python | def processPointOfSalePayment(request):
'''
This view handles the callbacks from point-of-sale transactions.
Please note that this will only work if you have set up your callback
URL in Square to point to this view.
'''
print('Request data is: %s' % request.GET)
# iOS transactions put all response information in the data key:
data = json.loads(request.GET.get('data','{}'))
if data:
status = data.get('status')
errorCode = data.get('error_code')
errorDescription = errorCode
try:
stateData = data.get('state','')
if stateData:
metadata = json.loads(b64decode(unquote(stateData).encode()).decode())
else:
metadata = {}
except (TypeError, ValueError, binascii.Error):
logger.error('Invalid metadata passed from Square app.')
messages.error(
request,
format_html(
'<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
str(_('ERROR: Error with Square point of sale transaction attempt.')),
str(_('Invalid metadata passed from Square app.')),
)
)
return HttpResponseRedirect(reverse('showRegSummary'))
# This is the normal transaction identifier, which will be stored in the
# database as a SquarePaymentRecord
serverTransId = data.get('transaction_id')
# This is the only identifier passed for non-card transactions.
clientTransId = data.get('client_transaction_id')
else:
# Android transactions use this GET response syntax
errorCode = request.GET.get('com.squareup.pos.ERROR_CODE')
errorDescription = request.GET.get('com.squareup.pos.ERROR_DESCRIPTION')
status = 'ok' if not errorCode else 'error'
# This is the normal transaction identifier, which will be stored in the
# database as a SquarePaymentRecord
serverTransId = request.GET.get('com.squareup.pos.SERVER_TRANSACTION_ID')
# This is the only identifier passed for non-card transactions.
clientTransId = request.GET.get('com.squareup.pos.CLIENT_TRANSACTION_ID')
# Load the metadata, which includes the registration or invoice ids
try:
stateData = request.GET.get('com.squareup.pos.REQUEST_METADATA','')
if stateData:
metadata = json.loads(b64decode(unquote(stateData).encode()).decode())
else:
metadata = {}
except (TypeError, ValueError, binascii.Error):
logger.error('Invalid metadata passed from Square app.')
messages.error(
request,
format_html(
'<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
str(_('ERROR: Error with Square point of sale transaction attempt.')),
str(_('Invalid metadata passed from Square app.')),
)
)
return HttpResponseRedirect(reverse('showRegSummary'))
# Other things that can be passed in the metadata
sourceUrl = metadata.get('sourceUrl',reverse('showRegSummary'))
successUrl = metadata.get('successUrl',reverse('registration'))
submissionUserId = metadata.get('userId', getattr(getattr(request,'user',None),'id',None))
transactionType = metadata.get('transaction_type')
taxable = metadata.get('taxable', False)
addSessionInfo = metadata.get('addSessionInfo',False)
customerEmail = metadata.get('customerEmail')
if errorCode or status != 'ok':
# Return the user to their original page with the error message displayed.
logger.error('Error with Square point of sale transaction attempt. CODE: %s; DESCRIPTION: %s' % (errorCode, errorDescription))
messages.error(
request,
format_html(
'<p>{}</p><ul><li><strong>CODE:</strong> {}</li><li><strong>DESCRIPTION:</strong> {}</li></ul>',
str(_('ERROR: Error with Square point of sale transaction attempt.')), errorCode, errorDescription
)
)
return HttpResponseRedirect(sourceUrl)
api_instance = TransactionsApi()
api_instance.api_client.configuration.access_token = getattr(settings,'SQUARE_ACCESS_TOKEN','')
location_id = getattr(settings,'SQUARE_LOCATION_ID','')
if serverTransId:
try:
api_response = api_instance.retrieve_transaction(transaction_id=serverTransId,location_id=location_id)
except ApiException:
logger.error('Unable to find Square transaction by server ID.')
messages.error(request,_('ERROR: Unable to find Square transaction by server ID.'))
return HttpResponseRedirect(sourceUrl)
if api_response.errors:
logger.error('Unable to find Square transaction by server ID: %s' % api_response.errors)
messages.error(request,str(_('ERROR: Unable to find Square transaction by server ID:')) + api_response.errors)
return HttpResponseRedirect(sourceUrl)
transaction = api_response.transaction
elif clientTransId:
# Try to find the transaction in the 50 most recent transactions
try:
api_response = api_instance.list_transactions(location_id=location_id)
except ApiException:
logger.error('Unable to find Square transaction by client ID.')
messages.error(request,_('ERROR: Unable to find Square transaction by client ID.'))
return HttpResponseRedirect(sourceUrl)
if api_response.errors:
logger.error('Unable to find Square transaction by client ID: %s' % api_response.errors)
messages.error(request,str(_('ERROR: Unable to find Square transaction by client ID:')) + api_response.errors)
return HttpResponseRedirect(sourceUrl)
transactions_list = [x for x in api_response.transactions if x.client_id == clientTransId]
if len(transactions_list) == 1:
transaction = transactions_list[0]
else:
logger.error('Returned client transaction ID not found.')
messages.error(request,_('ERROR: Returned client transaction ID not found.'))
return HttpResponseRedirect(sourceUrl)
else:
logger.error('An unknown error has occurred with Square point of sale transaction attempt.')
messages.error(request,_('ERROR: An unknown error has occurred with Square point of sale transaction attempt.'))
return HttpResponseRedirect(sourceUrl)
# Get total information from the transaction for handling invoice.
this_total = sum([x.amount_money.amount / 100 for x in transaction.tenders or []]) - \
sum([x.amount_money.amount / 100 for x in transaction.refunds or []])
# Parse if a specific submission user is indicated
submissionUser = None
if submissionUserId:
try:
submissionUser = User.objects.get(id=int(submissionUserId))
except (ValueError, ObjectDoesNotExist):
logger.warning('Invalid user passed, submissionUser will not be recorded.')
if 'registration' in metadata.keys():
try:
tr_id = int(metadata.get('registration'))
tr = TemporaryRegistration.objects.get(id=tr_id)
except (ValueError, TypeError, ObjectDoesNotExist):
logger.error('Invalid registration ID passed: %s' % metadata.get('registration'))
messages.error(
request,
str(_('ERROR: Invalid registration ID passed')) + ': %s' % metadata.get('registration')
)
return HttpResponseRedirect(sourceUrl)
tr.expirationDate = timezone.now() + timedelta(minutes=getConstant('registration__sessionExpiryMinutes'))
tr.save()
this_invoice = Invoice.get_or_create_from_registration(tr, submissionUser=submissionUser)
this_description = _('Registration Payment: #%s' % tr_id)
elif 'invoice' in metadata.keys():
try:
this_invoice = Invoice.objects.get(id=int(metadata.get('invoice')))
this_description = _('Invoice Payment: %s' % this_invoice.id)
except (ValueError, TypeError, ObjectDoesNotExist):
logger.error('Invalid invoice ID passed: %s' % metadata.get('invoice'))
messages.error(
request,
str(_('ERROR: Invalid invoice ID passed')) + ': %s' % metadata.get('invoice')
)
return HttpResponseRedirect(sourceUrl)
else:
# Gift certificates automatically get a nicer invoice description
if transactionType == 'Gift Certificate':
this_description = _('Gift Certificate Purchase')
else:
this_description = transactionType
this_invoice = Invoice.create_from_item(
this_total,
this_description,
submissionUser=submissionUser,
calculate_taxes=(taxable is not False),
transactionType=transactionType,
)
paymentRecord, created = SquarePaymentRecord.objects.get_or_create(
transactionId=transaction.id,
locationId=transaction.location_id,
defaults={'invoice': this_invoice,}
)
if created:
# We process the payment now, and enqueue the job to retrieve the
# transaction again once fees have been calculated by Square
this_invoice.processPayment(
amount=this_total,
fees=0,
paidOnline=True,
methodName='Square Point of Sale',
methodTxn=transaction.id,
notify=customerEmail,
)
updateSquareFees.schedule(args=(paymentRecord,), delay=60)
if addSessionInfo:
paymentSession = request.session.get(INVOICE_VALIDATION_STR, {})
paymentSession.update({
'invoiceID': str(this_invoice.id),
'amount': this_total,
'successUrl': successUrl,
})
request.session[INVOICE_VALIDATION_STR] = paymentSession
return HttpResponseRedirect(successUrl) |
python | def connection_required(func):
"""Decorator to specify that a target connection is required in order
for the given method to be used.
Args:
func (function): function being decorated
Returns:
The wrapper function.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
"""Wrapper function to check that the given ``JLink`` has been
connected to a target.
Args:
self (JLink): the ``JLink`` instance
args: list of arguments to pass to the wrapped function
kwargs: key-word arguments dict to pass to the wrapped function
Returns:
The return value of the wrapped function.
Raises:
JLinkException: if the JLink's target is not connected.
"""
if not self.target_connected():
raise errors.JLinkException('Target is not connected.')
return func(self, *args, **kwargs)
return wrapper |
java | public static Query createQueryForNodesWithFieldLessThan(String constraintValue,
String fieldName,
Function<String, String> caseOperation) {
return FieldComparison.LT.createQueryForNodesWithField(constraintValue, fieldName, caseOperation);
} |
java | @Nullable
public final View nextView(RecyclerView.Recycler recycler, LayoutStateWrapper layoutState, LayoutManagerHelper helper, LayoutChunkResult result) {
View view = layoutState.next(recycler);
if (view == null) {
// if we are laying out views in scrap, this may return null which means there is
// no more items to layout.
if (DEBUG && !layoutState.hasScrapList()) {
throw new RuntimeException("received null view when unexpected");
}
// if there is no more views can be retrieved, this layout process is finished
result.mFinished = true;
return null;
}
helper.addChildView(layoutState, view);
return view;
} |
java | private int buildLookUpTable() {
int i = 0;
int incDen = Math.round(8F * radiusMin); // increment denominator
lut = new int[2][incDen][depth];
for( int radius = radiusMin; radius <= radiusMax; radius = radius + radiusInc ) {
i = 0;
for( int incNun = 0; incNun < incDen; incNun++ ) {
double angle = (2 * Math.PI * (double) incNun) / (double) incDen;
int indexR = (radius - radiusMin) / radiusInc;
int rcos = (int) Math.round((double) radius * Math.cos(angle));
int rsin = (int) Math.round((double) radius * Math.sin(angle));
if ((i == 0) | (rcos != lut[0][i][indexR]) & (rsin != lut[1][i][indexR])) {
lut[0][i][indexR] = rcos;
lut[1][i][indexR] = rsin;
i++;
}
}
}
return i;
} |
python | def insert(self, data, return_object=False):
""" Inserts the data as a new document. """
obj = self(data) # pylint: disable=E1102
obj.save()
if return_object:
return obj
else:
return obj["_id"] |
python | def analyze_frames(cls, workdir):
'''generate draft from recorded frames'''
record = cls(None, workdir)
obj = {}
with open(os.path.join(workdir, 'frames', 'frames.json')) as f:
obj = json.load(f)
record.device_info = obj['device']
record.frames = obj['frames']
record.analyze_all()
record.save() |
java | private Double scale(Double value, Double mean, Double std) {
if(std.equals(0.0)) {
if(value > mean) {
return 1.0;
}
else if(value < mean) {
return -1.0;
}
else {
return Math.signum(value);
}
}
else {
return (value-mean)/std;
}
} |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT:
return getScript();
case DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT_FORMAT:
return getScriptFormat();
}
return super.eGet(featureID, resolve, coreType);
} |
java | public Collection<Dependency> getMemberInjectionDependencies(
Key<?> typeKey, TypeLiteral<?> type) {
Set<Dependency> required = new LinkedHashSet<Dependency>();
for (MethodLiteral<?, Method> method : memberCollector.getMethods(type)) {
required.addAll(getDependencies(typeKey, method));
}
for (FieldLiteral<?> field : memberCollector.getFields(type)) {
Key<?> key = getKey(field);
required.add(new Dependency(typeKey, key, isOptional(field), false,
"member injection of " + field));
}
return required;
} |
java | public static boolean contentEquals(InputStream input1, InputStream input2)
throws IOException {
if (!(input1 instanceof BufferedInputStream)) {
input1 = new BufferedInputStream(input1);
}
if (!(input2 instanceof BufferedInputStream)) {
input2 = new BufferedInputStream(input2);
}
int ch = input1.read();
while (EOF != ch) {
int ch2 = input2.read();
if (ch != ch2) {
return false;
}
ch = input1.read();
}
int ch2 = input2.read();
return ch2 == EOF;
} |
java | @SuppressWarnings("unchecked")
public CassandraJavaPairRDD<K, V> select(String... columnNames) {
Seq<ColumnRef> columnRefs = toScalaSeq(toSelectableColumnRefs(columnNames));
CassandraRDD<Tuple2<K, V>> newRDD = rdd().select(columnRefs);
return wrap(newRDD);
} |
java | public int compareTo(InternalFeature o) {
if (null == o) {
return -1; // avoid NPE, put null objects at the end
}
if (null != styleDefinition && null != o.getStyleInfo()) {
if (styleDefinition.getIndex() > o.getStyleInfo().getIndex()) {
return 1;
}
if (styleDefinition.getIndex() < o.getStyleInfo().getIndex()) {
return -1;
}
}
return 0;
} |
python | def page_count(self):
"""
Get count of total pages
"""
postcount = self.post_set.count()
max_pages = (postcount / get_paginate_by())
if postcount % get_paginate_by() != 0:
max_pages += 1
return max_pages |
java | private ReferenceType computeFirstCommonSuperclassOfSameDimensionArrays(ArrayType aArrType, ArrayType bArrType)
throws ClassNotFoundException {
assert aArrType.getDimensions() == bArrType.getDimensions();
Type aBaseType = aArrType.getBasicType();
Type bBaseType = bArrType.getBasicType();
boolean aBaseIsObjectType = (aBaseType instanceof ObjectType);
boolean bBaseIsObjectType = (bBaseType instanceof ObjectType);
if (!aBaseIsObjectType || !bBaseIsObjectType) {
assert (aBaseType instanceof BasicType) || (bBaseType instanceof BasicType);
if (aArrType.getDimensions() > 1) {
// E.g.: first common supertype of int[][] and WHATEVER[][] is
// Object[]
return new ArrayType(Type.OBJECT, aArrType.getDimensions() - 1);
} else {
assert aArrType.getDimensions() == 1;
// E.g.: first common supertype type of int[] and WHATEVER[] is
// Object
return Type.OBJECT;
}
} else {
assert (aBaseType instanceof ObjectType);
assert (bBaseType instanceof ObjectType);
// Base types are both ObjectTypes, and number of dimensions is
// same.
// We just need to find the first common supertype of base types
// and return a new ArrayType using that base type.
ObjectType firstCommonBaseType = getFirstCommonSuperclass((ObjectType) aBaseType, (ObjectType) bBaseType);
return new ArrayType(firstCommonBaseType, aArrType.getDimensions());
}
} |
python | def _validate_config(self):
""" ensure REQUIRED_CONFIG_KEYS are filled """
# exit if no backend specified
if not self.backend:
return
# exit if no required config keys
if len(self.REQUIRED_CONFIG_KEYS) < 1:
return
self.config = self.config or {} # default to empty dict of no config
required_keys_set = set(self.REQUIRED_CONFIG_KEYS)
config_keys_set = set(self.config.keys())
missing_required_keys = required_keys_set - config_keys_set
unrecognized_keys = config_keys_set - required_keys_set
# if any missing required key raise ValidationError
if len(missing_required_keys) > 0:
# converts list in comma separated string
missing_keys_string = ', '.join(missing_required_keys)
# django error
raise ValidationError(_('Missing required config keys: "%s"') % missing_keys_string)
elif len(unrecognized_keys) > 0:
# converts list in comma separated string
unrecognized_keys_string = ', '.join(unrecognized_keys)
# django error
raise ValidationError(_('Unrecognized config keys: "%s"') % unrecognized_keys_string) |
java | public void setSendRefererHeader(boolean send) {
if (send == sendRefererHeader) {
return;
}
this.sendRefererHeader = send;
getConfig().setProperty(SPIDER_SENDER_REFERER_HEADER, this.sendRefererHeader);
} |
python | def _conf(cls, opts):
"""Setup logging via ini-file from logging_conf_file option."""
if not opts.logging_conf_file:
return False
if not os.path.exists(opts.logging_conf_file):
# FileNotFoundError added only in Python 3.3
# https://docs.python.org/3/whatsnew/3.3.html#pep-3151-reworking-the-os-and-io-exception-hierarchy
raise OSError("Error: Unable to locate specified logging configuration file!")
logging.config.fileConfig(opts.logging_conf_file, disable_existing_loggers=False)
return True |
python | def _iterate_records(self):
""" iterate over each record
"""
raise_invalid_gzip = False
empty_record = False
while True:
try:
self.record = self._next_record(self.next_line)
if raise_invalid_gzip:
self._raise_invalid_gzip_err()
yield self.record
except EOFError:
empty_record = True
self.read_to_end()
if self.reader.decompressor:
# if another gzip member, continue
if self.reader.read_next_member():
continue
# if empty record, then we're done
elif empty_record:
break
# otherwise, probably a gzip
# containing multiple non-chunked records
# raise this as an error
else:
raise_invalid_gzip = True
# non-gzip, so we're done
elif empty_record:
break
self.close() |
python | def has_option(self, target):
"""
Return ``True`` if the actual arguments include
the specified ``target`` option or,
if ``target`` is a list of options,
at least one of them.
:param target: the option or a list of options
:type target: Unicode string or list of Unicode strings
:rtype: bool
"""
if isinstance(target, list):
target_set = set(target)
else:
target_set = set([target])
return len(target_set & set(self.actual_arguments)) > 0 |
java | public static String toStringForTimeZone(DateTime dateTime, String newZoneId) {
return dateTimesHelper.toStringForTimeZone(dateTime, newZoneId);
} |
java | public static int cusolverSpScsrlsvluHost(
cusolverSpHandle handle,
int n,
int nnzA,
cusparseMatDescr descrA,
Pointer csrValA,
Pointer csrRowPtrA,
Pointer csrColIndA,
Pointer b,
float tol,
int reorder,
Pointer x,
int[] singularity)
{
return checkResult(cusolverSpScsrlsvluHostNative(handle, n, nnzA, descrA, csrValA, csrRowPtrA, csrColIndA, b, tol, reorder, x, singularity));
} |
java | public void setExtension(/* @Nullable */ JvmField field, EObject sourceElement, boolean value) {
if (field == null)
return;
internalSetExtension(field, sourceElement, value);
} |
java | public static Context discover(Object context, Class<?>... subset) {
Set<Class<?>> contextSubset = (subset == null || subset.length == 0)?
contexts.keySet() :new HashSet<Class<?>>(Arrays.asList(subset));
Set<Class<?>> contextClasses = contexts.keySet();
for (Class<?> contextClass : contextClasses) {
if(!contextSubset.contains(contextClass)) continue;
if(contextClass.isAssignableFrom(context.getClass())) {
return contexts.get(contextClass).resolve(context);
}
}
throw new ContextNotFoundException(context.getClass());
} |
python | def job_success(self, job, queue, job_result):
"""
Called just after an execute call was successful.
job_result is the value returned by the callback, if any.
"""
job.queued.delete()
job.hmset(end=str(datetime.utcnow()), status=STATUSES.SUCCESS)
queue.success.rpush(job.ident)
self.log(self.job_success_message(job, queue, job_result))
if hasattr(job, 'on_success'):
job.on_success(queue, job_result) |
java | public static Version valueOf(String versionString)
throws IllegalArgumentException {
Matcher matcher = versionPattern.matcher(versionString);
if (!matcher.matches()) {
throw new IllegalArgumentException(
"The version string must match the pattern '"
+ versionRegExp + "'.");
}
int majorVersion = Integer.parseInt(matcher.group(1));
int minorVersion = Integer.parseInt(matcher.group(2));
int patchVersion = Integer.parseInt(matcher.group(3));
String preReleaseInformation = matcher.group(5);
String buildMetadata = matcher.group(12);
return new Version(majorVersion, minorVersion, patchVersion,
preReleaseInformation, buildMetadata);
} |
python | def floyd_warshall_get_cycle(self, distance, nextn, element = None):
'''
API:
floyd_warshall_get_cycle(self, distance, nextn, element = None)
Description:
Finds a negative cycle in the graph.
Pre:
(1) distance and nextn are outputs of floyd_warshall method.
(2) The graph should have a negative cycle, , ie.
distance[(i,i)] < 0 for some node i.
Return:
Returns the list of nodes on the cycle. Ex: [i,j,k,...,r], where
(i,j), (j,k) and (r,i) are some edges in the cycle.
'''
nl = self.get_node_list()
if element is None:
for i in nl:
if distance[(i,i)] < 0:
# graph has a cycle on the path from i to i.
element = i
break
else:
raise Exception('Graph does not have a negative cycle!')
elif distance[(element,element)] >= 0:
raise Exception('Graph does not have a negative cycle that contains node '+str(element)+'!')
# find the cycle on the path from i to i.
cycle = [element]
k = nextn[(element,element)]
while k not in cycle:
cycle.insert(1,k)
k = nextn[(element,k)]
if k==element:
return cycle
else:
return self.floyd_warshall_get_cycle(distance, nextn, k) |
java | public StateId forRange(final StateRange range) {
if (getRange().equals(range)) {
return this;
}
return new StateId(stateToken, range);
} |
java | public void del(byte[] key){
Jedis jedis = jedisPool.getResource();
try{
jedis.del(key);
}finally{
jedisPool.returnResource(jedis);
}
} |
java | public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
autoscaleaction updateresources[] = new autoscaleaction[resources.length];
for (int i=0;i<resources.length;i++){
updateresources[i] = new autoscaleaction();
updateresources[i].name = resources[i].name;
updateresources[i].profilename = resources[i].profilename;
updateresources[i].parameters = resources[i].parameters;
updateresources[i].vmdestroygraceperiod = resources[i].vmdestroygraceperiod;
updateresources[i].quiettime = resources[i].quiettime;
updateresources[i].vserver = resources[i].vserver;
}
result = update_bulk_request(client, updateresources);
}
return result;
} |
java | @Override
public void setActionObject(final Object data) {
InputModel model = getOrCreateComponentModel();
model.actionObject = data;
} |
java | @SuppressWarnings("unchecked")
public <K> K[] getKeys(Map<K, ?> map) {
K[] result = null;
Set<K> keySet = map.keySet();
if (keySet.size() > 0) {
result = (K[]) keySet.toArray(new Object[keySet.size()]);
}
return result;
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.