language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python
|
def set_governors(self, gov, rg=None):
'''
Set governors
gov: str name of the governor
rg: list of range of cores
'''
to_change = self.__get_ranges("online")
if type(rg) == int:
rg= [rg]
if rg: to_change= set(rg) & set(self.__get_ranges("online"))
for cpu in to_change:
fpath = path.join("cpu%i"%cpu,"cpufreq","scaling_governor")
self.__write_cpu_file(fpath, gov.encode())
|
python
|
def import_action(self, request, *args, **kwargs):
"""
Perform a dry_run of the import to make sure the import will not
result in errors. If there where no error, save the user
uploaded file to a local temp file that will be used by
'process_import' for the actual import.
"""
if not self.has_import_permission(request):
raise PermissionDenied
context = self.get_import_context_data()
import_formats = self.get_import_formats()
form_type = self.get_import_form()
form_kwargs = self.get_form_kwargs(form_type, *args, **kwargs)
form = form_type(import_formats,
request.POST or None,
request.FILES or None,
**form_kwargs)
if request.POST and form.is_valid():
input_format = import_formats[
int(form.cleaned_data['input_format'])
]()
import_file = form.cleaned_data['import_file']
# first always write the uploaded file to disk as it may be a
# memory file or else based on settings upload handlers
tmp_storage = self.write_to_tmp_storage(import_file, input_format)
# then read the file, using the proper format-specific mode
# warning, big files may exceed memory
try:
data = tmp_storage.read(input_format.get_read_mode())
if not input_format.is_binary() and self.from_encoding:
data = force_text(data, self.from_encoding)
dataset = input_format.create_dataset(data)
except UnicodeDecodeError as e:
return HttpResponse(_(u"<h1>Imported file has a wrong encoding: %s</h1>" % e))
except Exception as e:
return HttpResponse(_(u"<h1>%s encountered while trying to read file: %s</h1>" % (type(e).__name__, import_file.name)))
# prepare kwargs for import data, if needed
res_kwargs = self.get_import_resource_kwargs(request, form=form, *args, **kwargs)
resource = self.get_import_resource_class()(**res_kwargs)
# prepare additional kwargs for import_data, if needed
imp_kwargs = self.get_import_data_kwargs(request, form=form, *args, **kwargs)
result = resource.import_data(dataset, dry_run=True,
raise_errors=False,
file_name=import_file.name,
user=request.user,
**imp_kwargs)
context['result'] = result
if not result.has_errors() and not result.has_validation_errors():
initial = {
'import_file_name': tmp_storage.name,
'original_file_name': import_file.name,
'input_format': form.cleaned_data['input_format'],
}
confirm_form = self.get_confirm_import_form()
initial = self.get_form_kwargs(form=form, **initial)
context['confirm_form'] = confirm_form(initial=initial)
else:
res_kwargs = self.get_import_resource_kwargs(request, form=form, *args, **kwargs)
resource = self.get_import_resource_class()(**res_kwargs)
context.update(self.admin_site.each_context(request))
context['title'] = _("Import")
context['form'] = form
context['opts'] = self.model._meta
context['fields'] = [f.column_name for f in resource.get_user_visible_fields()]
request.current_app = self.admin_site.name
return TemplateResponse(request, [self.import_template_name],
context)
|
java
|
public static List<Long> lengths(final Iterable<Range<Long>> ranges) {
checkNotNull(ranges);
List<Long> lengths = new ArrayList<Long>();
for (Range<Long> range : ranges) {
lengths.add(length(range));
}
return lengths;
}
|
python
|
def opening(image, radius=None, mask=None, footprint=None):
'''Do a morphological opening
image - pixel image to operate on
radius - use a structuring element with the given radius. If no radius,
use an 8-connected structuring element.
mask - if present, only use unmasked pixels for operations
'''
eroded_image = grey_erosion(image, radius, mask, footprint)
return grey_dilation(eroded_image, radius, mask, footprint)
|
java
|
public ImportExportResponseInner importMethod(String resourceGroupName, String serverName, ImportRequest parameters) {
return importMethodWithServiceResponseAsync(resourceGroupName, serverName, parameters).toBlocking().last().body();
}
|
java
|
@Nullable
JSModule getModuleByName(String name) {
for (JSModule m : modules) {
if (m.getName().equals(name)) {
return m;
}
}
return null;
}
|
python
|
def sendNotification(snmpEngine, authData, transportTarget, contextData,
notifyType, *varBinds, **options):
"""Creates a generator to send one or more SNMP notifications.
On each iteration, new SNMP TRAP or INFORM notification is send
(:RFC:`1905#section-4,2,6`). The iterator blocks waiting for
INFORM acknowledgement to arrive or error to occur.
Parameters
----------
snmpEngine: :py:class:`~pysnmp.hlapi.SnmpEngine`
Class instance representing SNMP engine.
authData: :py:class:`~pysnmp.hlapi.CommunityData` or :py:class:`~pysnmp.hlapi.UsmUserData`
Class instance representing SNMP credentials.
transportTarget: :py:class:`~pysnmp.hlapi.asyncore.UdpTransportTarget` or :py:class:`~pysnmp.hlapi.asyncore.Udp6TransportTarget`
Class instance representing transport type along with SNMP peer address.
contextData: :py:class:`~pysnmp.hlapi.ContextData`
Class instance representing SNMP ContextEngineId and ContextName values.
notifyType: str
Indicates type of notification to be sent. Recognized literal
values are *trap* or *inform*.
\*varBinds: :class:`tuple` of OID-value pairs or :py:class:`~pysnmp.smi.rfc1902.ObjectType` or :py:class:`~pysnmp.smi.rfc1902.NotificationType`
One or more objects representing MIB variables to place
into SNMP notification. It could be tuples of OID-values
or :py:class:`~pysnmp.smi.rfc1902.ObjectType` class instances
of :py:class:`~pysnmp.smi.rfc1902.NotificationType` objects.
SNMP Notification PDU includes some housekeeping items that
are required for SNMP to function.
Agent information:
* SNMPv2-MIB::sysUpTime.0 = <agent uptime>
* SNMPv2-SMI::snmpTrapOID.0 = {SNMPv2-MIB::coldStart, ...}
Applicable to SNMP v1 TRAP:
* SNMP-COMMUNITY-MIB::snmpTrapAddress.0 = <agent-IP>
* SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 = <snmp-community-name>
* SNMP-COMMUNITY-MIB::snmpTrapEnterprise.0 = <enterprise-OID>
.. note::
Unless user passes some of these variable-bindings, `.sendNotification()`
call will fill in the missing items.
User variable-bindings:
* SNMPv2-SMI::NOTIFICATION-TYPE
* SNMPv2-SMI::OBJECT-TYPE
.. note::
The :py:class:`~pysnmp.smi.rfc1902.NotificationType` object ensures
properly formed SNMP notification (to comply MIB definition). If you
build notification PDU out of :py:class:`~pysnmp.smi.rfc1902.ObjectType`
objects or simple tuples of OID-value objects, it is your responsibility
to provide well-formed notification payload.
Other Parameters
----------------
\*\*options:
* `lookupMib` - load MIB and resolve response MIB variables at
the cost of slightly reduced performance. Default is `True`.
Yields
------
errorIndication: str
True value indicates SNMP engine error.
errorStatus: str
True value indicates SNMP PDU error.
errorIndex: int
Non-zero value refers to `varBinds[errorIndex-1]`
varBinds: tuple
A sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` class
instances representing MIB variables returned in SNMP response.
Raises
------
PySnmpError
Or its derivative indicating that an error occurred while
performing SNMP operation.
Notes
-----
The `sendNotification` generator will be exhausted immediately unless
an instance of :py:class:`~pysnmp.smi.rfc1902.NotificationType` class
or a sequence of :py:class:`~pysnmp.smi.rfc1902.ObjectType` `varBinds`
are send back into running generator (supported since Python 2.6).
Examples
--------
>>> from pysnmp.hlapi import *
>>> g = sendNotification(SnmpEngine(),
... CommunityData('public'),
... UdpTransportTarget(('demo.snmplabs.com', 162)),
... ContextData(),
... 'trap',
... NotificationType(ObjectIdentity('IF-MIB', 'linkDown')))
>>> next(g)
(None, 0, 0, [])
>>>
"""
# noinspection PyShadowingNames
def cbFun(snmpEngine, sendRequestHandle,
errorIndication, errorStatus, errorIndex,
varBinds, cbCtx):
cbCtx['errorIndication'] = errorIndication
cbCtx['errorStatus'] = errorStatus
cbCtx['errorIndex'] = errorIndex
cbCtx['varBinds'] = varBinds
cbCtx = {}
while True:
if varBinds:
ntforg.sendNotification(snmpEngine, authData, transportTarget,
contextData, notifyType, *varBinds,
cbFun=cbFun, cbCtx=cbCtx,
lookupMib=options.get('lookupMib', True))
snmpEngine.transportDispatcher.runDispatcher()
errorIndication = cbCtx.get('errorIndication')
errorStatus = cbCtx.get('errorStatus')
errorIndex = cbCtx.get('errorIndex')
varBinds = cbCtx.get('varBinds', [])
else:
errorIndication = errorStatus = errorIndex = None
varBinds = []
varBinds = (yield errorIndication, errorStatus, errorIndex, varBinds)
if not varBinds:
break
|
python
|
def mapped_read_count(self, force=False):
"""
Counts total reads in a BAM file.
If a file self.bam + '.scale' exists, then just read the first line of
that file that doesn't start with a "#". If such a file doesn't exist,
then it will be created with the number of reads as the first and only
line in the file.
The result is also stored in self._readcount so that the time-consuming
part only runs once; use force=True to force re-count.
Parameters
----------
force : bool
If True, then force a re-count; otherwise use cached data if
available.
"""
# Already run?
if self._readcount and not force:
return self._readcount
if os.path.exists(self.fn + '.mmr') and not force:
for line in open(self.fn + '.mmr'):
if line.startswith('#'):
continue
self._readcount = float(line.strip())
return self._readcount
cmds = ['samtools',
'view',
'-c',
'-F', '0x4',
self.fn]
p = subprocess.Popen(
cmds, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if stderr:
sys.stderr.write('samtools says: %s' % stderr)
return None
mapped_reads = int(stdout)
# write to file so the next time you need the lib size you can access
# it quickly
if not os.path.exists(self.fn + '.mmr'):
fout = open(self.fn + '.mmr', 'w')
fout.write(str(mapped_reads) + '\n')
fout.close()
self._readcount = mapped_reads
return self._readcount
|
python
|
def importExistingServerCertificate(self, alias, certPassword, certFile):
"""This operation imports an existing server certificate, stored in the PKCS #12 format, into the keystore."""
url = self._url + "/sslcertificates/importExistingServerCertificate"
files = {}
files['certFile'] = certFile
params = {
"f" : "json",
"alias" : alias,
"certPassword" : certPassword
}
return self._post(url=url,
param_dict=params,
securityHandler=self._securityHandler,
files=files,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
|
java
|
@Override
public AssumeRoleWithSAMLResult assumeRoleWithSAML(AssumeRoleWithSAMLRequest request) {
request = beforeClientExecution(request);
return executeAssumeRoleWithSAML(request);
}
|
python
|
def get_top_edge_depth(self):
"""
Compute top edge depth of each surface element and return area-weighted
average value (in km).
"""
areas = self._get_areas()
depths = numpy.array(
[surf.get_top_edge_depth() for surf in self.surfaces])
return numpy.sum(areas * depths) / numpy.sum(areas)
|
java
|
@Override
public RestRepositories getRepositories(Request request) {
RestRepositories repositories = new RestRepositories();
for (String repositoryName : getRepositoryManager().getJcrRepositoryNames()) {
addRepository(request, repositories, repositoryName);
}
return repositories;
}
|
java
|
public @NonNull Optional<T> get(final @NonNull String name) {
return Optional.ofNullable(this.byName.get(name));
}
|
java
|
public void writeHtmlString(String strHTML, PrintWriter out)
{
int iIndex;
if (strHTML == null)
return;
while ((iIndex = strHTML.indexOf(HtmlConstants.TITLE_TAG)) != -1)
{ // ** FIX THIS to look for a <xxx/> and look up the token **
strHTML = strHTML.substring(0, iIndex) + ((BasePanel)this.getScreenField()).getTitle() + strHTML.substring(iIndex + HtmlConstants.TITLE_TAG.length());
}
out.println(strHTML);
}
|
python
|
def _glob_to_re(self, pattern):
"""Translate a shell-like glob pattern to a regular expression.
Return a string containing the regex. Differs from
'fnmatch.translate()' in that '*' does not match "special characters"
(which are platform-specific).
"""
pattern_re = fnmatch.translate(pattern)
# '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
# IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
# and by extension they shouldn't match such "special characters" under
# any OS. So change all non-escaped dots in the RE to match any
# character except the special characters (currently: just os.sep).
sep = os.sep
if os.sep == '\\':
# we're using a regex to manipulate a regex, so we need
# to escape the backslash twice
sep = r'\\\\'
escaped = r'\1[^%s]' % sep
pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
return pattern_re
|
python
|
def set_custom_ticks(self, locations=None, clockwise=False, multiple=1,
axes_colors=None, tick_formats=None, **kwargs):
"""
Having called get_ticks_from_axis_limits, set the custom ticks on the
plot.
"""
for k in ['b', 'l', 'r']:
self.ticks(ticks=self._ticks[k], locations=locations,
axis=k, clockwise=clockwise, multiple=multiple,
axes_colors=axes_colors, tick_formats=tick_formats,
**kwargs)
|
java
|
@Override
public void onFileCreate(File file) {
try {
engine.addTemplate(context.getBundle(0), file.toURI().toURL());
} catch (MalformedURLException e) {
LOGGER.error("Cannot compute the url of file {}", file.getAbsolutePath(), e);
}
}
|
java
|
public static String join( Collection col, char sep )
{
if( col.isEmpty() )
{
return "";
}
StringBuffer buffer = new StringBuffer();
boolean first = true;
for (Object o : col)
{
if( first )
{
first = false;
}
else
{
buffer.append( sep );
}
buffer.append( o.toString() );
}
return buffer.toString();
}
|
java
|
public boolean removeMapping(String hostName, String contextPath) {
log.info("Remove mapping host: {} context: {}", hostName, contextPath);
final String key = getKey(hostName, contextPath);
log.debug("Remove mapping: {}", key);
return (mapping.remove(key) != null);
}
|
python
|
def priority(s):
"""Return priority for a given object."""
# REZ: Previously this value was calculated in place many times which is
# expensive. Do it once early.
# REZ: Changed this to output a list, so that can nicely sort "validate"
# items by the sub-priority of their schema
type_of_s = type(s)
if type_of_s in (list, tuple, set, frozenset):
return [ITERABLE]
if type_of_s is dict:
return [DICT]
if issubclass(type_of_s, type):
return [TYPE]
if hasattr(s, 'validate'):
p = [VALIDATOR]
if hasattr(s, "_schema"):
p.extend(priority(s._schema))
return p
if callable(s):
return [CALLABLE]
else:
return [COMPARABLE]
|
java
|
static Collection<Sample> samples(Collection<SampleDTO> samples) {
return Collections2.transform(samples, DTO_TO_SAMPLE);
}
|
python
|
def exception_info(current_filename=None, index=-1):
"Analizar el traceback y armar un dict con la info amigable user-friendly"
# guardo el traceback original (por si hay una excepción):
info = sys.exc_info() # exc_type, exc_value, exc_traceback
# importante: no usar unpacking porque puede causar memory leak
if not current_filename:
# genero un call stack para ver quien me llamó y limitar la traza:
# advertencia: esto es necesario ya que en py2exe no tengo __file__
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
current_filename = os.path.normpath(os.path.abspath(f.f_code.co_filename))
# extraer la última traza del archivo solicitado:
# (útil para no alargar demasiado la traza con lineas de las librerías)
ret = {'filename': "", 'lineno': 0, 'function_name': "", 'code': ""}
try:
for (filename, lineno, fn, text) in traceback.extract_tb(info[2]):
if os.path.normpath(os.path.abspath(filename)) == current_filename:
ret = {'filename': filename, 'lineno': lineno,
'function_name': fn, 'code': text}
except Exception, e:
pass
# obtengo el mensaje de excepcion tal cual lo formatea python:
# (para evitar errores de encoding)
try:
ret['msg'] = traceback.format_exception_only(*info[0:2])[0]
except:
ret['msg'] = '<no disponible>'
# obtener el nombre de la excepcion (ej. "NameError")
try:
ret['name'] = info[0].__name__
except:
ret['name'] = 'Exception'
# obtener la traza formateada como string:
try:
tb = traceback.format_exception(*info)
ret['tb'] = ''.join(tb)
except:
ret['tb'] = ""
return ret
|
python
|
def update_wsnum_in_files(self, vernum):
"""
With the given version number ```vernum```,
update the source's version number, and replace in the file hashmap.
the version number is in the CHECKSUMS file.
:param vernum:
:return:
"""
self.version_num = vernum
# replace the WSNUMBER in the url paths with the real WS###
for f in self.files:
url = self.files[f].get('url')
url = re.sub(r'WSNUMBER', self.version_num, url)
self.files[f]['url'] = url
LOG.debug(
"Replacing WSNUMBER in %s with %s", f, self.version_num)
# also the letter file - keep this so we know the version number
# self.files['checksums']['file'] = re.sub(
# r'WSNUMBER', self.version_num, self.files['checksums']['file'])
return
|
java
|
private void insertVariableDataTyping(Term term, Function atom, int position,
Map<String, List<IndexedPosition>> termOccurenceIndex) throws UnknownDatatypeException {
if (term instanceof Function) {
Function function = (Function) term;
Predicate functionSymbol = function.getFunctionSymbol();
if (function.isDataTypeFunction() ||
(functionSymbol instanceof URITemplatePredicate)
|| (functionSymbol instanceof BNodePredicate)) {
// NO-OP for already assigned datatypes, or object properties, or bnodes
}
else if (function.isOperation()) {
for (int i = 0; i < function.getArity(); i++) {
insertVariableDataTyping(function.getTerm(i), function, i, termOccurenceIndex);
}
} else {
throw new IllegalArgumentException("Unsupported subtype of: " + Function.class.getSimpleName());
}
} else if (term instanceof Variable) {
Variable variable = (Variable) term;
Term newTerm;
RDFDatatype type = getDataType(termOccurenceIndex, variable);
newTerm = termFactory.getTypedTerm(variable, type);
log.info("Datatype "+type+" for the value " + variable + " of the property " + atom + " has been " +
"inferred " +
"from the database");
atom.setTerm(position, newTerm);
} else if (term instanceof ValueConstant) {
Term newTerm = termFactory.getTypedTerm(term, ((ValueConstant) term).getType());
atom.setTerm(position, newTerm);
} else {
throw new IllegalArgumentException("Unsupported subtype of: " + Term.class.getSimpleName());
}
}
|
java
|
public static Resource toPythonConfigParser(@NonNull String sectionName, @NonNull Resource output) throws IOException {
try (BufferedWriter writer = new BufferedWriter(output.writer())) {
writer.write("[");
writer.write(sectionName);
writer.write("]\n");
for (Map.Entry<String, String> e : Sorting.sortMapEntries(getInstance().properties,
Map.Entry.comparingByKey())) {
writer.write(e.getKey());
writer.write(" : ");
writer.write(e.getValue().replaceAll("\n", "\n\t\t\t"));
writer.write("\n");
}
}
return output;
}
|
python
|
def score(self, features, classes, scoring_function=accuracy_score, **scoring_function_kwargs):
"""Estimates the accuracy of the predictions from the constructed feature
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix to predict from
classes: array-like {n_samples}
List of true class labels
Returns
-------
accuracy_score: float
The estimated accuracy based on the constructed feature
"""
if not self.mu:
raise ValueError('The DistanceClassifier model must be fit before score() can be called')
return scoring_function(classes, self.predict(features), **scoring_function_kwargs)
|
java
|
public int getOwnerDocument(int nodeHandle)
{
if (DTM.DOCUMENT_NODE == getNodeType(nodeHandle))
return DTM.NULL;
return getDocumentRoot(nodeHandle);
}
|
python
|
def gen_authenticated_decorator(api_tokens=[]):
"""
This is a helper to build an `@authenticated` decorator that knows which
API tokens are allowed.
Example usage which allows 2 valid API tokens:
authenticated = gen_authenticated_decorator(['123', 'abc'])
@authenticated
def test(request):
return { "hello": "world" }
"""
if isinstance(api_tokens, (list, tuple)):
pass
elif isinstance(api_tokens, str):
api_tokens = [api_tokens]
else:
raise Exception("Invalid data type for `api_tokens`: %s. Must be list, tuple or string" % type(api_tokens))
# The normal @authenticated decorator, which accesses `api_tokens`
def authenticated(func):
"""
@authenticated decorator, which makes sure the HTTP request has the correct access token.
Header has to be in the format "Authorization: Bearer {token}"
If no valid header is part of the request's HTTP headers, this decorator automatically
returns the HTTP status code 403.
"""
@wraps(func)
def wrapper(request, *args, **kwargs):
# Make sure Authorization header is present
if not request.requestHeaders.hasHeader("Authorization"):
request.setHeader('Content-Type', 'application/json')
request.setResponseCode(403)
return json.dumps({"error": "No Authorization header found"})
# Make sure Authorization header is valid
user_auth_token = str(request.requestHeaders.getRawHeaders("Authorization")[0])
if not user_auth_token.startswith("Bearer "):
request.setHeader('Content-Type', 'application/json')
request.setResponseCode(403)
return json.dumps({"error": "No valid Authorization header found"})
token = user_auth_token[7:]
if token not in api_tokens:
request.setHeader('Content-Type', 'application/json')
request.setResponseCode(403)
return json.dumps({"error": "Not authorized"})
# If all good, proceed to request handler
return func(request, *args, **kwargs)
return wrapper
# Return the decorator itself
return authenticated
|
python
|
def post(self, request, *args, **kwargs):
# type: (HttpRequest, object, object) -> HttpResponse
"""The method that handles HTTP POST request on the view.
This method is called when the view receives a HTTP POST
request, which is generally the request sent from Alexa during
skill invocation. The request is verified through the
registered list of verifiers, before invoking the request
handlers. The method returns a
:py:class:`django.http.JsonResponse` in case of successful
skill invocation.
:param request: The input request sent by Alexa to the skill
:type request: django.http.HttpRequest
:return: The response from the skill to Alexa
:rtype: django.http.JsonResponse
:raises: :py:class:`django.http.HttpResponseBadRequest` if the
request verification fails.
:py:class:`django.http.HttpResponseServerError` for any
internal exception.
"""
try:
content = request.body.decode(
verifier_constants.CHARACTER_ENCODING)
response = self._webservice_handler.verify_request_and_dispatch(
http_request_headers=request.META, http_request_body=content)
return JsonResponse(
data=response, safe=False)
except VerificationException:
logger.exception(msg="Request verification failed")
return HttpResponseBadRequest(
content="Incoming request failed verification")
except AskSdkException:
logger.exception(msg="Skill dispatch exception")
return HttpResponseServerError(
content="Exception occurred during skill dispatch")
|
python
|
def _xor_block(a, b):
""" XOR two blocks of equal length. """
return ''.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
|
java
|
public LDAPUserContext getUserContext(AuthenticatedUser authenticatedUser)
throws GuacamoleException {
// Bind using credentials associated with AuthenticatedUser
Credentials credentials = authenticatedUser.getCredentials();
LDAPConnection ldapConnection = bindAs(credentials);
if (ldapConnection == null)
return null;
try {
// Build user context by querying LDAP
LDAPUserContext userContext = userContextProvider.get();
userContext.init(authenticatedUser, ldapConnection);
return userContext;
}
// Always disconnect
finally {
ldapService.disconnect(ldapConnection);
}
}
|
java
|
void configureNotFound(Reflections reflections) {
log.info("Checking for a not-found endpoint..");
NotFound notFound = getEndpoint(NotFound.class, "not-found", reflections);
if (notFound == null) notFound = new DefaultNotFound();
printEndpoint(notFound, "not-found");
this.notFound = notFound;
}
|
python
|
def getAnalysisRequestTemplates(self):
"""
This functions builds a list of tuples with the object AnalysisRequestTemplates' uids and names.
:returns: A list of tuples where the first value of the tuple is the AnalysisRequestTemplate name and the
second one is the AnalysisRequestTemplate UID. --> [(ART.title),(ART.UID),...]
"""
l = []
art_uids = self.ar_templates
# I have to get the catalog in this way because I can't do it with 'self'...
pc = getToolByName(api.portal.get(), 'uid_catalog')
for art_uid in art_uids:
art_obj = pc(UID=art_uid)
if len(art_obj) != 0:
l.append((art_obj[0].Title, art_uid))
return l
|
python
|
def inline_map_reduce(self, map, reduce, full_response=False, **kwargs):
"""Perform an inline map/reduce operation on this collection.
Perform the map/reduce operation on the server in RAM. A result
collection is not created. The result set is returned as a list
of documents.
If `full_response` is ``False`` (default) returns the
result documents in a list. Otherwise, returns the full
response from the server to the `map reduce command`_.
The :meth:`inline_map_reduce` method obeys the :attr:`read_preference`
of this :class:`Collection`.
:Parameters:
- `map`: map function (as a JavaScript string)
- `reduce`: reduce function (as a JavaScript string)
- `full_response` (optional): if ``True``, return full response to
this command - otherwise just return the result collection
- `**kwargs` (optional): additional arguments to the
`map reduce command`_ may be passed as keyword arguments to this
helper method, e.g.::
>>> db.test.inline_map_reduce(map, reduce, limit=2)
.. versionchanged:: 3.4
Added the `collation` option.
"""
cmd = SON([("mapreduce", self.__name),
("map", map),
("reduce", reduce),
("out", {"inline": 1})])
collation = validate_collation_or_none(kwargs.pop('collation', None))
cmd.update(kwargs)
with self._socket_for_reads() as (sock_info, slave_ok):
if sock_info.max_wire_version >= 4 and 'readConcern' not in cmd:
res = self._command(sock_info, cmd, slave_ok,
read_concern=self.read_concern,
collation=collation)
else:
res = self._command(sock_info, cmd, slave_ok,
collation=collation)
if full_response:
return res
else:
return res.get("results")
|
python
|
def register(cls, attr_name, attr_cls):
"""
Register a custom extended property in this item class so they can be accessed just like any other attribute
"""
if not cls.INSERT_AFTER_FIELD:
raise ValueError('Class %s is missing INSERT_AFTER_FIELD value' % cls)
try:
cls.get_field_by_fieldname(attr_name)
except InvalidField:
pass
else:
raise ValueError("'%s' is already registered" % attr_name)
if not issubclass(attr_cls, ExtendedProperty):
raise ValueError("%r must be a subclass of ExtendedProperty" % attr_cls)
# Check if class attributes are properly defined
attr_cls.validate_cls()
# ExtendedProperty is not a real field, but a placeholder in the fields list. See
# https://msdn.microsoft.com/en-us/library/office/aa580790(v=exchg.150).aspx
#
# Find the correct index for the new extended property, and insert.
field = ExtendedPropertyField(attr_name, value_cls=attr_cls)
cls.add_field(field, insert_after=cls.INSERT_AFTER_FIELD)
|
java
|
public static byte[] queryBinary(PreparedStatement stmt, byte[] def) throws SQLException {
ResultSet rs = null;
try {
rs = stmt.executeQuery();
return rs.next() ? rs.getBytes(1) : def;
} finally {
close(rs);
}
}
|
python
|
def get_project(self, project_id):
"""
Returns a Project instance.
:param project_id: Project identifier
:returns: Project instance
"""
try:
UUID(project_id, version=4)
except ValueError:
raise aiohttp.web.HTTPBadRequest(text="Project ID {} is not a valid UUID".format(project_id))
if project_id not in self._projects:
raise aiohttp.web.HTTPNotFound(text="Project ID {} doesn't exist".format(project_id))
return self._projects[project_id]
|
java
|
public boolean existsOnBroker (String brokerId) {
boolean result = false;
PerBrokerInfo info;
synchronized (this.brokerDetails) {
info = this.brokerDetails.get(brokerId);
}
if ((info != null) && (info.exists)) {
result = true;
}
return result;
}
|
java
|
public ImageEncodingBITORDR createImageEncodingBITORDRFromString(EDataType eDataType, String initialValue) {
ImageEncodingBITORDR result = ImageEncodingBITORDR.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
|
java
|
public void floodFill(int xx, int yy, Rectangle clip, int replacement)
{
floodFill(xx, yy, clip, (c)->c!=replacement, replacement);
}
|
java
|
public static IntArray getInstance(byte[] buffer, int bitCount, ByteOrder order)
{
return getInstance(buffer, 0, buffer.length, bitCount, order);
}
|
java
|
public void appendMsg(final String msg) {
if (!EventQueue.isDispatchThread()) {
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
appendMsg(msg);
}
});
} catch (InvocationTargetException e) {
LOGGER.error("Failed to append message: ", e);
} catch (InterruptedException ignore) {
}
return;
}
displayRandomTip();
getLogPanel().append(msg);
JScrollBar vertical = getLogJScrollPane().getVerticalScrollBar();
vertical.setValue(vertical.getMaximum());
}
|
java
|
public static XLinkConnectorView[] getViewsOfRegistration(XLinkConnectorRegistration registration) {
List<XLinkConnectorView> viewsOfRegistration = new ArrayList<XLinkConnectorView>();
Map<ModelDescription, XLinkConnectorView[]> modelsToViews = registration.getModelsToViews();
for (XLinkConnectorView[] views : modelsToViews.values()) {
for (int i = 0; i < views.length; i++) {
XLinkConnectorView view = views[i];
if (!viewsOfRegistration.contains(view)) {
viewsOfRegistration.add(view);
}
}
}
return viewsOfRegistration.toArray(new XLinkConnectorView[0]);
}
|
python
|
def tolist(self, to):
"""
Make sure that our addressees are a unicoded list
Arguments:
- `to`: str or list
Return: [u, ...]
Exceptions: None
"""
return ', '.join(isinstance(to, list) and [u(x) for x in to] or [u(to)])
|
python
|
def based_on(self, based_on):
"""Sets the based_on of this TaxRate.
:param based_on: The based_on of this TaxRate.
:type: str
"""
allowed_values = ["shippingAddress", "billingAddress"]
if based_on is not None and based_on not in allowed_values:
raise ValueError(
"Invalid value for `based_on` ({0}), must be one of {1}"
.format(based_on, allowed_values)
)
self._based_on = based_on
|
java
|
public Agent newAgent(QualifiedName ag, String label) {
Agent res = newAgent(ag);
if (label != null)
res.getLabel().add(newInternationalizedString(label));
return res;
}
|
python
|
def transitive_closure(self):
"""Compute the transitive closure of the matrix."""
data = [[1 if j else 0 for j in i] for i in self.data]
for k in range(self.rows):
for i in range(self.rows):
for j in range(self.rows):
if data[i][k] and data[k][j]:
data[i][j] = 1
return data
|
java
|
public void setContains(T value, boolean isMember) {
checkNotFrozen();
m_membershipMap.put(value, new Boolean(isMember));
}
|
java
|
public static Comparable<?> getComparable(ValueData value, int type) throws UnsupportedEncodingException,
IllegalStateException, IOException, IllegalNameException, RepositoryException
{
switch (type)
{
case PropertyType.BINARY :
return null;
case PropertyType.BOOLEAN :
return ComparableBoolean.valueOf(ValueDataUtil.getBoolean(value));
case PropertyType.DATE :
return new Long(ValueDataUtil.getDate(value).getTimeInMillis());
case PropertyType.DOUBLE :
return new Double(ValueDataUtil.getDouble(value));
case PropertyType.LONG :
return new Long(ValueDataUtil.getLong(value));
case PropertyType.NAME :
return new QPathEntry(ValueDataUtil.getName(value), 1);
case PropertyType.PATH :
return ValueDataUtil.getPath(value);
case PropertyType.REFERENCE :
return ValueDataUtil.getReference(value);
case PropertyType.STRING :
return ValueDataUtil.getString(value);
default :
return null;
}
}
|
python
|
def encodeEntities(self, input):
"""TODO: remove xmlEncodeEntities, once we are not afraid of
breaking binary compatibility People must migrate their
code to xmlEncodeEntitiesReentrant ! This routine will
issue a warning when encountered. """
ret = libxml2mod.xmlEncodeEntities(self._o, input)
return ret
|
java
|
public <V> NavigableMap<T, V> toNavigableMap(Function<? super T, ? extends V> valMapper) {
return toNavigableMap(Function.identity(), valMapper);
}
|
java
|
public SoapClient setParam(String name, Object value) {
return setParam(name, value, true);
}
|
java
|
@Override
public void sawOpcode(int seen) {
String userValue = null;
try {
stack.precomputation(this);
int pc = getPC();
if (branchTargets.get(pc)) {
localMethodCalls.clear();
fieldMethodCalls.clear();
branchTargets.clear(pc);
}
if (((seen >= Const.IFEQ) && (seen <= Const.GOTO)) || ((seen >= Const.IFNULL) && (seen <= Const.GOTO_W))) {
branchTargets.set(getBranchTarget());
} else if ((seen == Const.TABLESWITCH) || (seen == Const.LOOKUPSWITCH)) {
int[] offsets = getSwitchOffsets();
for (int offset : offsets) {
branchTargets.set(offset + pc);
}
branchTargets.set(getDefaultSwitchOffset() + pc);
} else if (OpcodeUtils.isAStore(seen)) {
localMethodCalls.remove(Integer.valueOf(RegisterUtils.getAStoreReg(this, seen)));
} else if (seen == Const.PUTFIELD) {
String fieldSource = "";
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
fieldSource = (String) item.getUserValue();
if (fieldSource == null) {
fieldSource = "";
}
}
fieldMethodCalls.remove(new FieldInfo(fieldSource, getNameConstantOperand()));
} else if (seen == Const.GETFIELD) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
userValue = (String) item.getUserValue();
if (userValue == null) {
int reg = item.getRegisterNumber();
if (reg >= 0) {
userValue = String.valueOf(reg);
} else {
XField xf = item.getXField();
if (xf != null) {
userValue = xf.getName();
}
}
}
}
} else if ((seen == Const.INVOKEVIRTUAL) || (seen == Const.INVOKEINTERFACE)
|| (seen == Const.INVOKESTATIC)) {
String className = getClassConstantOperand();
String methodName = getNameConstantOperand();
String signature = getSigConstantOperand();
int parmCount = SignatureUtils.getNumParameters(signature);
int reg = -1;
XField field = null;
MethodCall mc = null;
String fieldSource = null;
if (seen == Const.INVOKESTATIC) {
XMethod xm = XFactory.createXMethod(getDottedClassConstantOperand(), methodName, signature, true);
String genericSignature = xm.getSourceSignature();
if ((genericSignature != null) && genericSignature.endsWith(">;")) {
return;
}
} else if (stack.getStackDepth() > parmCount) {
OpcodeStack.Item obj = stack.getStackItem(parmCount);
reg = obj.getRegisterNumber();
field = obj.getXField();
if (reg >= 0) {
mc = localMethodCalls.get(Integer.valueOf(reg));
MethodInfo mi = Statistics.getStatistics().getMethodStatistics(className,
getNameConstantOperand(), signature);
if ((mi != null) && mi.getModifiesState()) {
clearFieldMethods(String.valueOf(reg));
return;
}
} else if (field != null) {
fieldSource = (String) obj.getUserValue();
if (fieldSource == null) {
fieldSource = "";
}
mc = fieldMethodCalls.get(new FieldInfo(fieldSource, field.getName()));
MethodInfo mi = Statistics.getStatistics().getMethodStatistics(className,
getNameConstantOperand(), signature);
if ((mi != null) && mi.getModifiesState()) {
clearFieldMethods(fieldSource);
return;
}
}
}
int neededStackSize = parmCount + ((seen == Const.INVOKESTATIC) ? 0 : 1);
if (stack.getStackDepth() >= neededStackSize) {
Object[] parmConstants = new Object[parmCount];
for (int i = 0; i < parmCount; i++) {
OpcodeStack.Item parm = stack.getStackItem(i);
parmConstants[i] = parm.getConstant();
if (parm.getSignature().startsWith(Values.SIG_ARRAY_PREFIX)) {
if (!Values.ZERO.equals(parm.getConstant())) {
return;
}
XField f = parm.getXField();
if (f != null) {
// Two different fields holding a 0 length array should be considered different
parmConstants[i] = f.getName() + ':' + parmConstants[i];
}
}
if (parmConstants[i] == null) {
return;
}
}
if (seen == Const.INVOKESTATIC) {
mc = staticMethodCalls.get(className);
} else if ((reg < 0) && (field == null)) {
return;
}
if (mc != null) {
if (!signature.endsWith(Values.SIG_VOID) && methodName.equals(mc.getName())
&& signature.equals(mc.getSignature()) && !isRiskyName(className, methodName)
&& !commonMethods.contains(new FQMethod(className, methodName, signature))) {
Object[] parms = mc.getParms();
if (Arrays.equals(parms, parmConstants)) {
int ln = getLineNumber(pc);
if ((ln != mc.getLineNumber()) || (Math.abs(pc - mc.getPC()) < 10)) {
Statistics statistics = Statistics.getStatistics();
MethodInfo mi = statistics.getMethodStatistics(className, methodName, signature);
bugReporter.reportBug(
new BugInstance(this, BugType.PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS.name(),
getBugPriority(methodName, mi)).addClass(this).addMethod(this)
.addSourceLine(this).addString(methodName + signature));
}
}
}
if (seen == Const.INVOKESTATIC) {
staticMethodCalls.remove(className);
} else {
if (reg >= 0) {
localMethodCalls.remove(Integer.valueOf(reg));
} else if (fieldSource != null) {
fieldMethodCalls.remove(new FieldInfo(fieldSource, field.getName()));
}
}
} else {
int ln = getLineNumber(pc);
if (seen == Const.INVOKESTATIC) {
staticMethodCalls.put(className,
new MethodCall(methodName, signature, parmConstants, pc, ln));
} else {
if (reg >= 0) {
localMethodCalls.put(Integer.valueOf(reg),
new MethodCall(methodName, signature, parmConstants, pc, ln));
} else if (field != null) {
OpcodeStack.Item obj = stack.getStackItem(parmCount);
fieldSource = (String) obj.getUserValue();
if (fieldSource == null) {
fieldSource = "";
}
fieldMethodCalls.put(new FieldInfo(fieldSource, field.getName()),
new MethodCall(methodName, signature, parmConstants, pc, ln));
}
}
}
}
} else if (OpcodeUtils.isReturn(seen)) {
localMethodCalls.clear();
fieldMethodCalls.clear();
branchTargets.clear(pc);
}
} finally {
stack.sawOpcode(this, seen);
if ((userValue != null) && (stack.getStackDepth() > 0)) {
OpcodeStack.Item item = stack.getStackItem(0);
item.setUserValue(userValue);
}
}
}
|
java
|
public boolean isValidGenericTld(String gTld) {
final String key = chompLeadingDot(unicodeToASCII(gTld).toLowerCase(Locale.ENGLISH));
return (arrayContains(GENERIC_TLDS, key) || arrayContains(genericTLDsPlus, key))
&& !arrayContains(genericTLDsMinus, key);
}
|
python
|
def remove_dirs(self, directory):
"""Delete a directory recursively.
:param directory: $PATH to directory.
:type directory: ``str``
"""
LOG.info('Removing directory [ %s ]', directory)
local_files = self._drectory_local_files(directory=directory)
for file_name in local_files:
try:
os.remove(file_name['local_object'])
except OSError as exp:
LOG.error(str(exp))
# Build a list of all local directories
directories = sorted(
[i for i, _, _ in os.walk(directory)],
reverse=True
)
# Remove directories
for directory_path in directories:
try:
os.removedirs(directory_path)
except OSError as exp:
if exp.errno != 2:
LOG.error(str(exp))
pass
|
java
|
@Override
public CPDefinition fetchByC_S_First(long CProductId, int status,
OrderByComparator<CPDefinition> orderByComparator) {
List<CPDefinition> list = findByC_S(CProductId, status, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
|
java
|
private String escapeCodeText(String text) {
String lowerText = text.toLowerCase();
int preStart = lowerText.indexOf("<pre>");
int preEnd = lowerText.indexOf("</pre>");
if (preStart == -1 && preEnd == -1) {
return text;
}
if (preStart >= 0 && preEnd >= 0 && preEnd < preStart) {
// Bad code formatting, don't try to escape.
return text;
}
// Separately test begin and end tags, to support a span with multiple Javadoc tags.
StringBuilder sb = new StringBuilder();
if (preStart > -1 && preEnd > -1) {
// Both <pre> and </pre> are in the same text segment.
sb.append(text.substring(0, preStart));
if (preStart > 0) {
sb.append('\n');
}
sb.append("@code\n");
sb.append(text.substring(preStart + "<pre>".length(), preEnd));
sb.append("\n@endcode");
sb.append(text.substring(preEnd + "</pre>".length()));
} else if (preStart > -1) {
// The text has <pre> but not the </pre> should be in a following Javadoc tag.
sb.append(text.substring(0, preStart));
if (preStart > 0) {
sb.append('\n');
}
sb.append("@code\n");
sb.append(text.substring(preStart + "<pre>".length()));
spanningPreTag = true;
} else {
// The text just has a </pre>.
sb.append("\n@endcode");
sb.append(text.substring(preEnd + "</pre>".length()));
spanningPreTag = false;
}
return escapeCodeText(sb.toString()); // Allow for multiple <pre> spans in single text element.
}
|
java
|
public OutputStream create(String src,
FsPermission permission,
boolean overwrite,
boolean createParent,
short replication,
long blockSize,
Progressable progress,
int buffersize
) throws IOException {
return create(src, permission, overwrite, createParent, replication, blockSize,
progress, buffersize, conf.getInt("io.bytes.per.checksum", 512));
}
|
java
|
private void notifyOnPreferenceFragmentShown(
@NonNull final NavigationPreference navigationPreference,
@NonNull final Fragment fragment) {
for (PreferenceFragmentListener listener : preferenceFragmentListeners) {
listener.onPreferenceFragmentShown(navigationPreference, fragment);
}
}
|
python
|
def get_nadir(self, channel=0) -> tuple:
"""Get the coordinates, in units, of the minimum in a channel.
Parameters
----------
channel : int or str (optional)
Channel. Default is 0.
Returns
-------
generator of numbers
Coordinates in units for each axis.
"""
# get channel
if isinstance(channel, int):
channel_index = channel
elif isinstance(channel, str):
channel_index = self.channel_names.index(channel)
else:
raise TypeError("channel: expected {int, str}, got %s" % type(channel))
channel = self.channels[channel_index]
# get indicies
idx = channel.argmin()
# finish
return tuple(a[idx] for a in self._axes)
|
python
|
def attach_process_classic(self, command_or_pid_path, background, control=False, for_legion=False):
"""Attaches a command/daemon to the master process optionally managed by a pidfile.
This will allow the uWSGI master to control/monitor/respawn this process.
.. note:: This uses old classic uWSGI means of process attaching
To have more control use ``.attach_process()`` method (requires uWSGI 2.0+)
http://uwsgi-docs.readthedocs.io/en/latest/AttachingDaemons.html
:param str|unicode command_or_pid_path:
:param bool background: Must indicate whether process is in background.
:param bool control: Consider this process a control: when the daemon dies, the master exits.
.. note:: pidfile managed processed not supported.
:param bool for_legion: Legion daemons will be executed only on the legion lord node,
so there will always be a single daemon instance running in each legion.
Once the lord dies a daemon will be spawned on another node.
.. note:: uWSGI 1.9.9+ required.
"""
prefix = 'legion-' if for_legion else ''
if '.pid' in command_or_pid_path:
if background:
# Attach a command/daemon to the master process managed by a pidfile (the command must daemonize)
self._set(prefix + 'smart-attach-daemon', command_or_pid_path, multi=True)
else:
# Attach a command/daemon to the master process managed by a pidfile (the command must NOT daemonize)
self._set(prefix + 'smart-attach-daemon2', command_or_pid_path, multi=True)
else:
if background:
raise ConfigurationError('Background flag is only supported for pid-governed commands')
if control:
# todo needs check
self._set('attach-control-daemon', command_or_pid_path, multi=True)
else:
# Attach a command/daemon to the master process (the command has to remain in foreground)
self._set(prefix + 'attach-daemon', command_or_pid_path, multi=True)
return self._section
|
python
|
def process_view(self, request, view_func, view_args, view_kwargs):
"""
Per-request mechanics for the current page object.
"""
# Load the closest matching page by slug, and assign it to the
# request object. If none found, skip all further processing.
slug = path_to_slug(request.path_info)
pages = Page.objects.with_ascendants_for_slug(slug,
for_user=request.user, include_login_required=True)
if pages:
page = pages[0]
setattr(request, "page", page)
context_processors.page(request)
else:
return
# Handle ``page.login_required``.
if page.login_required and not request.user.is_authenticated():
return redirect_to_login(request.get_full_path())
# If the view isn't yacms's page view, try to return the result
# immediately. In the case of a 404 with an URL slug that matches a
# page exactly, swallow the exception and try yacms's page view.
#
# This allows us to set up pages with URLs that also match non-page
# urlpatterns. For example, a page could be created with the URL
# /blog/about/, which would match the blog urlpattern, and assuming
# there wasn't a blog post with the slug "about", would raise a 404
# and subsequently be rendered by yacms's page view.
if view_func != page_view:
try:
return view_func(request, *view_args, **view_kwargs)
except Http404:
if page.slug != slug:
raise
# Run page processors.
extra_context = {}
model_processors = page_processors.processors[page.content_model]
slug_processors = page_processors.processors["slug:%s" % page.slug]
for (processor, exact_page) in slug_processors + model_processors:
if exact_page and not page.is_current:
continue
processor_response = processor(request, page)
if isinstance(processor_response, HttpResponse):
return processor_response
elif processor_response:
try:
for k, v in processor_response.items():
if k not in extra_context:
extra_context[k] = v
except (TypeError, ValueError):
name = "%s.%s" % (processor.__module__, processor.__name__)
error = ("The page processor %s returned %s but must "
"return HttpResponse or dict." %
(name, type(processor_response)))
raise ValueError(error)
return page_view(request, slug, extra_context=extra_context)
|
python
|
def get_activation_key(self, user):
"""
Generate the activation key which will be emailed to the user.
"""
return signing.dumps(
obj=getattr(user, user.USERNAME_FIELD),
salt=self.key_salt
)
|
java
|
private void generateDelete(SQLiteDatabaseSchema schema) {
MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("delete").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(Integer.TYPE);
methodBuilder.addParameter(Uri.class, "uri");
methodBuilder.addParameter(String.class, "selection");
methodBuilder.addParameter(ParameterSpec.builder(TypeUtility.arrayTypeName(String.class), "selectionArgs").build());
boolean hasOperation = hasOperationOfType(schema, methodBuilder, JQLType.DELETE);
if (!hasOperation) {
methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.DELETE);
classBuilder.addMethod(methodBuilder.build());
return;
}
methodBuilder.addStatement("int returnRowDeleted=-1");
methodBuilder.beginControlFlow("switch (sURIMatcher.match(uri))");
defineJavadocHeaderForContentOperation(methodBuilder, "delete");
for (Entry<String, ContentEntry> item : uriSet.entrySet()) {
if (item.getValue().delete == null)
continue;
defineJavadocForContentUri(methodBuilder, item.getValue().delete);
// methodBuilder.addJavadoc("uri $L\n", item.getKey());
methodBuilder.beginControlFlow("case $L:", item.getValue().pathIndex);
methodBuilder.addCode("// URI: $L\n", item.getValue().delete.contentProviderUri());
methodBuilder.addStatement("returnRowDeleted=dataSource.get$L().$L(uri, selection, selectionArgs)", item.getValue().delete.getParent().getName(),
item.getValue().delete.contentProviderMethodName);
methodBuilder.addStatement("break");
methodBuilder.endControlFlow();
}
defineJavadocFooterForContentOperation(methodBuilder);
methodBuilder.beginControlFlow("default:");
methodBuilder.addStatement("throw new $T(\"Unknown URI for $L operation: \" + uri)", IllegalArgumentException.class, JQLType.DELETE);
methodBuilder.endControlFlow();
methodBuilder.endControlFlow();
if (hasOperation) {
if (schema.generateLog) {
// generate log section - BEGIN
methodBuilder.addComment("log section for content provider delete BEGIN");
methodBuilder.beginControlFlow("if (dataSource.isLogEnabled())");
methodBuilder.addStatement("$T.info(\"Changes are notified for URI %s\", uri)", Logger.class);
// generate log section - END
methodBuilder.endControlFlow();
methodBuilder.addComment("log section for content provider delete END");
}
methodBuilder.addStatement("getContext().getContentResolver().notifyChange(uri, null)");
}
methodBuilder.addCode("return returnRowDeleted;\n");
classBuilder.addMethod(methodBuilder.build());
}
|
python
|
def get_uncompleted_tasks(self):
"""Return all of a user's uncompleted tasks.
.. warning:: Requires Todoist premium.
:return: A list of uncompleted tasks.
:rtype: list of :class:`pytodoist.todoist.Task`
>>> from pytodoist import todoist
>>> user = todoist.login('[email protected]', 'password')
>>> uncompleted_tasks = user.get_uncompleted_tasks()
>>> for task in uncompleted_tasks:
... task.complete()
"""
tasks = (p.get_uncompleted_tasks() for p in self.get_projects())
return list(itertools.chain.from_iterable(tasks))
|
python
|
def iter_user_repos(login, type=None, sort=None, direction=None, number=-1,
etag=None):
"""List public repositories for the specified ``login``.
.. versionadded:: 0.6
.. note:: This replaces github3.iter_repos
:param str login: (required)
:param str type: (optional), accepted values:
('all', 'owner', 'member')
API default: 'all'
:param str sort: (optional), accepted values:
('created', 'updated', 'pushed', 'full_name')
API default: 'created'
:param str direction: (optional), accepted values:
('asc', 'desc'), API default: 'asc' when using 'full_name',
'desc' otherwise
:param int number: (optional), number of repositories to return.
Default: -1 returns all repositories
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of :class:`Repository <github3.repos.Repository>`
objects
"""
if login:
return gh.iter_user_repos(login, type, sort, direction, number, etag)
return iter([])
|
python
|
def setEncoder(self, encoder):
"""
Sets the client's encoder
``encoder`` should be an instance of a ``json.JSONEncoder`` class
"""
if not encoder:
self._encoder = json.JSONEncoder()
else:
self._encoder = encoder
self._encode = self._encoder.encode
|
java
|
@Override
public void play()
{
final String name = media.getPath();
if (Medias.getResourcesLoader().isPresent())
{
if (cache == null)
{
cache = extractFromJar(media);
}
play(cache, name);
}
else
{
play(media.getFile().getAbsolutePath(), name);
}
}
|
java
|
public final void transliterate(Replaceable text, Position index,
int insertion) {
transliterate(text, index, UTF16.valueOf(insertion));
}
|
python
|
def __process_warc_gz_file(self, path_name):
"""
Iterates all transactions in one WARC file and for each transaction tries to extract an article object.
Afterwards, each article is checked against the filter criteria and if all are passed, the function
on_valid_article_extracted is invoked with the article object.
:param path_name:
:return:
"""
counter_article_total = 0
counter_article_passed = 0
counter_article_discarded = 0
start_time = time.time()
with open(path_name, 'rb') as stream:
for record in ArchiveIterator(stream):
# try:
if record.rec_type == 'response':
counter_article_total += 1
# if the article passes filter tests, we notify the user
filter_pass, article = self.__filter_record(record)
if filter_pass:
counter_article_passed += 1
if not article:
article = NewsPlease.from_warc(record)
self.__logger.info('article pass (%s; %s; %s)', article.source_domain, article.date_publish,
article.title)
self.__callback_on_article_extracted(article)
else:
counter_article_discarded += 1
if article:
self.__logger.info('article discard (%s; %s; %s)', article.source_domain,
article.date_publish,
article.title)
else:
self.__logger.info('article discard (%s)',
record.rec_headers.get_header('WARC-Target-URI'))
if counter_article_total % 10 == 0:
elapsed_secs = time.time() - start_time
secs_per_article = elapsed_secs / counter_article_total
self.__logger.info('statistics')
self.__logger.info('pass = %i, discard = %i, total = %i', counter_article_passed,
counter_article_discarded, counter_article_total)
self.__logger.info('extraction from current WARC file started %s; %f s/article',
human(start_time), secs_per_article)
# except:
# if self.__continue_after_error:
# self.__logger.error('Unexpected error: %s', sys.exc_info()[0])
# pass
# else:
# raise
# cleanup
if self.__delete_warc_after_extraction:
os.remove(path_name)
self.__register_fully_extracted_warc_file(self.__warc_download_url)
|
python
|
def del_contact_downtime(self, downtime_id):
"""Delete a contact downtime
Format of the line that triggers function call::
DEL_CONTACT_DOWNTIME;<downtime_id>
:param downtime_id: downtime id to delete
:type downtime_id: int
:return: None
"""
for item in self.daemon.contacts:
if downtime_id in item.downtimes:
item.downtimes[downtime_id].cancel(self.daemon.contacts)
break
else:
self.send_an_element(make_monitoring_log(
'warning', 'DEL_CONTACT_DOWNTIME: downtime id: %s does not exist '
'and cannot be deleted.' % downtime_id))
|
java
|
private CmsSearchWorkplaceBean getSearchParams() {
if ((m_searchParams == null) && (getSettings().getDialogObject() instanceof Map<?, ?>)) {
Map<?, ?> dialogObject = (Map<?, ?>)getSettings().getDialogObject();
if (dialogObject.get(CmsSearchDialog.class.getName()) instanceof CmsSearchWorkplaceBean) {
m_searchParams = (CmsSearchWorkplaceBean)dialogObject.get(CmsSearchDialog.class.getName());
}
}
return m_searchParams;
}
|
python
|
def get_tasklogger(name="TaskLogger"):
"""Get a TaskLogger object
Parameters
----------
logger : str, optional (default: "TaskLogger")
Unique name of the logger to retrieve
Returns
-------
logger : TaskLogger
"""
try:
return logging.getLogger(name).tasklogger
except AttributeError:
return logger.TaskLogger(name)
|
java
|
@Override
public T doDeserialize( JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params ) {
// Processing the parameters. We fallback to default if parameter is not present.
final IdentityDeserializationInfo identityInfo = null == params.getIdentityInfo() ? defaultIdentityInfo : params.getIdentityInfo();
final TypeDeserializationInfo typeInfo = null == params.getTypeInfo() ? defaultTypeInfo : params.getTypeInfo();
JsonToken token = reader.peek();
// If it's not a json object or array, it must be an identifier
if ( null != identityInfo && !JsonToken.BEGIN_OBJECT.equals( token ) && !JsonToken.BEGIN_ARRAY.equals( token ) ) {
Object id;
if ( identityInfo.isProperty() ) {
HasDeserializerAndParameters propertyDeserializer = deserializers.get( identityInfo.getPropertyName() );
if ( null == propertyDeserializer ) {
propertyDeserializer = instanceBuilder.getParametersDeserializer().get( identityInfo.getPropertyName() );
}
id = propertyDeserializer.getDeserializer().deserialize( reader, ctx );
} else {
id = identityInfo.readId( reader, ctx );
}
Object instance = ctx.getObjectWithId( identityInfo.newIdKey( id ) );
if ( null == instance ) {
throw ctx.traceError( "Cannot find an object with id " + id, reader );
}
return (T) instance;
}
T result;
if ( null != typeInfo ) {
As include;
if ( JsonToken.BEGIN_ARRAY.equals( token ) ) {
// we can have a wrapper array even if the user specified As.PROPERTY in some cases (enum, creator delegation)
include = As.WRAPPER_ARRAY;
} else {
include = typeInfo.getInclude();
}
switch ( include ) {
case PROPERTY:
// the type info is the first property of the object
reader.beginObject();
Map<String, String> bufferedProperties = null;
String typeInfoProperty = null;
while ( JsonToken.NAME.equals( reader.peek() ) ) {
String name = reader.nextName();
if ( typeInfo.getPropertyName().equals( name ) ) {
typeInfoProperty = reader.nextString();
break;
} else {
if ( null == bufferedProperties ) {
bufferedProperties = new HashMap<String, String>();
}
bufferedProperties.put( name, reader.nextValue() );
}
}
if ( null == typeInfoProperty ) {
throw ctx.traceError( "Cannot find the property " + typeInfo
.getPropertyName() + " containing the type information", reader );
}
result = getDeserializer( reader, ctx, typeInfo, typeInfoProperty )
.deserializeInline( reader, ctx, params, identityInfo, typeInfo, typeInfoProperty, bufferedProperties );
reader.endObject();
break;
case WRAPPER_OBJECT:
// type info is included in a wrapper object that contains only one property. The name of this property is the type
// info and the value the object
reader.beginObject();
String typeInfoWrapObj = reader.nextName();
result = getDeserializer( reader, ctx, typeInfo, typeInfoWrapObj )
.deserializeWrapped( reader, ctx, params, identityInfo, typeInfo, typeInfoWrapObj );
reader.endObject();
break;
case WRAPPER_ARRAY:
// type info is included in a wrapper array that contains two elements. First one is the type
// info and the second one the object
reader.beginArray();
String typeInfoWrapArray = reader.nextString();
result = getDeserializer( reader, ctx, typeInfo, typeInfoWrapArray )
.deserializeWrapped( reader, ctx, params, identityInfo, typeInfo, typeInfoWrapArray );
reader.endArray();
break;
default:
throw ctx.traceError( "JsonTypeInfo.As." + typeInfo.getInclude() + " is not supported", reader );
}
} else if ( canDeserialize() ) {
result = deserializeWrapped( reader, ctx, params, identityInfo, null, null );
} else {
throw ctx.traceError( "Cannot instantiate the type " + getDeserializedType().getName(), reader );
}
return result;
}
|
java
|
public void insertRule(final String rule, final int index) throws DOMException {
try {
final CSSOMParser parser = new CSSOMParser();
parser.setParentStyleSheet(this);
parser.setErrorHandler(ThrowCssExceptionErrorHandler.INSTANCE);
final AbstractCSSRuleImpl r = parser.parseRule(rule);
if (r == null) {
// this should neven happen because of the ThrowCssExceptionErrorHandler
throw new DOMExceptionImpl(
DOMException.SYNTAX_ERR,
DOMExceptionImpl.SYNTAX_ERROR,
"Parsing rule '" + rule + "' failed.");
}
if (getCssRules().getLength() > 0) {
// We need to check that this type of rule can legally go into
// the requested position.
int msg = -1;
if (r instanceof CSSCharsetRuleImpl) {
// Index must be 0, and there can be only one charset rule
if (index != 0) {
msg = DOMExceptionImpl.CHARSET_NOT_FIRST;
}
else if (getCssRules().getRules().get(0) instanceof CSSCharsetRuleImpl) {
msg = DOMExceptionImpl.CHARSET_NOT_UNIQUE;
}
}
else if (r instanceof CSSImportRuleImpl) {
// Import rules must preceed all other rules (except
// charset rules)
if (index <= getCssRules().getLength()) {
for (int i = 0; i < index; i++) {
final AbstractCSSRuleImpl ri = getCssRules().getRules().get(i);
if (!(ri instanceof CSSCharsetRuleImpl) && !(ri instanceof CSSImportRuleImpl)) {
msg = DOMExceptionImpl.IMPORT_NOT_FIRST;
break;
}
}
}
}
else {
if (index <= getCssRules().getLength()) {
for (int i = index; i < getCssRules().getLength(); i++) {
final AbstractCSSRuleImpl ri = getCssRules().getRules().get(i);
if ((ri instanceof CSSCharsetRuleImpl) || (ri instanceof CSSImportRuleImpl)) {
msg = DOMExceptionImpl.INSERT_BEFORE_IMPORT;
break;
}
}
}
}
if (msg > -1) {
throw new DOMExceptionImpl(DOMException.HIERARCHY_REQUEST_ERR, msg);
}
}
// Insert the rule into the list of rules
getCssRules().insert(r, index);
}
catch (final IndexOutOfBoundsException e) {
throw new DOMExceptionImpl(
DOMException.INDEX_SIZE_ERR,
DOMExceptionImpl.INDEX_OUT_OF_BOUNDS,
e.getMessage());
}
catch (final CSSException e) {
throw new DOMExceptionImpl(
DOMException.SYNTAX_ERR,
DOMExceptionImpl.SYNTAX_ERROR,
e.getMessage());
}
catch (final IOException e) {
throw new DOMExceptionImpl(
DOMException.SYNTAX_ERR,
DOMExceptionImpl.SYNTAX_ERROR,
e.getMessage());
}
}
|
java
|
public void init()
{
LOG.info("Scanning esjps for REST implementations");
try {
if (!Context.isThreadActive()) {
Context.begin(null, Context.Inheritance.Local);
Context.getThreadContext().setRequestAttribute(CONTEXTHINT, true);
}
registerClasses(new EsjpScanner().scan(Path.class, Provider.class));
} catch (final EFapsException e) {
LOG.error("Catched EFapsException", e);
}
registerClasses(Compile.class);
registerClasses(Update.class);
registerClasses(RestEQLInvoker.class);
registerClasses(RestContext.class);
registerClasses(Search.class);
registerClasses(ObjectMapperResolver.class);
if (EFapsResourceConfig.LOG.isInfoEnabled() && !getClasses().isEmpty()) {
final Set<Class<?>> rootResourceClasses = get(Path.class);
if (rootResourceClasses.isEmpty()) {
EFapsResourceConfig.LOG.info("No root resource classes found.");
} else {
logClasses("Root resource classes found:", rootResourceClasses);
}
final Set<Class<?>> providerClasses = get(Provider.class);
if (providerClasses.isEmpty()) {
EFapsResourceConfig.LOG.info("No provider classes found.");
} else {
logClasses("Provider classes found:", providerClasses);
}
}
this.cachedClasses.clear();
this.cachedClasses.addAll(getClasses());
}
|
python
|
def cls_slots(self, cls: CLASS_OR_CLASSNAME) -> List[SlotDefinition]:
""" Return the list of slots directly included in the class definition. Includes slots whose
domain is cls -- as declared in slot.domain or class.slots
Does not include slots declared in mixins, apply_to or is_a links
@param cls: class name or class definition name
@return: all direct class slots
"""
if not isinstance(cls, ClassDefinition):
cls = self.schema.classes[cls]
return [self.schema.slots[s] for s in cls.slots]
|
python
|
def _get_journal():
'''
Return the active running journal object
'''
if 'systemd.journald' in __context__:
return __context__['systemd.journald']
__context__['systemd.journald'] = systemd.journal.Reader()
# get to the end of the journal
__context__['systemd.journald'].seek_tail()
__context__['systemd.journald'].get_previous()
return __context__['systemd.journald']
|
python
|
def chat_update_message(self, channel, text, timestamp, **params):
"""chat.update
This method updates a message.
Required parameters:
`channel`: Channel containing the message to be updated. (e.g: "C1234567890")
`text`: New text for the message, using the default formatting rules. (e.g: "Hello world")
`timestamp`: Timestamp of the message to be updated (e.g: "1405894322.002768")
https://api.slack.com/methods/chat.update
"""
method = 'chat.update'
if self._channel_is_name(channel):
# chat.update only takes channel ids (not channel names)
channel = self.channel_name_to_id(channel)
params.update({
'channel': channel,
'text': text,
'ts': timestamp,
})
return self._make_request(method, params)
|
java
|
public EClass getGSLT() {
if (gsltEClass == null) {
gsltEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(476);
}
return gsltEClass;
}
|
python
|
def notChainStr (states, s):
"""XXX I'm not sure this is how it should be done, but I'm going to
try it anyway. Note that for this case, I require only single character
arcs, since I would have to basically invert all accepting states and
non-accepting states of any sub-NFA's.
"""
assert len(s) > 0
arcs = list(map(lambda x : newArcPair(states, x), s))
finish = len(states)
states.append([])
start, lastFinish = arcs[0]
states[start].append((EMPTY, finish))
for crntStart, crntFinish in arcs[1:]:
states[lastFinish].append((EMPTY, crntStart))
states[crntStart].append((EMPTY, finish))
return start, finish
|
java
|
private CompositeExpression parseWildcardRange() {
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(0, 0, 0));
}
int major = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
if (tokens.positiveLookahead(WILDCARD)) {
tokens.consume();
return gte(versionFor(major)).and(lt(versionFor(major + 1)));
}
int minor = intOf(consumeNextToken(NUMERIC).lexeme);
consumeNextToken(DOT);
consumeNextToken(WILDCARD);
return gte(versionFor(major, minor)).and(lt(versionFor(major, minor + 1)));
}
|
java
|
public void grow(float h, float v) {
setX(getX() - h);
setY(getY() - v);
setWidth(getWidth() + (h*2));
setHeight(getHeight() + (v*2));
}
|
java
|
@Deprecated
public void setPrimaryKeys(String... primaryKeyFieldName) {
setProp(ConfigurationKeys.EXTRACT_PRIMARY_KEY_FIELDS_KEY, Joiner.on(",").join(primaryKeyFieldName));
}
|
java
|
@Override
public boolean encode(long[] current, long[] next) {
boolean configured = false;
for (int i = unconfigured.nextSetBit(0); i >= 0; i = unconfigured.nextSetBit(i + 1)) {
if (encoders.get(i).encode(current, next)) {
unconfigured.clear(i); // don't configure again (unless reset)
configured = true;
}
}
return configured;
}
|
python
|
def add_io_macro(self,io,filename):
"""
Add a variable (macro) for storing the input/output files associated
with this node.
@param io: macroinput or macrooutput
@param filename: filename of input/output file
"""
io = self.__bad_macro_chars.sub( r'', io )
if io not in self.__opts:
self.__opts[io] = filename
else:
if filename not in self.__opts[io]:
self.__opts[io] += ',%s' % filename
|
java
|
public void update(PeerState state, long uploaded, long downloaded,
long left) {
if (PeerState.STARTED.equals(state) && left == 0) {
state = PeerState.COMPLETED;
}
if (!state.equals(this.state)) {
logger.trace("Peer {} {} download of {}.",
new Object[]{
this,
state.name().toLowerCase(),
this.torrent,
});
}
this.state = state;
this.lastAnnounce = myTimeService.now();
this.uploaded = uploaded;
this.downloaded = downloaded;
this.left = left;
}
|
java
|
public List<MwDumpFile> findAllRelevantRevisionDumps(boolean preferCurrent) {
MwDumpFile mainDump;
if (preferCurrent) {
mainDump = findMostRecentDump(DumpContentType.CURRENT);
} else {
mainDump = findMostRecentDump(DumpContentType.FULL);
}
if (mainDump == null) {
return findAllDumps(DumpContentType.DAILY);
}
List<MwDumpFile> result = new ArrayList<>();
for (MwDumpFile dumpFile : findAllDumps(DumpContentType.DAILY)) {
if (dumpFile.getDateStamp().compareTo(mainDump.getDateStamp()) > 0) {
result.add(dumpFile);
}
}
result.add(mainDump);
if (logger.isInfoEnabled()) {
StringBuilder logMessage = new StringBuilder();
logMessage.append("Found ")
.append(result.size())
.append(" relevant dumps to process:");
for (MwDumpFile dumpFile : result) {
logMessage.append("\n * ").append(dumpFile.toString());
}
logger.info(logMessage.toString());
}
return result;
}
|
java
|
public static List<CmsResource> getDetailOnlyResources(CmsObject cms, CmsResource resource) {
List<CmsResource> result = new ArrayList<CmsResource>();
Set<String> resourcePaths = new HashSet<String>();
String sitePath = cms.getSitePath(resource);
for (Locale locale : OpenCms.getLocaleManager().getAvailableLocales()) {
resourcePaths.add(getDetailOnlyPageNameWithoutLocaleCheck(sitePath, locale.toString()));
}
// in case the deprecated locale less detail container resource exists
resourcePaths.add(getDetailOnlyPageNameWithoutLocaleCheck(sitePath, null));
// add the locale independent detail container resource
resourcePaths.add(getDetailOnlyPageNameWithoutLocaleCheck(sitePath, LOCALE_ALL));
for (String path : resourcePaths) {
try {
CmsResource detailContainers = cms.readResource(path, CmsResourceFilter.IGNORE_EXPIRATION);
result.add(detailContainers);
} catch (CmsException e) {
// will happen in case resource does not exist, ignore
}
}
return result;
}
|
java
|
public TypeMetadata without(Entry.Kind kind) {
if (this == EMPTY || contents.get(kind) == null)
return this;
TypeMetadata out = new TypeMetadata(this);
out.contents.remove(kind);
return out.contents.isEmpty() ? EMPTY : out;
}
|
python
|
def _init_metadata(self):
"""stub"""
super(PDFPreviewFormRecord, self)._init_metadata()
self._preview_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'file'),
'element_label': 'File',
'instructions': 'accepts an Asset Id',
'required': True,
'read_only': False,
'linked': False,
'array': False,
'default_id_values': [''],
'syntax': 'ID',
'id_set': []
}
|
java
|
public static MozuUrl removeDestinationUrl(String checkoutId, String destinationId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/checkouts/{checkoutId}/destinations/{destinationId}");
formatter.formatUrl("checkoutId", checkoutId);
formatter.formatUrl("destinationId", destinationId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
}
|
java
|
public Observable<ServiceResponse<Void>> checkNameAvailabilityWithServiceResponseAsync(CheckNameAvailabilityParameters parameters) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
}
Validator.validate(parameters);
return service.checkNameAvailability(this.client.subscriptionId(), parameters, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = checkNameAvailabilityDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
|
python
|
def CDSReader( fh, format='gff' ):
""" yield chrom, strand, cds_exons, name """
known_formats = ( 'gff', 'gtf', 'bed')
if format not in known_formats:
print('%s format not in %s' % (format, ",".join( known_formats )), file=sys.stderr)
raise Exception('?')
if format == 'bed':
for line in fh:
f = line.strip().split()
chrom = f[0]
chrom_start = int(f[1])
name = f[4]
strand = f[5]
cdsStart = int(f[6])
cdsEnd = int(f[7])
blockCount = int(f[9])
blockSizes = [ int(i) for i in f[10].strip(',').split(',') ]
blockStarts = [ chrom_start + int(i) for i in f[11].strip(',').split(',') ]
# grab cdsStart - cdsEnd
cds_exons = []
cds_seq = ''
genome_seq_index = []
for base,offset in zip( blockStarts, blockSizes ):
if (base + offset) < cdsStart: continue
if base > cdsEnd: continue
exon_start = max( base, cdsStart )
exon_end = min( base+offset, cdsEnd )
cds_exons.append( (exon_start, exon_end) )
yield chrom, strand, cds_exons, name
genelist = {}
grouplist = []
if format == 'gff' or format == 'gtf':
for line in fh:
if line.startswith('#'): continue
fields = line.strip().split('\t')
if len( fields ) < 9: continue
if fields[2] not in ('CDS', 'stop_codon', 'start_codon'): continue
# fields
chrom = fields[0]
ex_st = int( fields[3] ) - 1 # make zero-centered
ex_end = int( fields[4] ) #+ 1 # make exclusive
strand = fields[6]
if format == 'gtf':
group = fields[8].split(';')[0]
else:
group = fields[8]
if group not in grouplist: grouplist.append( group )
if group not in genelist:
genelist[group] = (chrom, strand, [])
genelist[group][2].append( ( ex_st, ex_end ) )
sp = lambda a,b: cmp( a[0], b[0] )
#for gene in genelist.values():
for gene in grouplist:
chrom, strand, cds_exons = genelist[ gene ]
seqlen = sum([ a[1]-a[0] for a in cds_exons ])
overhang = seqlen % 3
if overhang > 0:
#print >>sys.stderr, "adjusting ", gene
if strand == '+':
cds_exons[-1] = ( cds_exons[-1][0], cds_exons[-1][1] - overhang )
else:
cds_exons[0] = ( cds_exons[0][0] + overhang, cds_exons[0][1] )
cds_exons = bitset_union( cds_exons )
yield chrom, strand, cds_exons, gene
|
python
|
def _create_affine_siemens_mosaic(dicom_input):
"""
Function to create the affine matrix for a siemens mosaic dataset
This will work for siemens dti and 4d if in mosaic format
"""
# read dicom series with pds
dicom_header = dicom_input[0]
# Create affine matrix (http://nipy.sourceforge.net/nibabel/dicom/dicom_orientation.html#dicom-slice-affine)
image_orient1 = numpy.array(dicom_header.ImageOrientationPatient)[0:3]
image_orient2 = numpy.array(dicom_header.ImageOrientationPatient)[3:6]
normal = numpy.cross(image_orient1, image_orient2)
delta_r = float(dicom_header.PixelSpacing[0])
delta_c = float(dicom_header.PixelSpacing[1])
image_pos = dicom_header.ImagePositionPatient
delta_s = dicom_header.SpacingBetweenSlices
return numpy.array(
[[-image_orient1[0] * delta_c, -image_orient2[0] * delta_r, -delta_s * normal[0], -image_pos[0]],
[-image_orient1[1] * delta_c, -image_orient2[1] * delta_r, -delta_s * normal[1], -image_pos[1]],
[image_orient1[2] * delta_c, image_orient2[2] * delta_r, delta_s * normal[2], image_pos[2]],
[0, 0, 0, 1]])
|
java
|
public boolean isFinishing() {
final Iterator<ExecutionVertex> it = this.vertices.iterator();
while (it.hasNext()) {
final ExecutionState state = it.next().getExecutionState();
if (state != ExecutionState.FINISHING && state != ExecutionState.FINISHED) {
return false;
}
}
return true;
}
|
java
|
@Override
public UpdateServiceSpecificCredentialResult updateServiceSpecificCredential(UpdateServiceSpecificCredentialRequest request) {
request = beforeClientExecution(request);
return executeUpdateServiceSpecificCredential(request);
}
|
java
|
@SuppressWarnings("static-method")
protected ILaunchConfiguration chooseConfiguration(List<ILaunchConfiguration> configList) {
final IDebugModelPresentation labelProvider = DebugUITools.newDebugModelPresentation();
final ElementListSelectionDialog dialog = new ElementListSelectionDialog(getShell(), labelProvider);
dialog.setElements(configList.toArray());
dialog.setTitle(Messages.AbstractSarlLaunchShortcut_0);
dialog.setMessage(Messages.AbstractSarlLaunchShortcut_1);
dialog.setMultipleSelection(false);
final int result = dialog.open();
labelProvider.dispose();
if (result == Window.OK) {
return (ILaunchConfiguration) dialog.getFirstResult();
}
return null;
}
|
python
|
def _normalize_port(scheme, port):
"""Return port if it is not default port, else None.
>>> _normalize_port('http', '80')
>>> _normalize_port('http', '8080')
'8080'
"""
if not scheme:
return port
if port and port != DEFAULT_PORT[scheme]:
return port
|
python
|
def _from_timeseries(ts1, ts2, stride, fftlength=None, overlap=None,
window=None, **kwargs):
"""Generate a time-frequency coherence
:class:`~gwpy.spectrogram.Spectrogram` from a pair of
:class:`~gwpy.timeseries.TimeSeries`.
For each `stride`, a PSD :class:`~gwpy.frequencyseries.FrequencySeries`
is generated, with all resulting spectra stacked in time and returned.
"""
# check sampling rates
if ts1.sample_rate.to('Hertz') != ts2.sample_rate.to('Hertz'):
sampling = min(ts1.sample_rate.value, ts2.sample_rate.value)
# resample higher rate series
if ts1.sample_rate.value == sampling:
ts2 = ts2.resample(sampling)
else:
ts1 = ts1.resample(sampling)
else:
sampling = ts1.sample_rate.value
# format FFT parameters
if fftlength is None:
fftlength = stride
if overlap is None:
overlap = 0
nstride = int(stride * sampling)
# get size of spectrogram
nsteps = int(ts1.size // nstride)
nfreqs = int(fftlength * sampling // 2 + 1)
# generate output spectrogram
out = Spectrogram(zeros((nsteps, nfreqs)), epoch=ts1.epoch, dt=stride,
f0=0, df=1/fftlength, copy=True, unit='coherence')
if not nsteps:
return out
# stride through TimeSeries, recording PSDs as columns of spectrogram
for step in range(nsteps):
# find step TimeSeries
idx = nstride * step
idx_end = idx + nstride
stepseries1 = ts1[idx:idx_end]
stepseries2 = ts2[idx:idx_end]
stepcoh = stepseries1.coherence(stepseries2, fftlength=fftlength,
overlap=overlap, window=window,
**kwargs)
out.value[step] = stepcoh.value
return out
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.