text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def related(self):
""" Yields a list of all chunks in the sentence with the same relation id.
"""
return [ch for ch in self.sentence.chunks
if ch != self and intersects(unzip(0, ch.relations), unzip(0, self.relations))] | [
"def",
"related",
"(",
"self",
")",
":",
"return",
"[",
"ch",
"for",
"ch",
"in",
"self",
".",
"sentence",
".",
"chunks",
"if",
"ch",
"!=",
"self",
"and",
"intersects",
"(",
"unzip",
"(",
"0",
",",
"ch",
".",
"relations",
")",
",",
"unzip",
"(",
"0",
",",
"self",
".",
"relations",
")",
")",
"]"
] | 52 | 18.2 |
def partial(cls, prefix, source):
"""Strip a prefix from the keys of another dictionary, returning a Bunch containing only valid key, value pairs."""
match = prefix + "."
matches = cls([(key[len(match):], source[key]) for key in source if key.startswith(match)])
if not matches:
raise ValueError()
return matches | [
"def",
"partial",
"(",
"cls",
",",
"prefix",
",",
"source",
")",
":",
"match",
"=",
"prefix",
"+",
"\".\"",
"matches",
"=",
"cls",
"(",
"[",
"(",
"key",
"[",
"len",
"(",
"match",
")",
":",
"]",
",",
"source",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"source",
"if",
"key",
".",
"startswith",
"(",
"match",
")",
"]",
")",
"if",
"not",
"matches",
":",
"raise",
"ValueError",
"(",
")",
"return",
"matches"
] | 38.2 | 21.9 |
def agent_delete(self, agent_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/agents#delete-agent"
api_path = "/api/v2/agents/{agent_id}"
api_path = api_path.format(agent_id=agent_id)
return self.call(api_path, method="DELETE", **kwargs) | [
"def",
"agent_delete",
"(",
"self",
",",
"agent_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/agents/{agent_id}\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"agent_id",
"=",
"agent_id",
")",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"DELETE\"",
",",
"*",
"*",
"kwargs",
")"
] | 56.2 | 16.2 |
def clean_networks(networks: Iterable[str] = None) -> Optional[Iterable[str]]:
"""
Cleans the values inside `networks`
Returns a new list
"""
if not networks:
return networks
if not isinstance(networks, list):
raise TypeError("networks parameter must be a list.")
result = []
for n in networks:
if isinstance(n, str):
n = {"Target": n}
result.append(n)
return result | [
"def",
"clean_networks",
"(",
"networks",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"Optional",
"[",
"Iterable",
"[",
"str",
"]",
"]",
":",
"if",
"not",
"networks",
":",
"return",
"networks",
"if",
"not",
"isinstance",
"(",
"networks",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"networks parameter must be a list.\"",
")",
"result",
"=",
"[",
"]",
"for",
"n",
"in",
"networks",
":",
"if",
"isinstance",
"(",
"n",
",",
"str",
")",
":",
"n",
"=",
"{",
"\"Target\"",
":",
"n",
"}",
"result",
".",
"append",
"(",
"n",
")",
"return",
"result"
] | 27 | 16.25 |
def _delete_handler(self, handler_class):
"""Delete a specific handler from our logger."""
to_remove = self._get_handler(handler_class)
if not to_remove:
logging.warning('Error we should have an element to remove')
else:
self.handlers.remove(to_remove)
self.logger.removeHandler(to_remove) | [
"def",
"_delete_handler",
"(",
"self",
",",
"handler_class",
")",
":",
"to_remove",
"=",
"self",
".",
"_get_handler",
"(",
"handler_class",
")",
"if",
"not",
"to_remove",
":",
"logging",
".",
"warning",
"(",
"'Error we should have an element to remove'",
")",
"else",
":",
"self",
".",
"handlers",
".",
"remove",
"(",
"to_remove",
")",
"self",
".",
"logger",
".",
"removeHandler",
"(",
"to_remove",
")"
] | 43.75 | 12.25 |
def on_lstUnits_itemSelectionChanged(self):
"""Update unit description label and field widgets.
.. note:: This is an automatic Qt slot
executed when the unit selection changes.
"""
self.clear_further_steps()
# Set widgets
unit = self.selected_unit()
# Exit if no selection
if not unit:
return
self.lblDescribeUnit.setText(unit['description'])
# Enable the next button
self.parent.pbnNext.setEnabled(True) | [
"def",
"on_lstUnits_itemSelectionChanged",
"(",
"self",
")",
":",
"self",
".",
"clear_further_steps",
"(",
")",
"# Set widgets",
"unit",
"=",
"self",
".",
"selected_unit",
"(",
")",
"# Exit if no selection",
"if",
"not",
"unit",
":",
"return",
"self",
".",
"lblDescribeUnit",
".",
"setText",
"(",
"unit",
"[",
"'description'",
"]",
")",
"# Enable the next button",
"self",
".",
"parent",
".",
"pbnNext",
".",
"setEnabled",
"(",
"True",
")"
] | 33.466667 | 11.466667 |
def build_timeout_circuit(tor_state, reactor, path, timeout, using_guards=False):
"""
Build a new circuit within a timeout.
CircuitBuildTimedOutError will be raised unless we receive a
circuit build result (success or failure) within the `timeout`
duration.
:returns: a Deferred which fires when the circuit build succeeds (or
fails to build).
"""
timed_circuit = []
d = tor_state.build_circuit(routers=path, using_guards=using_guards)
def get_circuit(c):
timed_circuit.append(c)
return c
def trap_cancel(f):
f.trap(defer.CancelledError)
if timed_circuit:
d2 = timed_circuit[0].close()
else:
d2 = defer.succeed(None)
d2.addCallback(lambda _: Failure(CircuitBuildTimedOutError("circuit build timed out")))
return d2
d.addCallback(get_circuit)
d.addCallback(lambda circ: circ.when_built())
d.addErrback(trap_cancel)
reactor.callLater(timeout, d.cancel)
return d | [
"def",
"build_timeout_circuit",
"(",
"tor_state",
",",
"reactor",
",",
"path",
",",
"timeout",
",",
"using_guards",
"=",
"False",
")",
":",
"timed_circuit",
"=",
"[",
"]",
"d",
"=",
"tor_state",
".",
"build_circuit",
"(",
"routers",
"=",
"path",
",",
"using_guards",
"=",
"using_guards",
")",
"def",
"get_circuit",
"(",
"c",
")",
":",
"timed_circuit",
".",
"append",
"(",
"c",
")",
"return",
"c",
"def",
"trap_cancel",
"(",
"f",
")",
":",
"f",
".",
"trap",
"(",
"defer",
".",
"CancelledError",
")",
"if",
"timed_circuit",
":",
"d2",
"=",
"timed_circuit",
"[",
"0",
"]",
".",
"close",
"(",
")",
"else",
":",
"d2",
"=",
"defer",
".",
"succeed",
"(",
"None",
")",
"d2",
".",
"addCallback",
"(",
"lambda",
"_",
":",
"Failure",
"(",
"CircuitBuildTimedOutError",
"(",
"\"circuit build timed out\"",
")",
")",
")",
"return",
"d2",
"d",
".",
"addCallback",
"(",
"get_circuit",
")",
"d",
".",
"addCallback",
"(",
"lambda",
"circ",
":",
"circ",
".",
"when_built",
"(",
")",
")",
"d",
".",
"addErrback",
"(",
"trap_cancel",
")",
"reactor",
".",
"callLater",
"(",
"timeout",
",",
"d",
".",
"cancel",
")",
"return",
"d"
] | 29.848485 | 21.545455 |
def reads_supporting_variants(variants, samfile, **kwargs):
"""
Given a SAM/BAM file and a collection of variants, generates a sequence
of variants paired with reads which support each variant.
"""
for variant, allele_reads in reads_overlapping_variants(
variants=variants,
samfile=samfile,
**kwargs):
yield variant, filter_non_alt_reads_for_variant(variant, allele_reads) | [
"def",
"reads_supporting_variants",
"(",
"variants",
",",
"samfile",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"variant",
",",
"allele_reads",
"in",
"reads_overlapping_variants",
"(",
"variants",
"=",
"variants",
",",
"samfile",
"=",
"samfile",
",",
"*",
"*",
"kwargs",
")",
":",
"yield",
"variant",
",",
"filter_non_alt_reads_for_variant",
"(",
"variant",
",",
"allele_reads",
")"
] | 42.7 | 17.3 |
def create_user(self, user):
"""
Create a user on the local system
"""
self.run("useradd -m %s" % user)
usr = getpwnam(user)
return usr | [
"def",
"create_user",
"(",
"self",
",",
"user",
")",
":",
"self",
".",
"run",
"(",
"\"useradd -m %s\"",
"%",
"user",
")",
"usr",
"=",
"getpwnam",
"(",
"user",
")",
"return",
"usr"
] | 25.428571 | 6.571429 |
def fit_transform(self, X, y):
"""Encode categorical columns into average target values.
Args:
X (pandas.DataFrame): categorical columns to encode
y (pandas.Series): the target column
Returns:
X (pandas.DataFrame): encoded columns
"""
self.target_encoders = [None] * X.shape[1]
self.target_mean = y.mean()
for i, col in enumerate(X.columns):
self.target_encoders[i] = self._get_target_encoder(X[col], y)
X.loc[:, col] = X[col].fillna(NAN_INT).map(self.target_encoders[i]).fillna(self.target_mean)
return X | [
"def",
"fit_transform",
"(",
"self",
",",
"X",
",",
"y",
")",
":",
"self",
".",
"target_encoders",
"=",
"[",
"None",
"]",
"*",
"X",
".",
"shape",
"[",
"1",
"]",
"self",
".",
"target_mean",
"=",
"y",
".",
"mean",
"(",
")",
"for",
"i",
",",
"col",
"in",
"enumerate",
"(",
"X",
".",
"columns",
")",
":",
"self",
".",
"target_encoders",
"[",
"i",
"]",
"=",
"self",
".",
"_get_target_encoder",
"(",
"X",
"[",
"col",
"]",
",",
"y",
")",
"X",
".",
"loc",
"[",
":",
",",
"col",
"]",
"=",
"X",
"[",
"col",
"]",
".",
"fillna",
"(",
"NAN_INT",
")",
".",
"map",
"(",
"self",
".",
"target_encoders",
"[",
"i",
"]",
")",
".",
"fillna",
"(",
"self",
".",
"target_mean",
")",
"return",
"X"
] | 36.235294 | 21.176471 |
def calculate_unaryop(self, node, next_node):
"""Create new node for unaryop"""
position = (next_node.first_line, next_node.first_col + 1)
possible = []
for ch in OPERATORS[node.__class__]:
try:
pos = self.operators[ch].find_previous(position)
if pos[1] < position:
possible.append(pos)
except KeyError:
pass
return NodeWithPosition(
*min(possible, key=lambda x: tuple(map(sub, position, x[0])))
) | [
"def",
"calculate_unaryop",
"(",
"self",
",",
"node",
",",
"next_node",
")",
":",
"position",
"=",
"(",
"next_node",
".",
"first_line",
",",
"next_node",
".",
"first_col",
"+",
"1",
")",
"possible",
"=",
"[",
"]",
"for",
"ch",
"in",
"OPERATORS",
"[",
"node",
".",
"__class__",
"]",
":",
"try",
":",
"pos",
"=",
"self",
".",
"operators",
"[",
"ch",
"]",
".",
"find_previous",
"(",
"position",
")",
"if",
"pos",
"[",
"1",
"]",
"<",
"position",
":",
"possible",
".",
"append",
"(",
"pos",
")",
"except",
"KeyError",
":",
"pass",
"return",
"NodeWithPosition",
"(",
"*",
"min",
"(",
"possible",
",",
"key",
"=",
"lambda",
"x",
":",
"tuple",
"(",
"map",
"(",
"sub",
",",
"position",
",",
"x",
"[",
"0",
"]",
")",
")",
")",
")"
] | 35.733333 | 16.6 |
def process(self, sched, coro):
"""Add the given coroutine in the scheduler."""
super(AddCoro, self).process(sched, coro)
self.result = sched.add(self.coro, self.args, self.kwargs, self.prio & priority.OP)
if self.prio & priority.CORO:
return self, coro
else:
sched.active.append( (None, coro)) | [
"def",
"process",
"(",
"self",
",",
"sched",
",",
"coro",
")",
":",
"super",
"(",
"AddCoro",
",",
"self",
")",
".",
"process",
"(",
"sched",
",",
"coro",
")",
"self",
".",
"result",
"=",
"sched",
".",
"add",
"(",
"self",
".",
"coro",
",",
"self",
".",
"args",
",",
"self",
".",
"kwargs",
",",
"self",
".",
"prio",
"&",
"priority",
".",
"OP",
")",
"if",
"self",
".",
"prio",
"&",
"priority",
".",
"CORO",
":",
"return",
"self",
",",
"coro",
"else",
":",
"sched",
".",
"active",
".",
"append",
"(",
"(",
"None",
",",
"coro",
")",
")"
] | 44.75 | 14.25 |
def send_msg(self, message):
"""Send a SLIP-encoded message over the stream.
:param bytes message: The message to encode and send
"""
packet = self.driver.send(message)
self.send_bytes(packet) | [
"def",
"send_msg",
"(",
"self",
",",
"message",
")",
":",
"packet",
"=",
"self",
".",
"driver",
".",
"send",
"(",
"message",
")",
"self",
".",
"send_bytes",
"(",
"packet",
")"
] | 32.428571 | 11.857143 |
def create(self, emails, displayName=None, firstName=None, lastName=None,
avatar=None, orgId=None, roles=None, licenses=None,
**request_parameters):
"""Create a new user account for a given organization
Only an admin can create a new user account.
Args:
emails(`list`): Email address(es) of the person (list of strings).
displayName(basestring): Full name of the person.
firstName(basestring): First name of the person.
lastName(basestring): Last name of the person.
avatar(basestring): URL to the person's avatar in PNG format.
orgId(basestring): ID of the organization to which this
person belongs.
roles(`list`): Roles of the person (list of strings containing
the role IDs to be assigned to the person).
licenses(`list`): Licenses allocated to the person (list of
strings - containing the license IDs to be allocated to the
person).
**request_parameters: Additional request parameters (provides
support for parameters that may be added in the future).
Returns:
Person: A Person object with the details of the created person.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(emails, list, may_be_none=False)
check_type(displayName, basestring)
check_type(firstName, basestring)
check_type(lastName, basestring)
check_type(avatar, basestring)
check_type(orgId, basestring)
check_type(roles, list)
check_type(licenses, list)
post_data = dict_from_items_with_values(
request_parameters,
emails=emails,
displayName=displayName,
firstName=firstName,
lastName=lastName,
avatar=avatar,
orgId=orgId,
roles=roles,
licenses=licenses,
)
# API request
json_data = self._session.post(API_ENDPOINT, json=post_data)
# Return a person object created from the returned JSON object
return self._object_factory(OBJECT_TYPE, json_data) | [
"def",
"create",
"(",
"self",
",",
"emails",
",",
"displayName",
"=",
"None",
",",
"firstName",
"=",
"None",
",",
"lastName",
"=",
"None",
",",
"avatar",
"=",
"None",
",",
"orgId",
"=",
"None",
",",
"roles",
"=",
"None",
",",
"licenses",
"=",
"None",
",",
"*",
"*",
"request_parameters",
")",
":",
"check_type",
"(",
"emails",
",",
"list",
",",
"may_be_none",
"=",
"False",
")",
"check_type",
"(",
"displayName",
",",
"basestring",
")",
"check_type",
"(",
"firstName",
",",
"basestring",
")",
"check_type",
"(",
"lastName",
",",
"basestring",
")",
"check_type",
"(",
"avatar",
",",
"basestring",
")",
"check_type",
"(",
"orgId",
",",
"basestring",
")",
"check_type",
"(",
"roles",
",",
"list",
")",
"check_type",
"(",
"licenses",
",",
"list",
")",
"post_data",
"=",
"dict_from_items_with_values",
"(",
"request_parameters",
",",
"emails",
"=",
"emails",
",",
"displayName",
"=",
"displayName",
",",
"firstName",
"=",
"firstName",
",",
"lastName",
"=",
"lastName",
",",
"avatar",
"=",
"avatar",
",",
"orgId",
"=",
"orgId",
",",
"roles",
"=",
"roles",
",",
"licenses",
"=",
"licenses",
",",
")",
"# API request",
"json_data",
"=",
"self",
".",
"_session",
".",
"post",
"(",
"API_ENDPOINT",
",",
"json",
"=",
"post_data",
")",
"# Return a person object created from the returned JSON object",
"return",
"self",
".",
"_object_factory",
"(",
"OBJECT_TYPE",
",",
"json_data",
")"
] | 39.789474 | 20.807018 |
def ConsultarContribuyentes(self, fecha_desde, fecha_hasta, cuit_contribuyente):
"Realiza la consulta remota a ARBA, estableciendo los resultados"
self.limpiar()
try:
self.xml = SimpleXMLElement(XML_ENTRADA_BASE)
self.xml.fechaDesde = fecha_desde
self.xml.fechaHasta = fecha_hasta
self.xml.contribuyentes.contribuyente.cuitContribuyente = cuit_contribuyente
xml = self.xml.as_xml()
self.CodigoHash = md5.md5(xml).hexdigest()
nombre = "DFEServicioConsulta_%s.xml" % self.CodigoHash
# guardo el xml en el archivo a enviar y luego lo re-abro:
archivo = open(os.path.join(tempfile.gettempdir(), nombre), "w")
archivo.write(xml)
archivo.close()
archivo = open(os.path.join(tempfile.gettempdir(), nombre), "r")
if not self.testing:
response = self.client(user=self.Usuario, password=self.Password,
file=archivo)
else:
response = open(self.testing).read()
self.XmlResponse = response
self.xml = SimpleXMLElement(response)
if 'tipoError' in self.xml:
self.TipoError = str(self.xml.tipoError)
self.CodigoError = str(self.xml.codigoError)
self.MensajeError = str(self.xml.mensajeError).decode('latin1').encode("ascii", "replace")
if 'numeroComprobante' in self.xml:
self.NumeroComprobante = str(self.xml.numeroComprobante)
self.CantidadContribuyentes = int(self.xml.cantidadContribuyentes)
if 'contribuyentes' in self.xml:
for contrib in self.xml.contribuyente:
c = {
'CuitContribuytente': str(contrib.cuitContribuyente),
'AlicuotaPercepcion': str(contrib.alicuotaPercepcion),
'AlicuotaRetencion': str(contrib.alicuotaRetencion),
'GrupoPercepcion': str(contrib.grupoPercepcion),
'GrupoRetencion': str(contrib.grupoRetencion),
'Errores': [],
}
self.contribuyentes.append(c)
# establecer valores del primer contrib (sin eliminarlo)
self.LeerContribuyente(pop=False)
return True
except Exception, e:
ex = traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback)
self.Traceback = ''.join(ex)
try:
self.Excepcion = traceback.format_exception_only( sys.exc_type, sys.exc_value)[0]
except:
self.Excepcion = u"<no disponible>"
return False | [
"def",
"ConsultarContribuyentes",
"(",
"self",
",",
"fecha_desde",
",",
"fecha_hasta",
",",
"cuit_contribuyente",
")",
":",
"self",
".",
"limpiar",
"(",
")",
"try",
":",
"self",
".",
"xml",
"=",
"SimpleXMLElement",
"(",
"XML_ENTRADA_BASE",
")",
"self",
".",
"xml",
".",
"fechaDesde",
"=",
"fecha_desde",
"self",
".",
"xml",
".",
"fechaHasta",
"=",
"fecha_hasta",
"self",
".",
"xml",
".",
"contribuyentes",
".",
"contribuyente",
".",
"cuitContribuyente",
"=",
"cuit_contribuyente",
"xml",
"=",
"self",
".",
"xml",
".",
"as_xml",
"(",
")",
"self",
".",
"CodigoHash",
"=",
"md5",
".",
"md5",
"(",
"xml",
")",
".",
"hexdigest",
"(",
")",
"nombre",
"=",
"\"DFEServicioConsulta_%s.xml\"",
"%",
"self",
".",
"CodigoHash",
"# guardo el xml en el archivo a enviar y luego lo re-abro:",
"archivo",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"nombre",
")",
",",
"\"w\"",
")",
"archivo",
".",
"write",
"(",
"xml",
")",
"archivo",
".",
"close",
"(",
")",
"archivo",
"=",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"nombre",
")",
",",
"\"r\"",
")",
"if",
"not",
"self",
".",
"testing",
":",
"response",
"=",
"self",
".",
"client",
"(",
"user",
"=",
"self",
".",
"Usuario",
",",
"password",
"=",
"self",
".",
"Password",
",",
"file",
"=",
"archivo",
")",
"else",
":",
"response",
"=",
"open",
"(",
"self",
".",
"testing",
")",
".",
"read",
"(",
")",
"self",
".",
"XmlResponse",
"=",
"response",
"self",
".",
"xml",
"=",
"SimpleXMLElement",
"(",
"response",
")",
"if",
"'tipoError'",
"in",
"self",
".",
"xml",
":",
"self",
".",
"TipoError",
"=",
"str",
"(",
"self",
".",
"xml",
".",
"tipoError",
")",
"self",
".",
"CodigoError",
"=",
"str",
"(",
"self",
".",
"xml",
".",
"codigoError",
")",
"self",
".",
"MensajeError",
"=",
"str",
"(",
"self",
".",
"xml",
".",
"mensajeError",
")",
".",
"decode",
"(",
"'latin1'",
")",
".",
"encode",
"(",
"\"ascii\"",
",",
"\"replace\"",
")",
"if",
"'numeroComprobante'",
"in",
"self",
".",
"xml",
":",
"self",
".",
"NumeroComprobante",
"=",
"str",
"(",
"self",
".",
"xml",
".",
"numeroComprobante",
")",
"self",
".",
"CantidadContribuyentes",
"=",
"int",
"(",
"self",
".",
"xml",
".",
"cantidadContribuyentes",
")",
"if",
"'contribuyentes'",
"in",
"self",
".",
"xml",
":",
"for",
"contrib",
"in",
"self",
".",
"xml",
".",
"contribuyente",
":",
"c",
"=",
"{",
"'CuitContribuytente'",
":",
"str",
"(",
"contrib",
".",
"cuitContribuyente",
")",
",",
"'AlicuotaPercepcion'",
":",
"str",
"(",
"contrib",
".",
"alicuotaPercepcion",
")",
",",
"'AlicuotaRetencion'",
":",
"str",
"(",
"contrib",
".",
"alicuotaRetencion",
")",
",",
"'GrupoPercepcion'",
":",
"str",
"(",
"contrib",
".",
"grupoPercepcion",
")",
",",
"'GrupoRetencion'",
":",
"str",
"(",
"contrib",
".",
"grupoRetencion",
")",
",",
"'Errores'",
":",
"[",
"]",
",",
"}",
"self",
".",
"contribuyentes",
".",
"append",
"(",
"c",
")",
"# establecer valores del primer contrib (sin eliminarlo)",
"self",
".",
"LeerContribuyente",
"(",
"pop",
"=",
"False",
")",
"return",
"True",
"except",
"Exception",
",",
"e",
":",
"ex",
"=",
"traceback",
".",
"format_exception",
"(",
"sys",
".",
"exc_type",
",",
"sys",
".",
"exc_value",
",",
"sys",
".",
"exc_traceback",
")",
"self",
".",
"Traceback",
"=",
"''",
".",
"join",
"(",
"ex",
")",
"try",
":",
"self",
".",
"Excepcion",
"=",
"traceback",
".",
"format_exception_only",
"(",
"sys",
".",
"exc_type",
",",
"sys",
".",
"exc_value",
")",
"[",
"0",
"]",
"except",
":",
"self",
".",
"Excepcion",
"=",
"u\"<no disponible>\"",
"return",
"False"
] | 50.642857 | 23.75 |
def add_category(self, category):
"""
Category Tags are used to characterize an element by a type
identifier. They can then be searched and returned as a group
of elements. If the category tag specified does not exist, it
will be created. This change will take effect immediately.
:param list tags: list of category tag names to add to this
element
:type tags: list(str)
:raises ElementNotFound: Category tag element name not found
:return: None
.. seealso:: :class:`smc.elements.other.Category`
"""
assert isinstance(category, list), 'Category input was expecting list.'
from smc.elements.other import Category
for tag in category:
category = Category(tag)
try:
category.add_element(self.href)
except ElementNotFound:
Category.create(name=tag)
category.add_element(self.href) | [
"def",
"add_category",
"(",
"self",
",",
"category",
")",
":",
"assert",
"isinstance",
"(",
"category",
",",
"list",
")",
",",
"'Category input was expecting list.'",
"from",
"smc",
".",
"elements",
".",
"other",
"import",
"Category",
"for",
"tag",
"in",
"category",
":",
"category",
"=",
"Category",
"(",
"tag",
")",
"try",
":",
"category",
".",
"add_element",
"(",
"self",
".",
"href",
")",
"except",
"ElementNotFound",
":",
"Category",
".",
"create",
"(",
"name",
"=",
"tag",
")",
"category",
".",
"add_element",
"(",
"self",
".",
"href",
")"
] | 40.125 | 17.791667 |
def import_from_string(self, text, title=None):
"""Import data from string"""
data = self.model.get_data()
# Check if data is a dict
if not hasattr(data, "keys"):
return
editor = ImportWizard(self, text, title=title,
contents_title=_("Clipboard contents"),
varname=fix_reference_name("data",
blacklist=list(data.keys())))
if editor.exec_():
var_name, clip_data = editor.get_data()
self.new_value(var_name, clip_data) | [
"def",
"import_from_string",
"(",
"self",
",",
"text",
",",
"title",
"=",
"None",
")",
":",
"data",
"=",
"self",
".",
"model",
".",
"get_data",
"(",
")",
"# Check if data is a dict\r",
"if",
"not",
"hasattr",
"(",
"data",
",",
"\"keys\"",
")",
":",
"return",
"editor",
"=",
"ImportWizard",
"(",
"self",
",",
"text",
",",
"title",
"=",
"title",
",",
"contents_title",
"=",
"_",
"(",
"\"Clipboard contents\"",
")",
",",
"varname",
"=",
"fix_reference_name",
"(",
"\"data\"",
",",
"blacklist",
"=",
"list",
"(",
"data",
".",
"keys",
"(",
")",
")",
")",
")",
"if",
"editor",
".",
"exec_",
"(",
")",
":",
"var_name",
",",
"clip_data",
"=",
"editor",
".",
"get_data",
"(",
")",
"self",
".",
"new_value",
"(",
"var_name",
",",
"clip_data",
")"
] | 47.461538 | 14.538462 |
def age(self, now=None):
"""
Returns an integer which is the difference in seconds from
'now' to when this circuit was created.
Returns None if there is no created-time.
"""
if not self.time_created:
return None
if now is None:
now = datetime.utcnow()
return (now - self.time_created).seconds | [
"def",
"age",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"time_created",
":",
"return",
"None",
"if",
"now",
"is",
"None",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"return",
"(",
"now",
"-",
"self",
".",
"time_created",
")",
".",
"seconds"
] | 30.833333 | 12.666667 |
def open(self, fname, mode='r', psw=None):
"""Returns file-like object (:class:`RarExtFile`) from where the data can be read.
The object implements :class:`io.RawIOBase` interface, so it can
be further wrapped with :class:`io.BufferedReader`
and :class:`io.TextIOWrapper`.
On older Python where io module is not available, it implements
only .read(), .seek(), .tell() and .close() methods.
The object is seekable, although the seeking is fast only on
uncompressed files, on compressed files the seeking is implemented
by reading ahead and/or restarting the decompression.
Parameters:
fname
file name or RarInfo instance.
mode
must be 'r'
psw
password to use for extracting.
"""
if mode != 'r':
raise NotImplementedError("RarFile.open() supports only mode=r")
# entry lookup
inf = self.getinfo(fname)
if inf.isdir():
raise TypeError("Directory does not have any data: " + inf.filename)
# check password
if inf.needs_password():
psw = psw or self._password
if psw is None:
raise PasswordRequired("File %s requires password" % inf.filename)
else:
psw = None
return self._file_parser.open(inf, psw) | [
"def",
"open",
"(",
"self",
",",
"fname",
",",
"mode",
"=",
"'r'",
",",
"psw",
"=",
"None",
")",
":",
"if",
"mode",
"!=",
"'r'",
":",
"raise",
"NotImplementedError",
"(",
"\"RarFile.open() supports only mode=r\"",
")",
"# entry lookup",
"inf",
"=",
"self",
".",
"getinfo",
"(",
"fname",
")",
"if",
"inf",
".",
"isdir",
"(",
")",
":",
"raise",
"TypeError",
"(",
"\"Directory does not have any data: \"",
"+",
"inf",
".",
"filename",
")",
"# check password",
"if",
"inf",
".",
"needs_password",
"(",
")",
":",
"psw",
"=",
"psw",
"or",
"self",
".",
"_password",
"if",
"psw",
"is",
"None",
":",
"raise",
"PasswordRequired",
"(",
"\"File %s requires password\"",
"%",
"inf",
".",
"filename",
")",
"else",
":",
"psw",
"=",
"None",
"return",
"self",
".",
"_file_parser",
".",
"open",
"(",
"inf",
",",
"psw",
")"
] | 33.536585 | 22.780488 |
def order_by_next_occurrence(self):
"""
:return: A list of events in order of minimum occurrence greater than
now (or overlapping now in the case of drop-in events).
This is an expensive operation - use with as small a source
queryset as possible.
Events with no upcoming occurrence appear last (in order of their first
occurrence). Events with no occurrences at all appear right at the end
(in no order). To remove these, use "with_upcoming_occurrences" or
"with_upcoming_or_no_occurrences".
"""
qs = self.prefetch_related('occurrences')
def _sort(x):
try:
# If there's an upcoming occurrence, use it.
return x.get_next_occurrence().start
except AttributeError:
try:
# If there's any occurrence, use the first one, plus 1000 years.
return x.get_first_occurrence().start + timedelta(days=1000*365)
except AttributeError:
# If no occurence, use a localised datetime.max (minus a
# few days to avoid overflow)
return make_aware(datetime.max-timedelta(2))
sorted_qs = sorted(qs, key=_sort)
return sorted_qs | [
"def",
"order_by_next_occurrence",
"(",
"self",
")",
":",
"qs",
"=",
"self",
".",
"prefetch_related",
"(",
"'occurrences'",
")",
"def",
"_sort",
"(",
"x",
")",
":",
"try",
":",
"# If there's an upcoming occurrence, use it.",
"return",
"x",
".",
"get_next_occurrence",
"(",
")",
".",
"start",
"except",
"AttributeError",
":",
"try",
":",
"# If there's any occurrence, use the first one, plus 1000 years.",
"return",
"x",
".",
"get_first_occurrence",
"(",
")",
".",
"start",
"+",
"timedelta",
"(",
"days",
"=",
"1000",
"*",
"365",
")",
"except",
"AttributeError",
":",
"# If no occurence, use a localised datetime.max (minus a",
"# few days to avoid overflow)",
"return",
"make_aware",
"(",
"datetime",
".",
"max",
"-",
"timedelta",
"(",
"2",
")",
")",
"sorted_qs",
"=",
"sorted",
"(",
"qs",
",",
"key",
"=",
"_sort",
")",
"return",
"sorted_qs"
] | 40.875 | 22.625 |
def _get_attr_list(self, attr):
"""Return user's attribute/attributes"""
a = self._attrs.get(attr)
if not a:
return []
if type(a) is list:
r = [i.decode('utf-8', 'ignore') for i in a]
else:
r = [a.decode('utf-8', 'ignore')]
return r | [
"def",
"_get_attr_list",
"(",
"self",
",",
"attr",
")",
":",
"a",
"=",
"self",
".",
"_attrs",
".",
"get",
"(",
"attr",
")",
"if",
"not",
"a",
":",
"return",
"[",
"]",
"if",
"type",
"(",
"a",
")",
"is",
"list",
":",
"r",
"=",
"[",
"i",
".",
"decode",
"(",
"'utf-8'",
",",
"'ignore'",
")",
"for",
"i",
"in",
"a",
"]",
"else",
":",
"r",
"=",
"[",
"a",
".",
"decode",
"(",
"'utf-8'",
",",
"'ignore'",
")",
"]",
"return",
"r"
] | 30.7 | 14.3 |
def RegisterDecompressor(cls, decompressor):
"""Registers a decompressor for a specific compression method.
Args:
decompressor (type): decompressor class.
Raises:
KeyError: if the corresponding decompressor is already set.
"""
compression_method = decompressor.COMPRESSION_METHOD.lower()
if compression_method in cls._decompressors:
raise KeyError(
'Decompressor for compression method: {0:s} already set.'.format(
decompressor.COMPRESSION_METHOD))
cls._decompressors[compression_method] = decompressor | [
"def",
"RegisterDecompressor",
"(",
"cls",
",",
"decompressor",
")",
":",
"compression_method",
"=",
"decompressor",
".",
"COMPRESSION_METHOD",
".",
"lower",
"(",
")",
"if",
"compression_method",
"in",
"cls",
".",
"_decompressors",
":",
"raise",
"KeyError",
"(",
"'Decompressor for compression method: {0:s} already set.'",
".",
"format",
"(",
"decompressor",
".",
"COMPRESSION_METHOD",
")",
")",
"cls",
".",
"_decompressors",
"[",
"compression_method",
"]",
"=",
"decompressor"
] | 35 | 20.3125 |
def is_url(value):
"Must start with http:// or https:// and contain JUST a URL"
if not isinstance(value, str):
return False
if not value.startswith('http://') and not value.startswith('https://'):
return False
# Any whitespace at all is invalid
if whitespace_re.search(value):
return False
return True | [
"def",
"is_url",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"return",
"False",
"if",
"not",
"value",
".",
"startswith",
"(",
"'http://'",
")",
"and",
"not",
"value",
".",
"startswith",
"(",
"'https://'",
")",
":",
"return",
"False",
"# Any whitespace at all is invalid",
"if",
"whitespace_re",
".",
"search",
"(",
"value",
")",
":",
"return",
"False",
"return",
"True"
] | 34 | 18 |
def _trigger_event(
self, holder: T.Any, alt_name: str, action: str, *event_args: T.Any
) -> None:
"""Triggers an event on the associated Observable object.
The Holder is the object this property is a member of, alt_name
is used as the event name when self.event is not set, action is
prepended to the event name and event_args are passed through
to the registered event handlers."""
if isinstance(self.observable, Observable):
observable = self.observable
elif isinstance(self.observable, str):
observable = getattr(holder, self.observable)
elif isinstance(holder, Observable):
observable = holder
else:
raise TypeError(
"This ObservableProperty is no member of an Observable "
"object. Specify where to find the Observable object for "
"triggering events with the observable keyword argument "
"when initializing the ObservableProperty."
)
name = alt_name if self.event is None else self.event
event = "{}_{}".format(action, name)
observable.trigger(event, *event_args) | [
"def",
"_trigger_event",
"(",
"self",
",",
"holder",
":",
"T",
".",
"Any",
",",
"alt_name",
":",
"str",
",",
"action",
":",
"str",
",",
"*",
"event_args",
":",
"T",
".",
"Any",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"self",
".",
"observable",
",",
"Observable",
")",
":",
"observable",
"=",
"self",
".",
"observable",
"elif",
"isinstance",
"(",
"self",
".",
"observable",
",",
"str",
")",
":",
"observable",
"=",
"getattr",
"(",
"holder",
",",
"self",
".",
"observable",
")",
"elif",
"isinstance",
"(",
"holder",
",",
"Observable",
")",
":",
"observable",
"=",
"holder",
"else",
":",
"raise",
"TypeError",
"(",
"\"This ObservableProperty is no member of an Observable \"",
"\"object. Specify where to find the Observable object for \"",
"\"triggering events with the observable keyword argument \"",
"\"when initializing the ObservableProperty.\"",
")",
"name",
"=",
"alt_name",
"if",
"self",
".",
"event",
"is",
"None",
"else",
"self",
".",
"event",
"event",
"=",
"\"{}_{}\"",
".",
"format",
"(",
"action",
",",
"name",
")",
"observable",
".",
"trigger",
"(",
"event",
",",
"*",
"event_args",
")"
] | 45.538462 | 19.961538 |
def set_tag(tag, value):
"""
Set the tag 'tag' to the value True or False.
:param value: should be a boolean
:param tag: should be the id of the tag. Can not starts with '*auto-tag-'
"""
if not tag.startswith("*auto-tag-"):
rdict = load_feedback()
tests = rdict.setdefault("tests", {})
tests[tag] = (value == True)
save_feedback(rdict) | [
"def",
"set_tag",
"(",
"tag",
",",
"value",
")",
":",
"if",
"not",
"tag",
".",
"startswith",
"(",
"\"*auto-tag-\"",
")",
":",
"rdict",
"=",
"load_feedback",
"(",
")",
"tests",
"=",
"rdict",
".",
"setdefault",
"(",
"\"tests\"",
",",
"{",
"}",
")",
"tests",
"[",
"tag",
"]",
"=",
"(",
"value",
"==",
"True",
")",
"save_feedback",
"(",
"rdict",
")"
] | 35 | 8.636364 |
async def stop_tasks(self, address):
"""Clear all tasks pertaining to a tile.
This coroutine will synchronously cancel all running tasks that were
attached to the given tile and wait for them to stop before returning.
Args:
address (int): The address of the tile we should stop.
"""
tasks = self._tasks.get(address, [])
for task in tasks:
task.cancel()
asyncio.gather(*tasks, return_exceptions=True)
self._tasks[address] = [] | [
"async",
"def",
"stop_tasks",
"(",
"self",
",",
"address",
")",
":",
"tasks",
"=",
"self",
".",
"_tasks",
".",
"get",
"(",
"address",
",",
"[",
"]",
")",
"for",
"task",
"in",
"tasks",
":",
"task",
".",
"cancel",
"(",
")",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
",",
"return_exceptions",
"=",
"True",
")",
"self",
".",
"_tasks",
"[",
"address",
"]",
"=",
"[",
"]"
] | 31.875 | 21.5625 |
def execute(self, fragment, pretty_format=True):
"""
Run or aggregate a query fragment
Concat the fragment to any stored fragments. If they form a complete
query, run it and return the result. If not, store them and return
None.
"""
self.fragments = (self.fragments + "\n" + fragment).lstrip()
try:
line_parser.parseString(self.fragments)
except ParseException:
pass
else:
self.last_query = self.fragments.strip()
self.fragments = ""
return super(FragmentEngine, self).execute(self.last_query, pretty_format)
return None | [
"def",
"execute",
"(",
"self",
",",
"fragment",
",",
"pretty_format",
"=",
"True",
")",
":",
"self",
".",
"fragments",
"=",
"(",
"self",
".",
"fragments",
"+",
"\"\\n\"",
"+",
"fragment",
")",
".",
"lstrip",
"(",
")",
"try",
":",
"line_parser",
".",
"parseString",
"(",
"self",
".",
"fragments",
")",
"except",
"ParseException",
":",
"pass",
"else",
":",
"self",
".",
"last_query",
"=",
"self",
".",
"fragments",
".",
"strip",
"(",
")",
"self",
".",
"fragments",
"=",
"\"\"",
"return",
"super",
"(",
"FragmentEngine",
",",
"self",
")",
".",
"execute",
"(",
"self",
".",
"last_query",
",",
"pretty_format",
")",
"return",
"None"
] | 34.315789 | 21.157895 |
def get_chunk(self, chunk_id):
"""
Returns the chunk object for the supplied identifier
@type chunk_id: string
@param chunk_id: chunk identifier
"""
if chunk_id in self.idx:
return Cchunk(self.idx[chunk_id], self.type)
else:
return None | [
"def",
"get_chunk",
"(",
"self",
",",
"chunk_id",
")",
":",
"if",
"chunk_id",
"in",
"self",
".",
"idx",
":",
"return",
"Cchunk",
"(",
"self",
".",
"idx",
"[",
"chunk_id",
"]",
",",
"self",
".",
"type",
")",
"else",
":",
"return",
"None"
] | 30.7 | 10.9 |
def config_examples(dest, user_dir):
""" Copy the example workflows to a directory.
\b
DEST: Path to which the examples should be copied.
"""
examples_path = Path(lightflow.__file__).parents[1] / 'examples'
if examples_path.exists():
dest_path = Path(dest).resolve()
if not user_dir:
dest_path = dest_path / 'examples'
if dest_path.exists():
if not click.confirm('Directory already exists. Overwrite existing files?',
default=True, abort=True):
return
else:
dest_path.mkdir()
for example_file in examples_path.glob('*.py'):
shutil.copy(str(example_file), str(dest_path / example_file.name))
click.echo('Copied examples to {}'.format(str(dest_path)))
else:
click.echo('The examples source path does not exist') | [
"def",
"config_examples",
"(",
"dest",
",",
"user_dir",
")",
":",
"examples_path",
"=",
"Path",
"(",
"lightflow",
".",
"__file__",
")",
".",
"parents",
"[",
"1",
"]",
"/",
"'examples'",
"if",
"examples_path",
".",
"exists",
"(",
")",
":",
"dest_path",
"=",
"Path",
"(",
"dest",
")",
".",
"resolve",
"(",
")",
"if",
"not",
"user_dir",
":",
"dest_path",
"=",
"dest_path",
"/",
"'examples'",
"if",
"dest_path",
".",
"exists",
"(",
")",
":",
"if",
"not",
"click",
".",
"confirm",
"(",
"'Directory already exists. Overwrite existing files?'",
",",
"default",
"=",
"True",
",",
"abort",
"=",
"True",
")",
":",
"return",
"else",
":",
"dest_path",
".",
"mkdir",
"(",
")",
"for",
"example_file",
"in",
"examples_path",
".",
"glob",
"(",
"'*.py'",
")",
":",
"shutil",
".",
"copy",
"(",
"str",
"(",
"example_file",
")",
",",
"str",
"(",
"dest_path",
"/",
"example_file",
".",
"name",
")",
")",
"click",
".",
"echo",
"(",
"'Copied examples to {}'",
".",
"format",
"(",
"str",
"(",
"dest_path",
")",
")",
")",
"else",
":",
"click",
".",
"echo",
"(",
"'The examples source path does not exist'",
")"
] | 36.25 | 20.625 |
def get_inst_info(qry_string):
"""Get details for instances that match the qry_string.
Execute a query against the AWS EC2 client object, that is
based on the contents of qry_string.
Args:
qry_string (str): the query to be used against the aws ec2 client.
Returns:
qry_results (dict): raw information returned from AWS.
"""
qry_prefix = "EC2C.describe_instances("
qry_real = qry_prefix + qry_string + ")"
qry_results = eval(qry_real) # pylint: disable=eval-used
return qry_results | [
"def",
"get_inst_info",
"(",
"qry_string",
")",
":",
"qry_prefix",
"=",
"\"EC2C.describe_instances(\"",
"qry_real",
"=",
"qry_prefix",
"+",
"qry_string",
"+",
"\")\"",
"qry_results",
"=",
"eval",
"(",
"qry_real",
")",
"# pylint: disable=eval-used",
"return",
"qry_results"
] | 33 | 19.75 |
async def start_store(app, url, workers=0, **kw):
'''Equivalent to :func:`.create_store` for most cases excepts when the
``url`` is for a pulsar store not yet started.
In this case, a :class:`.PulsarDS` is started.
'''
store = create_store(url, **kw)
if store.name == 'pulsar':
client = store.client()
try:
await client.ping()
except ConnectionRefusedError:
host = localhost(store._host)
if not host:
raise
cfg = await send('arbiter', 'run', start_pulsar_ds,
host, workers)
store._host = cfg.addresses[0]
dsn = store.buildurl()
store = create_store(dsn, **kw)
app.cfg.set('data_store', store.dsn) | [
"async",
"def",
"start_store",
"(",
"app",
",",
"url",
",",
"workers",
"=",
"0",
",",
"*",
"*",
"kw",
")",
":",
"store",
"=",
"create_store",
"(",
"url",
",",
"*",
"*",
"kw",
")",
"if",
"store",
".",
"name",
"==",
"'pulsar'",
":",
"client",
"=",
"store",
".",
"client",
"(",
")",
"try",
":",
"await",
"client",
".",
"ping",
"(",
")",
"except",
"ConnectionRefusedError",
":",
"host",
"=",
"localhost",
"(",
"store",
".",
"_host",
")",
"if",
"not",
"host",
":",
"raise",
"cfg",
"=",
"await",
"send",
"(",
"'arbiter'",
",",
"'run'",
",",
"start_pulsar_ds",
",",
"host",
",",
"workers",
")",
"store",
".",
"_host",
"=",
"cfg",
".",
"addresses",
"[",
"0",
"]",
"dsn",
"=",
"store",
".",
"buildurl",
"(",
")",
"store",
"=",
"create_store",
"(",
"dsn",
",",
"*",
"*",
"kw",
")",
"app",
".",
"cfg",
".",
"set",
"(",
"'data_store'",
",",
"store",
".",
"dsn",
")"
] | 37.9 | 11.6 |
def find_window(className = None, windowName = None):
"""
Find the first top-level window in the current desktop to match the
given class name and/or window name. If neither are provided any
top-level window will match.
@see: L{get_window_at}
@type className: str
@param className: (Optional) Class name of the window to find.
If C{None} or not used any class name will match the search.
@type windowName: str
@param windowName: (Optional) Caption text of the window to find.
If C{None} or not used any caption text will match the search.
@rtype: L{Window} or None
@return: A window that matches the request. There may be more matching
windows, but this method only returns one. If no matching window
is found, the return value is C{None}.
@raise WindowsError: An error occured while processing this request.
"""
# I'd love to reverse the order of the parameters
# but that might create some confusion. :(
hWnd = win32.FindWindow(className, windowName)
if hWnd:
return Window(hWnd) | [
"def",
"find_window",
"(",
"className",
"=",
"None",
",",
"windowName",
"=",
"None",
")",
":",
"# I'd love to reverse the order of the parameters",
"# but that might create some confusion. :(",
"hWnd",
"=",
"win32",
".",
"FindWindow",
"(",
"className",
",",
"windowName",
")",
"if",
"hWnd",
":",
"return",
"Window",
"(",
"hWnd",
")"
] | 41.357143 | 23 |
def add_marshaller(self, marshallers):
""" Add a marshaller/s to the user provided list.
Adds a marshaller or a list of them to the user provided set of
marshallers.
Note that the builtin marshallers take priority when choosing
the right marshaller.
.. versionchanged:: 0.2
All marshallers must now inherit from
``hdf5storage.Marshallers.TypeMarshaller``.
.. versionchanged:: 0.2
Builtin marshallers take priority over user provided ones.
Parameters
----------
marshallers : marshaller or iterable of marshallers
The user marshaller/s to add to the user provided
collection. Must inherit from
``hdf5storage.Marshallers.TypeMarshaller``.
Raises
------
TypeError
If one of `marshallers` is the wrong type.
See Also
--------
hdf5storage.Marshallers.TypeMarshaller
"""
if not isinstance(marshallers, collections.Iterable):
marshallers = [marshallers]
for m in marshallers:
if not isinstance(m, Marshallers.TypeMarshaller):
raise TypeError('Each marshaller must inherit from '
'hdf5storage.Marshallers.'
'TypeMarshaller.')
if m not in self._user_marshallers:
self._user_marshallers.append(m)
self._update_marshallers() | [
"def",
"add_marshaller",
"(",
"self",
",",
"marshallers",
")",
":",
"if",
"not",
"isinstance",
"(",
"marshallers",
",",
"collections",
".",
"Iterable",
")",
":",
"marshallers",
"=",
"[",
"marshallers",
"]",
"for",
"m",
"in",
"marshallers",
":",
"if",
"not",
"isinstance",
"(",
"m",
",",
"Marshallers",
".",
"TypeMarshaller",
")",
":",
"raise",
"TypeError",
"(",
"'Each marshaller must inherit from '",
"'hdf5storage.Marshallers.'",
"'TypeMarshaller.'",
")",
"if",
"m",
"not",
"in",
"self",
".",
"_user_marshallers",
":",
"self",
".",
"_user_marshallers",
".",
"append",
"(",
"m",
")",
"self",
".",
"_update_marshallers",
"(",
")"
] | 33.767442 | 19.906977 |
def Split(axis, a, n):
"""
Split op with n splits.
"""
return tuple(np.split(np.copy(a), n, axis=axis)) | [
"def",
"Split",
"(",
"axis",
",",
"a",
",",
"n",
")",
":",
"return",
"tuple",
"(",
"np",
".",
"split",
"(",
"np",
".",
"copy",
"(",
"a",
")",
",",
"n",
",",
"axis",
"=",
"axis",
")",
")"
] | 23 | 8.6 |
def change_pin(ctx, pin, new_pin):
"""
Change the PIN code.
The PIN must be between 6 and 8 characters long, and supports any type of
alphanumeric characters. For cross-platform compatibility,
numeric digits are recommended.
"""
controller = ctx.obj['controller']
if not pin:
pin = _prompt_pin(ctx, prompt='Enter your current PIN')
if not new_pin:
new_pin = click.prompt(
'Enter your new PIN', default='', hide_input=True,
show_default=False, confirmation_prompt=True, err=True)
if not _valid_pin_length(pin):
ctx.fail('Current PIN must be between 6 and 8 characters long.')
if not _valid_pin_length(new_pin):
ctx.fail('New PIN must be between 6 and 8 characters long.')
try:
controller.change_pin(pin, new_pin)
click.echo('New PIN set.')
except AuthenticationBlocked as e:
logger.debug('PIN is blocked.', exc_info=e)
ctx.fail('PIN is blocked.')
except WrongPin as e:
logger.debug(
'Failed to change PIN, %d tries left', e.tries_left, exc_info=e)
ctx.fail('PIN change failed - %d tries left.' % e.tries_left) | [
"def",
"change_pin",
"(",
"ctx",
",",
"pin",
",",
"new_pin",
")",
":",
"controller",
"=",
"ctx",
".",
"obj",
"[",
"'controller'",
"]",
"if",
"not",
"pin",
":",
"pin",
"=",
"_prompt_pin",
"(",
"ctx",
",",
"prompt",
"=",
"'Enter your current PIN'",
")",
"if",
"not",
"new_pin",
":",
"new_pin",
"=",
"click",
".",
"prompt",
"(",
"'Enter your new PIN'",
",",
"default",
"=",
"''",
",",
"hide_input",
"=",
"True",
",",
"show_default",
"=",
"False",
",",
"confirmation_prompt",
"=",
"True",
",",
"err",
"=",
"True",
")",
"if",
"not",
"_valid_pin_length",
"(",
"pin",
")",
":",
"ctx",
".",
"fail",
"(",
"'Current PIN must be between 6 and 8 characters long.'",
")",
"if",
"not",
"_valid_pin_length",
"(",
"new_pin",
")",
":",
"ctx",
".",
"fail",
"(",
"'New PIN must be between 6 and 8 characters long.'",
")",
"try",
":",
"controller",
".",
"change_pin",
"(",
"pin",
",",
"new_pin",
")",
"click",
".",
"echo",
"(",
"'New PIN set.'",
")",
"except",
"AuthenticationBlocked",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"'PIN is blocked.'",
",",
"exc_info",
"=",
"e",
")",
"ctx",
".",
"fail",
"(",
"'PIN is blocked.'",
")",
"except",
"WrongPin",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"'Failed to change PIN, %d tries left'",
",",
"e",
".",
"tries_left",
",",
"exc_info",
"=",
"e",
")",
"ctx",
".",
"fail",
"(",
"'PIN change failed - %d tries left.'",
"%",
"e",
".",
"tries_left",
")"
] | 32.027778 | 21.138889 |
def decimal_field_data(field, **kwargs):
"""
Return random value for DecimalField
>>> result = any_form_field(forms.DecimalField(max_value=100, min_value=11, max_digits=4, decimal_places = 2))
>>> type(result)
<type 'str'>
>>> from decimal import Decimal
>>> Decimal(result) >= 11, Decimal(result) <= Decimal('99.99')
(True, True)
"""
min_value = 0
max_value = 10
from django.core.validators import MinValueValidator, MaxValueValidator
for elem in field.validators:
if isinstance(elem, MinValueValidator):
min_value = elem.limit_value
if isinstance(elem, MaxValueValidator):
max_value = elem.limit_value
if (field.max_digits and field.decimal_places):
from decimal import Decimal
max_value = min(max_value,
Decimal('%s.%s' % ('9'*(field.max_digits-field.decimal_places),
'9'*field.decimal_places)))
min_value = kwargs.get('min_value') or min_value
max_value = kwargs.get('max_value') or max_value
return str(xunit.any_decimal(min_value=min_value,
max_value=max_value,
decimal_places = field.decimal_places or 2)) | [
"def",
"decimal_field_data",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"min_value",
"=",
"0",
"max_value",
"=",
"10",
"from",
"django",
".",
"core",
".",
"validators",
"import",
"MinValueValidator",
",",
"MaxValueValidator",
"for",
"elem",
"in",
"field",
".",
"validators",
":",
"if",
"isinstance",
"(",
"elem",
",",
"MinValueValidator",
")",
":",
"min_value",
"=",
"elem",
".",
"limit_value",
"if",
"isinstance",
"(",
"elem",
",",
"MaxValueValidator",
")",
":",
"max_value",
"=",
"elem",
".",
"limit_value",
"if",
"(",
"field",
".",
"max_digits",
"and",
"field",
".",
"decimal_places",
")",
":",
"from",
"decimal",
"import",
"Decimal",
"max_value",
"=",
"min",
"(",
"max_value",
",",
"Decimal",
"(",
"'%s.%s'",
"%",
"(",
"'9'",
"*",
"(",
"field",
".",
"max_digits",
"-",
"field",
".",
"decimal_places",
")",
",",
"'9'",
"*",
"field",
".",
"decimal_places",
")",
")",
")",
"min_value",
"=",
"kwargs",
".",
"get",
"(",
"'min_value'",
")",
"or",
"min_value",
"max_value",
"=",
"kwargs",
".",
"get",
"(",
"'max_value'",
")",
"or",
"max_value",
"return",
"str",
"(",
"xunit",
".",
"any_decimal",
"(",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
",",
"decimal_places",
"=",
"field",
".",
"decimal_places",
"or",
"2",
")",
")"
] | 39.83871 | 18.483871 |
def solve(self):
""" Solves AC optimal power flow.
"""
case = self.om.case
self._base_mva = case.base_mva
# TODO: Find an explanation for this value.
self.opt["cost_mult"] = 1e-4
# Unpack the OPF model.
self._bs, self._ln, self._gn, _ = self._unpack_model(self.om)
# Compute problem dimensions.
self._ipol, _, self._nb, self._nl, _, self._ny, self._nxyz = \
self._dimension_data(self._bs, self._ln, self._gn)
# Compute problem dimensions.
self._ng = len(self._gn)
# gpol = [g for g in gn if g.pcost_model == POLYNOMIAL]
# Linear constraints (l <= A*x <= u).
A, l, u = self.om.linear_constraints()
# AA, bb = self._linear_constraints(self.om)
_, xmin, xmax = self._var_bounds()
# Select an interior initial point for interior point solver.
x0 = self._initial_interior_point(self._bs, self._gn, xmin, xmax, self._ny)
# Build admittance matrices.
self._Ybus, self._Yf, self._Yt = case.Y
# Optimisation variables.
self._Pg = self.om.get_var("Pg")
self._Qg = self.om.get_var("Qg")
self._Va = self.om.get_var("Va")
self._Vm = self.om.get_var("Vm")
# Adds a constraint on the reference bus angles.
# xmin, xmax = self._ref_bus_angle_constraint(bs, Va, xmin, xmax)
# Solve using Python Interior Point Solver (PIPS).
s = self._solve(x0, A, l, u, xmin, xmax)
Vang, Vmag, Pgen, Qgen = self._update_solution_data(s)
self._update_case(self._bs, self._ln, self._gn, self._base_mva,
self._Yf, self._Yt, Vang, Vmag, Pgen, Qgen, s["lmbda"])
return s | [
"def",
"solve",
"(",
"self",
")",
":",
"case",
"=",
"self",
".",
"om",
".",
"case",
"self",
".",
"_base_mva",
"=",
"case",
".",
"base_mva",
"# TODO: Find an explanation for this value.",
"self",
".",
"opt",
"[",
"\"cost_mult\"",
"]",
"=",
"1e-4",
"# Unpack the OPF model.",
"self",
".",
"_bs",
",",
"self",
".",
"_ln",
",",
"self",
".",
"_gn",
",",
"_",
"=",
"self",
".",
"_unpack_model",
"(",
"self",
".",
"om",
")",
"# Compute problem dimensions.",
"self",
".",
"_ipol",
",",
"_",
",",
"self",
".",
"_nb",
",",
"self",
".",
"_nl",
",",
"_",
",",
"self",
".",
"_ny",
",",
"self",
".",
"_nxyz",
"=",
"self",
".",
"_dimension_data",
"(",
"self",
".",
"_bs",
",",
"self",
".",
"_ln",
",",
"self",
".",
"_gn",
")",
"# Compute problem dimensions.",
"self",
".",
"_ng",
"=",
"len",
"(",
"self",
".",
"_gn",
")",
"# gpol = [g for g in gn if g.pcost_model == POLYNOMIAL]",
"# Linear constraints (l <= A*x <= u).",
"A",
",",
"l",
",",
"u",
"=",
"self",
".",
"om",
".",
"linear_constraints",
"(",
")",
"# AA, bb = self._linear_constraints(self.om)",
"_",
",",
"xmin",
",",
"xmax",
"=",
"self",
".",
"_var_bounds",
"(",
")",
"# Select an interior initial point for interior point solver.",
"x0",
"=",
"self",
".",
"_initial_interior_point",
"(",
"self",
".",
"_bs",
",",
"self",
".",
"_gn",
",",
"xmin",
",",
"xmax",
",",
"self",
".",
"_ny",
")",
"# Build admittance matrices.",
"self",
".",
"_Ybus",
",",
"self",
".",
"_Yf",
",",
"self",
".",
"_Yt",
"=",
"case",
".",
"Y",
"# Optimisation variables.",
"self",
".",
"_Pg",
"=",
"self",
".",
"om",
".",
"get_var",
"(",
"\"Pg\"",
")",
"self",
".",
"_Qg",
"=",
"self",
".",
"om",
".",
"get_var",
"(",
"\"Qg\"",
")",
"self",
".",
"_Va",
"=",
"self",
".",
"om",
".",
"get_var",
"(",
"\"Va\"",
")",
"self",
".",
"_Vm",
"=",
"self",
".",
"om",
".",
"get_var",
"(",
"\"Vm\"",
")",
"# Adds a constraint on the reference bus angles.",
"# xmin, xmax = self._ref_bus_angle_constraint(bs, Va, xmin, xmax)",
"# Solve using Python Interior Point Solver (PIPS).",
"s",
"=",
"self",
".",
"_solve",
"(",
"x0",
",",
"A",
",",
"l",
",",
"u",
",",
"xmin",
",",
"xmax",
")",
"Vang",
",",
"Vmag",
",",
"Pgen",
",",
"Qgen",
"=",
"self",
".",
"_update_solution_data",
"(",
"s",
")",
"self",
".",
"_update_case",
"(",
"self",
".",
"_bs",
",",
"self",
".",
"_ln",
",",
"self",
".",
"_gn",
",",
"self",
".",
"_base_mva",
",",
"self",
".",
"_Yf",
",",
"self",
".",
"_Yt",
",",
"Vang",
",",
"Vmag",
",",
"Pgen",
",",
"Qgen",
",",
"s",
"[",
"\"lmbda\"",
"]",
")",
"return",
"s"
] | 34.326531 | 20.244898 |
def plot(*args, ax=None, **kwargs):
"""
Plots but automatically resizes x axis.
.. versionadded:: 1.4
Parameters
----------
args
Passed on to :meth:`matplotlib.axis.Axis.plot`.
ax : :class:`matplotlib.axis.Axis`, optional
The axis to plot to.
kwargs
Passed on to :meth:`matplotlib.axis.Axis.plot`.
"""
if ax is None:
fig, ax = _setup_axes()
pl = ax.plot(*args, **kwargs)
if _np.shape(args)[0] > 1:
if type(args[1]) is not str:
min_x = min(args[0])
max_x = max(args[0])
ax.set_xlim((min_x, max_x))
return pl | [
"def",
"plot",
"(",
"*",
"args",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"fig",
",",
"ax",
"=",
"_setup_axes",
"(",
")",
"pl",
"=",
"ax",
".",
"plot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"_np",
".",
"shape",
"(",
"args",
")",
"[",
"0",
"]",
">",
"1",
":",
"if",
"type",
"(",
"args",
"[",
"1",
"]",
")",
"is",
"not",
"str",
":",
"min_x",
"=",
"min",
"(",
"args",
"[",
"0",
"]",
")",
"max_x",
"=",
"max",
"(",
"args",
"[",
"0",
"]",
")",
"ax",
".",
"set_xlim",
"(",
"(",
"min_x",
",",
"max_x",
")",
")",
"return",
"pl"
] | 21.892857 | 18.678571 |
def emit_edge(self, name1, name2, **props):
"""emit an edge from <name1> to <name2>.
edge properties: see http://www.graphviz.org/doc/info/attrs.html
"""
attrs = ['%s="%s"' % (prop, value) for prop, value in props.items()]
n_from, n_to = normalize_node_id(name1), normalize_node_id(name2)
self.emit("%s -> %s [%s];" % (n_from, n_to, ", ".join(sorted(attrs)))) | [
"def",
"emit_edge",
"(",
"self",
",",
"name1",
",",
"name2",
",",
"*",
"*",
"props",
")",
":",
"attrs",
"=",
"[",
"'%s=\"%s\"'",
"%",
"(",
"prop",
",",
"value",
")",
"for",
"prop",
",",
"value",
"in",
"props",
".",
"items",
"(",
")",
"]",
"n_from",
",",
"n_to",
"=",
"normalize_node_id",
"(",
"name1",
")",
",",
"normalize_node_id",
"(",
"name2",
")",
"self",
".",
"emit",
"(",
"\"%s -> %s [%s];\"",
"%",
"(",
"n_from",
",",
"n_to",
",",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"attrs",
")",
")",
")",
")"
] | 57.285714 | 20.285714 |
def get_agent_queues_by_names(self, queue_names, project=None, action_filter=None):
"""GetAgentQueuesByNames.
[Preview API] Get a list of agent queues by their names
:param [str] queue_names: A comma-separated list of agent names to retrieve
:param str project: Project ID or project name
:param str action_filter: Filter by whether the calling user has use or manage permissions
:rtype: [TaskAgentQueue]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if queue_names is not None:
queue_names = ",".join(queue_names)
query_parameters['queueNames'] = self._serialize.query('queue_names', queue_names, 'str')
if action_filter is not None:
query_parameters['actionFilter'] = self._serialize.query('action_filter', action_filter, 'str')
response = self._send(http_method='GET',
location_id='900fa995-c559-4923-aae7-f8424fe4fbea',
version='5.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[TaskAgentQueue]', self._unwrap_collection(response)) | [
"def",
"get_agent_queues_by_names",
"(",
"self",
",",
"queue_names",
",",
"project",
"=",
"None",
",",
"action_filter",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'project'",
",",
"project",
",",
"'str'",
")",
"query_parameters",
"=",
"{",
"}",
"if",
"queue_names",
"is",
"not",
"None",
":",
"queue_names",
"=",
"\",\"",
".",
"join",
"(",
"queue_names",
")",
"query_parameters",
"[",
"'queueNames'",
"]",
"=",
"self",
".",
"_serialize",
".",
"query",
"(",
"'queue_names'",
",",
"queue_names",
",",
"'str'",
")",
"if",
"action_filter",
"is",
"not",
"None",
":",
"query_parameters",
"[",
"'actionFilter'",
"]",
"=",
"self",
".",
"_serialize",
".",
"query",
"(",
"'action_filter'",
",",
"action_filter",
",",
"'str'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'GET'",
",",
"location_id",
"=",
"'900fa995-c559-4923-aae7-f8424fe4fbea'",
",",
"version",
"=",
"'5.1-preview.1'",
",",
"route_values",
"=",
"route_values",
",",
"query_parameters",
"=",
"query_parameters",
")",
"return",
"self",
".",
"_deserialize",
"(",
"'[TaskAgentQueue]'",
",",
"self",
".",
"_unwrap_collection",
"(",
"response",
")",
")"
] | 58.391304 | 24.391304 |
def bisine_wave(frequency):
"""Emit two sine waves, in stereo at different octaves."""
#
# We can first our existing sine generator to generate two different
# waves.
f_hi = frequency
f_lo = frequency / 2.0
with tf.name_scope('hi'):
sine_hi = sine_wave(f_hi)
with tf.name_scope('lo'):
sine_lo = sine_wave(f_lo)
#
# Now, we have two tensors of shape [1, _samples(), 1]. By concatenating
# them along axis 2, we get a tensor of shape [1, _samples(), 2]---a
# stereo waveform.
return tf.concat([sine_lo, sine_hi], axis=2) | [
"def",
"bisine_wave",
"(",
"frequency",
")",
":",
"#",
"# We can first our existing sine generator to generate two different",
"# waves.",
"f_hi",
"=",
"frequency",
"f_lo",
"=",
"frequency",
"/",
"2.0",
"with",
"tf",
".",
"name_scope",
"(",
"'hi'",
")",
":",
"sine_hi",
"=",
"sine_wave",
"(",
"f_hi",
")",
"with",
"tf",
".",
"name_scope",
"(",
"'lo'",
")",
":",
"sine_lo",
"=",
"sine_wave",
"(",
"f_lo",
")",
"#",
"# Now, we have two tensors of shape [1, _samples(), 1]. By concatenating",
"# them along axis 2, we get a tensor of shape [1, _samples(), 2]---a",
"# stereo waveform.",
"return",
"tf",
".",
"concat",
"(",
"[",
"sine_lo",
",",
"sine_hi",
"]",
",",
"axis",
"=",
"2",
")"
] | 33.5625 | 20.1875 |
def _generate_docker_image_version(layers, runtime):
"""
Generate the Docker TAG that will be used to create the image
Parameters
----------
layers list(samcli.commands.local.lib.provider.Layer)
List of the layers
runtime str
Runtime of the image to create
Returns
-------
str
String representing the TAG to be attached to the image
"""
# Docker has a concept of a TAG on an image. This is plus the REPOSITORY is a way to determine
# a version of the image. We will produced a TAG for a combination of the runtime with the layers
# specified in the template. This will allow reuse of the runtime and layers across different
# functions that are defined. If two functions use the same runtime with the same layers (in the
# same order), SAM CLI will only produce one image and use this image across both functions for invoke.
return runtime + '-' + hashlib.sha256(
"-".join([layer.name for layer in layers]).encode('utf-8')).hexdigest()[0:25] | [
"def",
"_generate_docker_image_version",
"(",
"layers",
",",
"runtime",
")",
":",
"# Docker has a concept of a TAG on an image. This is plus the REPOSITORY is a way to determine",
"# a version of the image. We will produced a TAG for a combination of the runtime with the layers",
"# specified in the template. This will allow reuse of the runtime and layers across different",
"# functions that are defined. If two functions use the same runtime with the same layers (in the",
"# same order), SAM CLI will only produce one image and use this image across both functions for invoke.",
"return",
"runtime",
"+",
"'-'",
"+",
"hashlib",
".",
"sha256",
"(",
"\"-\"",
".",
"join",
"(",
"[",
"layer",
".",
"name",
"for",
"layer",
"in",
"layers",
"]",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
"0",
":",
"25",
"]"
] | 43.88 | 31.32 |
def show_heatmap(self, blocking=True, output_file=None, enable_scroll=False):
"""Method to actually display the heatmap created.
@param blocking: When set to False makes an unblocking plot show.
@param output_file: If not None the heatmap image is output to this
file. Supported formats: (eps, pdf, pgf, png, ps, raw, rgba, svg,
svgz)
@param enable_scroll: Flag used add a scroll bar to scroll long files.
"""
if output_file is None:
if enable_scroll:
# Add a new axes which will be used as scroll bar.
axpos = plt.axes([0.12, 0.1, 0.625, 0.03])
spos = Slider(axpos, "Scroll", 10, len(self.pyfile.lines))
def update(val):
"""Method to update position when slider is moved."""
pos = spos.val
self.ax.axis([0, 1, pos, pos - 10])
self.fig.canvas.draw_idle()
spos.on_changed(update)
plt.show(block=blocking)
else:
plt.savefig(output_file) | [
"def",
"show_heatmap",
"(",
"self",
",",
"blocking",
"=",
"True",
",",
"output_file",
"=",
"None",
",",
"enable_scroll",
"=",
"False",
")",
":",
"if",
"output_file",
"is",
"None",
":",
"if",
"enable_scroll",
":",
"# Add a new axes which will be used as scroll bar.",
"axpos",
"=",
"plt",
".",
"axes",
"(",
"[",
"0.12",
",",
"0.1",
",",
"0.625",
",",
"0.03",
"]",
")",
"spos",
"=",
"Slider",
"(",
"axpos",
",",
"\"Scroll\"",
",",
"10",
",",
"len",
"(",
"self",
".",
"pyfile",
".",
"lines",
")",
")",
"def",
"update",
"(",
"val",
")",
":",
"\"\"\"Method to update position when slider is moved.\"\"\"",
"pos",
"=",
"spos",
".",
"val",
"self",
".",
"ax",
".",
"axis",
"(",
"[",
"0",
",",
"1",
",",
"pos",
",",
"pos",
"-",
"10",
"]",
")",
"self",
".",
"fig",
".",
"canvas",
".",
"draw_idle",
"(",
")",
"spos",
".",
"on_changed",
"(",
"update",
")",
"plt",
".",
"show",
"(",
"block",
"=",
"blocking",
")",
"else",
":",
"plt",
".",
"savefig",
"(",
"output_file",
")"
] | 44.04 | 20.2 |
def find_module(self, fullname, path=None):
"""
Find the appropriate loader for module ``name``
:param fullname: ``__name__`` of the module to import
:type fullname: str
:param path: ``__path__`` of the *parent* package already imported
:type path: str or None
"""
# path points to the top-level package path if any
# and we can only import sub-modules/-packages
if path is None:
return
if fullname.startswith(self.module_prefix):
return self
else:
return None | [
"def",
"find_module",
"(",
"self",
",",
"fullname",
",",
"path",
"=",
"None",
")",
":",
"# path points to the top-level package path if any",
"# and we can only import sub-modules/-packages",
"if",
"path",
"is",
"None",
":",
"return",
"if",
"fullname",
".",
"startswith",
"(",
"self",
".",
"module_prefix",
")",
":",
"return",
"self",
"else",
":",
"return",
"None"
] | 33.941176 | 16.294118 |
def make_article_info_dates(self):
"""
Makes the section containing important dates for the article: typically
Received, Accepted, and Published.
"""
dates_div = etree.Element('div', {'id': 'article-dates'})
d = './front/article-meta/history/date'
received = self.article.root.xpath(d + "[@date-type='received']")
accepted = self.article.root.xpath(d + "[@date-type='accepted']")
if received:
b = etree.SubElement(dates_div, 'b')
b.text = 'Received: '
dt = self.date_tuple_from_date(received[0], 'Received')
formatted_date_string = self.format_date_string(dt)
append_new_text(dates_div, formatted_date_string + '; ')
if accepted:
b = etree.SubElement(dates_div, 'b')
b.text = 'Accepted: '
dt = self.date_tuple_from_date(accepted[0], 'Accepted')
formatted_date_string = self.format_date_string(dt)
append_new_text(dates_div, formatted_date_string + '; ')
#Published date is required
pub_date = self.article.root.xpath("./front/article-meta/pub-date[@pub-type='epub']")[0]
b = etree.SubElement(dates_div, 'b')
b.text = 'Published: '
dt = self.date_tuple_from_date(pub_date, 'Published')
formatted_date_string = self.format_date_string(dt)
append_new_text(dates_div, formatted_date_string)
return dates_div | [
"def",
"make_article_info_dates",
"(",
"self",
")",
":",
"dates_div",
"=",
"etree",
".",
"Element",
"(",
"'div'",
",",
"{",
"'id'",
":",
"'article-dates'",
"}",
")",
"d",
"=",
"'./front/article-meta/history/date'",
"received",
"=",
"self",
".",
"article",
".",
"root",
".",
"xpath",
"(",
"d",
"+",
"\"[@date-type='received']\"",
")",
"accepted",
"=",
"self",
".",
"article",
".",
"root",
".",
"xpath",
"(",
"d",
"+",
"\"[@date-type='accepted']\"",
")",
"if",
"received",
":",
"b",
"=",
"etree",
".",
"SubElement",
"(",
"dates_div",
",",
"'b'",
")",
"b",
".",
"text",
"=",
"'Received: '",
"dt",
"=",
"self",
".",
"date_tuple_from_date",
"(",
"received",
"[",
"0",
"]",
",",
"'Received'",
")",
"formatted_date_string",
"=",
"self",
".",
"format_date_string",
"(",
"dt",
")",
"append_new_text",
"(",
"dates_div",
",",
"formatted_date_string",
"+",
"'; '",
")",
"if",
"accepted",
":",
"b",
"=",
"etree",
".",
"SubElement",
"(",
"dates_div",
",",
"'b'",
")",
"b",
".",
"text",
"=",
"'Accepted: '",
"dt",
"=",
"self",
".",
"date_tuple_from_date",
"(",
"accepted",
"[",
"0",
"]",
",",
"'Accepted'",
")",
"formatted_date_string",
"=",
"self",
".",
"format_date_string",
"(",
"dt",
")",
"append_new_text",
"(",
"dates_div",
",",
"formatted_date_string",
"+",
"'; '",
")",
"#Published date is required",
"pub_date",
"=",
"self",
".",
"article",
".",
"root",
".",
"xpath",
"(",
"\"./front/article-meta/pub-date[@pub-type='epub']\"",
")",
"[",
"0",
"]",
"b",
"=",
"etree",
".",
"SubElement",
"(",
"dates_div",
",",
"'b'",
")",
"b",
".",
"text",
"=",
"'Published: '",
"dt",
"=",
"self",
".",
"date_tuple_from_date",
"(",
"pub_date",
",",
"'Published'",
")",
"formatted_date_string",
"=",
"self",
".",
"format_date_string",
"(",
"dt",
")",
"append_new_text",
"(",
"dates_div",
",",
"formatted_date_string",
")",
"return",
"dates_div"
] | 46.419355 | 19.322581 |
def dstationarystate(self, k, param):
"""See docs for `Model` abstract base class."""
assert param not in self.distributionparams
assert param in self.freeparams or param == self.distributedparam
ds = self._models[k].dstationarystate(param)
return ds | [
"def",
"dstationarystate",
"(",
"self",
",",
"k",
",",
"param",
")",
":",
"assert",
"param",
"not",
"in",
"self",
".",
"distributionparams",
"assert",
"param",
"in",
"self",
".",
"freeparams",
"or",
"param",
"==",
"self",
".",
"distributedparam",
"ds",
"=",
"self",
".",
"_models",
"[",
"k",
"]",
".",
"dstationarystate",
"(",
"param",
")",
"return",
"ds"
] | 47.5 | 13.666667 |
def complete_value_catching_error(
self,
return_type: GraphQLOutputType,
field_nodes: List[FieldNode],
info: GraphQLResolveInfo,
path: ResponsePath,
result: Any,
) -> AwaitableOrValue[Any]:
"""Complete a value while catching an error.
This is a small wrapper around completeValue which detects and logs errors in
the execution context.
"""
try:
if isawaitable(result):
async def await_result():
value = self.complete_value(
return_type, field_nodes, info, path, await result
)
if isawaitable(value):
return await value
return value
completed = await_result()
else:
completed = self.complete_value(
return_type, field_nodes, info, path, result
)
if isawaitable(completed):
# noinspection PyShadowingNames
async def await_completed():
try:
return await completed
except Exception as error:
self.handle_field_error(error, field_nodes, path, return_type)
return await_completed()
return completed
except Exception as error:
self.handle_field_error(error, field_nodes, path, return_type)
return None | [
"def",
"complete_value_catching_error",
"(",
"self",
",",
"return_type",
":",
"GraphQLOutputType",
",",
"field_nodes",
":",
"List",
"[",
"FieldNode",
"]",
",",
"info",
":",
"GraphQLResolveInfo",
",",
"path",
":",
"ResponsePath",
",",
"result",
":",
"Any",
",",
")",
"->",
"AwaitableOrValue",
"[",
"Any",
"]",
":",
"try",
":",
"if",
"isawaitable",
"(",
"result",
")",
":",
"async",
"def",
"await_result",
"(",
")",
":",
"value",
"=",
"self",
".",
"complete_value",
"(",
"return_type",
",",
"field_nodes",
",",
"info",
",",
"path",
",",
"await",
"result",
")",
"if",
"isawaitable",
"(",
"value",
")",
":",
"return",
"await",
"value",
"return",
"value",
"completed",
"=",
"await_result",
"(",
")",
"else",
":",
"completed",
"=",
"self",
".",
"complete_value",
"(",
"return_type",
",",
"field_nodes",
",",
"info",
",",
"path",
",",
"result",
")",
"if",
"isawaitable",
"(",
"completed",
")",
":",
"# noinspection PyShadowingNames",
"async",
"def",
"await_completed",
"(",
")",
":",
"try",
":",
"return",
"await",
"completed",
"except",
"Exception",
"as",
"error",
":",
"self",
".",
"handle_field_error",
"(",
"error",
",",
"field_nodes",
",",
"path",
",",
"return_type",
")",
"return",
"await_completed",
"(",
")",
"return",
"completed",
"except",
"Exception",
"as",
"error",
":",
"self",
".",
"handle_field_error",
"(",
"error",
",",
"field_nodes",
",",
"path",
",",
"return_type",
")",
"return",
"None"
] | 35.166667 | 15.333333 |
def syslog_generate(str_processName, str_pid):
'''
Returns a string similar to:
Tue Oct 9 10:49:53 2012 pretoria message.py[26873]:
where 'pretoria' is the hostname, 'message.py' is the current process
name and 26873 is the current process id.
'''
localtime = time.asctime( time.localtime(time.time()) )
hostname = os.uname()[1]
syslog = '%s %s %s[%s]' % (localtime, hostname, str_processName, str_pid)
return syslog | [
"def",
"syslog_generate",
"(",
"str_processName",
",",
"str_pid",
")",
":",
"localtime",
"=",
"time",
".",
"asctime",
"(",
"time",
".",
"localtime",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
"hostname",
"=",
"os",
".",
"uname",
"(",
")",
"[",
"1",
"]",
"syslog",
"=",
"'%s %s %s[%s]'",
"%",
"(",
"localtime",
",",
"hostname",
",",
"str_processName",
",",
"str_pid",
")",
"return",
"syslog"
] | 36.846154 | 24.384615 |
def estimate_achievable_tmid_precision(snr, t_ingress_min=10,
t_duration_hr=2.14):
'''Using Carter et al. 2009's estimate, calculate the theoretical optimal
precision on mid-transit time measurement possible given a transit of a
particular SNR.
The relation used is::
sigma_tc = Q^{-1} * T * sqrt(θ/2)
Q = SNR of the transit.
T = transit duration, which is 2.14 hours from discovery paper.
θ = τ/T = ratio of ingress to total duration
~= (few minutes [guess]) / 2.14 hours
Parameters
----------
snr : float
The measured signal-to-noise of the transit, e,g. from
:py:func:`astrobase.periodbase.kbls.bls_stats_singleperiod` or from
running the `.compute_stats()` method on an Astropy BoxLeastSquares
object.
t_ingress_min : float
The ingress duration in minutes. This is t_I to t_II in Winn (2010)
nomenclature.
t_duration_hr : float
The transit duration in hours. This is t_I to t_IV in Winn (2010)
nomenclature.
Returns
-------
float
Returns the precision achievable for transit-center time as calculated
from the relation above. This is in days.
'''
t_ingress = t_ingress_min*u.minute
t_duration = t_duration_hr*u.hour
theta = t_ingress/t_duration
sigma_tc = (1/snr * t_duration * np.sqrt(theta/2))
LOGINFO('assuming t_ingress = {:.1f}'.format(t_ingress))
LOGINFO('assuming t_duration = {:.1f}'.format(t_duration))
LOGINFO('measured SNR={:.2f}\n\t'.format(snr) +
'-->theoretical sigma_tc = {:.2e} = {:.2e} = {:.2e}'.format(
sigma_tc.to(u.minute), sigma_tc.to(u.hour), sigma_tc.to(u.day)))
return sigma_tc.to(u.day).value | [
"def",
"estimate_achievable_tmid_precision",
"(",
"snr",
",",
"t_ingress_min",
"=",
"10",
",",
"t_duration_hr",
"=",
"2.14",
")",
":",
"t_ingress",
"=",
"t_ingress_min",
"*",
"u",
".",
"minute",
"t_duration",
"=",
"t_duration_hr",
"*",
"u",
".",
"hour",
"theta",
"=",
"t_ingress",
"/",
"t_duration",
"sigma_tc",
"=",
"(",
"1",
"/",
"snr",
"*",
"t_duration",
"*",
"np",
".",
"sqrt",
"(",
"theta",
"/",
"2",
")",
")",
"LOGINFO",
"(",
"'assuming t_ingress = {:.1f}'",
".",
"format",
"(",
"t_ingress",
")",
")",
"LOGINFO",
"(",
"'assuming t_duration = {:.1f}'",
".",
"format",
"(",
"t_duration",
")",
")",
"LOGINFO",
"(",
"'measured SNR={:.2f}\\n\\t'",
".",
"format",
"(",
"snr",
")",
"+",
"'-->theoretical sigma_tc = {:.2e} = {:.2e} = {:.2e}'",
".",
"format",
"(",
"sigma_tc",
".",
"to",
"(",
"u",
".",
"minute",
")",
",",
"sigma_tc",
".",
"to",
"(",
"u",
".",
"hour",
")",
",",
"sigma_tc",
".",
"to",
"(",
"u",
".",
"day",
")",
")",
")",
"return",
"sigma_tc",
".",
"to",
"(",
"u",
".",
"day",
")",
".",
"value"
] | 32.018182 | 26.709091 |
def write_main_jobwrappers(self):
'''
Writes out 'jobs' as wrapped toil objects in preparation for calling.
:return: A string representing this.
'''
main_section = ''
# toil cannot technically start with multiple jobs, so an empty
# 'initialize_jobs' function is always called first to get around this
main_section = main_section + '\n job0 = Job.wrapJobFn(initialize_jobs)\n'
# declare each job in main as a wrapped toil function in order of priority
for wf in self.workflows_dictionary:
for assignment in self.workflows_dictionary[wf]:
if assignment.startswith('call'):
main_section += ' job0 = job0.encapsulate()\n'
main_section += self.write_main_jobwrappers_call(self.workflows_dictionary[wf][assignment])
if assignment.startswith('scatter'):
main_section += ' job0 = job0.encapsulate()\n'
main_section += self.write_main_jobwrappers_scatter(self.workflows_dictionary[wf][assignment],
assignment)
if assignment.startswith('if'):
main_section += ' if {}:\n'.format(self.workflows_dictionary[wf][assignment]['expression'])
main_section += self.write_main_jobwrappers_if(self.workflows_dictionary[wf][assignment]['body'])
main_section += '\n fileStore.start(job0)\n'
return main_section | [
"def",
"write_main_jobwrappers",
"(",
"self",
")",
":",
"main_section",
"=",
"''",
"# toil cannot technically start with multiple jobs, so an empty",
"# 'initialize_jobs' function is always called first to get around this",
"main_section",
"=",
"main_section",
"+",
"'\\n job0 = Job.wrapJobFn(initialize_jobs)\\n'",
"# declare each job in main as a wrapped toil function in order of priority",
"for",
"wf",
"in",
"self",
".",
"workflows_dictionary",
":",
"for",
"assignment",
"in",
"self",
".",
"workflows_dictionary",
"[",
"wf",
"]",
":",
"if",
"assignment",
".",
"startswith",
"(",
"'call'",
")",
":",
"main_section",
"+=",
"' job0 = job0.encapsulate()\\n'",
"main_section",
"+=",
"self",
".",
"write_main_jobwrappers_call",
"(",
"self",
".",
"workflows_dictionary",
"[",
"wf",
"]",
"[",
"assignment",
"]",
")",
"if",
"assignment",
".",
"startswith",
"(",
"'scatter'",
")",
":",
"main_section",
"+=",
"' job0 = job0.encapsulate()\\n'",
"main_section",
"+=",
"self",
".",
"write_main_jobwrappers_scatter",
"(",
"self",
".",
"workflows_dictionary",
"[",
"wf",
"]",
"[",
"assignment",
"]",
",",
"assignment",
")",
"if",
"assignment",
".",
"startswith",
"(",
"'if'",
")",
":",
"main_section",
"+=",
"' if {}:\\n'",
".",
"format",
"(",
"self",
".",
"workflows_dictionary",
"[",
"wf",
"]",
"[",
"assignment",
"]",
"[",
"'expression'",
"]",
")",
"main_section",
"+=",
"self",
".",
"write_main_jobwrappers_if",
"(",
"self",
".",
"workflows_dictionary",
"[",
"wf",
"]",
"[",
"assignment",
"]",
"[",
"'body'",
"]",
")",
"main_section",
"+=",
"'\\n fileStore.start(job0)\\n'",
"return",
"main_section"
] | 53.37931 | 33.586207 |
def file_exists(path, saltenv=None):
'''
.. versionadded:: 2016.3.0
This is a master-only function. Calling from the minion is not supported.
Use the given path and search relative to the pillar environments to see if
a file exists at that path.
If the ``saltenv`` argument is given, restrict search to that environment
only.
Will only work with ``pillar_roots``, not external pillars.
Returns True if the file is found, and False otherwise.
path
The path to the file in question. Will be treated as a relative path
saltenv
Optional argument to restrict the search to a specific saltenv
CLI Example:
.. code-block:: bash
salt '*' pillar.file_exists foo/bar.sls
'''
pillar_roots = __opts__.get('pillar_roots')
if not pillar_roots:
raise CommandExecutionError('No pillar_roots found. Are you running '
'this on the master?')
if saltenv:
if saltenv in pillar_roots:
pillar_roots = {saltenv: pillar_roots[saltenv]}
else:
return False
for env in pillar_roots:
for pillar_dir in pillar_roots[env]:
full_path = os.path.join(pillar_dir, path)
if __salt__['file.file_exists'](full_path):
return True
return False | [
"def",
"file_exists",
"(",
"path",
",",
"saltenv",
"=",
"None",
")",
":",
"pillar_roots",
"=",
"__opts__",
".",
"get",
"(",
"'pillar_roots'",
")",
"if",
"not",
"pillar_roots",
":",
"raise",
"CommandExecutionError",
"(",
"'No pillar_roots found. Are you running '",
"'this on the master?'",
")",
"if",
"saltenv",
":",
"if",
"saltenv",
"in",
"pillar_roots",
":",
"pillar_roots",
"=",
"{",
"saltenv",
":",
"pillar_roots",
"[",
"saltenv",
"]",
"}",
"else",
":",
"return",
"False",
"for",
"env",
"in",
"pillar_roots",
":",
"for",
"pillar_dir",
"in",
"pillar_roots",
"[",
"env",
"]",
":",
"full_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"pillar_dir",
",",
"path",
")",
"if",
"__salt__",
"[",
"'file.file_exists'",
"]",
"(",
"full_path",
")",
":",
"return",
"True",
"return",
"False"
] | 28.326087 | 26.543478 |
def result(self):
'''
:return: None if the result is not ready, the result from set_result, or raise the exception
from set_exception. If the result can be None, it is not possible to tell if the result is
available; use done() to determine that.
'''
try:
r = getattr(self, '_result')
except AttributeError:
return None
else:
if hasattr(self, '_exception'):
raise self._exception
else:
return r | [
"def",
"result",
"(",
"self",
")",
":",
"try",
":",
"r",
"=",
"getattr",
"(",
"self",
",",
"'_result'",
")",
"except",
"AttributeError",
":",
"return",
"None",
"else",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_exception'",
")",
":",
"raise",
"self",
".",
"_exception",
"else",
":",
"return",
"r"
] | 36.133333 | 23.466667 |
def build_disease_term(disease_info, alias_genes={}):
"""Build a disease phenotype object
Args:
disease_info(dict): Dictionary with phenotype information
alias_genes(dict): {
<alias_symbol>: {
'true': hgnc_id or None,
'ids': [<hgnc_id>, ...]}}
Returns:
disease_obj(dict): Formated for mongodb
disease_term = dict(
_id = str, # Same as disease_id
disease_id = str, # required, like OMIM:600233
disase_nr = int, # The disease nr, required
description = str, # required
source = str, # required
inheritance = list, # list of strings
genes = list, # List with integers that are hgnc_ids
hpo_terms = list, # List with str that are hpo_terms
)
"""
try:
disease_nr = int(disease_info['mim_number'])
except KeyError:
raise KeyError("Diseases has to have a disease number")
except ValueError:
raise KeyError("Diseases nr has to be integer")
disease_id = "{0}:{1}".format('OMIM', disease_nr)
LOG.debug("Building disease term %s", disease_id)
try:
description = disease_info['description']
except KeyError:
raise KeyError("Diseases has to have a description")
disease_obj = DiseaseTerm(
disease_id=disease_id,
disease_nr=disease_nr,
description=description,
source='OMIM'
)
# Check if there where any inheritance information
inheritance_models = disease_info.get('inheritance')
if inheritance_models:
disease_obj['inheritance'] = list(inheritance_models)
hgnc_ids = set()
for hgnc_symbol in disease_info.get('hgnc_symbols', []):
## TODO need to consider genome build here?
if hgnc_symbol in alias_genes:
# If the symbol identifies a unique gene we add that
if alias_genes[hgnc_symbol]['true']:
hgnc_ids.add(alias_genes[hgnc_symbol]['true'])
else:
for hgnc_id in alias_genes[hgnc_symbol]['ids']:
hgnc_ids.add(hgnc_id)
else:
LOG.debug("Gene symbol %s could not be found in database", hgnc_symbol)
disease_obj['genes'] = list(hgnc_ids)
if 'hpo_terms' in disease_info:
disease_obj['hpo_terms'] = list(disease_info['hpo_terms'])
return disease_obj | [
"def",
"build_disease_term",
"(",
"disease_info",
",",
"alias_genes",
"=",
"{",
"}",
")",
":",
"try",
":",
"disease_nr",
"=",
"int",
"(",
"disease_info",
"[",
"'mim_number'",
"]",
")",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"Diseases has to have a disease number\"",
")",
"except",
"ValueError",
":",
"raise",
"KeyError",
"(",
"\"Diseases nr has to be integer\"",
")",
"disease_id",
"=",
"\"{0}:{1}\"",
".",
"format",
"(",
"'OMIM'",
",",
"disease_nr",
")",
"LOG",
".",
"debug",
"(",
"\"Building disease term %s\"",
",",
"disease_id",
")",
"try",
":",
"description",
"=",
"disease_info",
"[",
"'description'",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"Diseases has to have a description\"",
")",
"disease_obj",
"=",
"DiseaseTerm",
"(",
"disease_id",
"=",
"disease_id",
",",
"disease_nr",
"=",
"disease_nr",
",",
"description",
"=",
"description",
",",
"source",
"=",
"'OMIM'",
")",
"# Check if there where any inheritance information",
"inheritance_models",
"=",
"disease_info",
".",
"get",
"(",
"'inheritance'",
")",
"if",
"inheritance_models",
":",
"disease_obj",
"[",
"'inheritance'",
"]",
"=",
"list",
"(",
"inheritance_models",
")",
"hgnc_ids",
"=",
"set",
"(",
")",
"for",
"hgnc_symbol",
"in",
"disease_info",
".",
"get",
"(",
"'hgnc_symbols'",
",",
"[",
"]",
")",
":",
"## TODO need to consider genome build here?",
"if",
"hgnc_symbol",
"in",
"alias_genes",
":",
"# If the symbol identifies a unique gene we add that",
"if",
"alias_genes",
"[",
"hgnc_symbol",
"]",
"[",
"'true'",
"]",
":",
"hgnc_ids",
".",
"add",
"(",
"alias_genes",
"[",
"hgnc_symbol",
"]",
"[",
"'true'",
"]",
")",
"else",
":",
"for",
"hgnc_id",
"in",
"alias_genes",
"[",
"hgnc_symbol",
"]",
"[",
"'ids'",
"]",
":",
"hgnc_ids",
".",
"add",
"(",
"hgnc_id",
")",
"else",
":",
"LOG",
".",
"debug",
"(",
"\"Gene symbol %s could not be found in database\"",
",",
"hgnc_symbol",
")",
"disease_obj",
"[",
"'genes'",
"]",
"=",
"list",
"(",
"hgnc_ids",
")",
"if",
"'hpo_terms'",
"in",
"disease_info",
":",
"disease_obj",
"[",
"'hpo_terms'",
"]",
"=",
"list",
"(",
"disease_info",
"[",
"'hpo_terms'",
"]",
")",
"return",
"disease_obj"
] | 33.561644 | 20.356164 |
def to_json_file(self, path, file_name=None):
"""Writes output to a JSON file with the given file name"""
if bool(path) and os.path.isdir(path):
self.write_to_json(path, file_name)
else:
self.write_to_json(os.getcwd(), file_name) | [
"def",
"to_json_file",
"(",
"self",
",",
"path",
",",
"file_name",
"=",
"None",
")",
":",
"if",
"bool",
"(",
"path",
")",
"and",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"self",
".",
"write_to_json",
"(",
"path",
",",
"file_name",
")",
"else",
":",
"self",
".",
"write_to_json",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"file_name",
")"
] | 45.333333 | 9.833333 |
def save_as_png(self, filename, width=300, height=250, render_time=1):
"""Open saved html file in an virtual browser and save a screen shot to PNG format."""
self.driver.set_window_size(width, height)
self.driver.get('file://{path}/{filename}'.format(
path=os.getcwd(), filename=filename + ".html"))
time.sleep(render_time)
self.driver.save_screenshot(filename + ".png") | [
"def",
"save_as_png",
"(",
"self",
",",
"filename",
",",
"width",
"=",
"300",
",",
"height",
"=",
"250",
",",
"render_time",
"=",
"1",
")",
":",
"self",
".",
"driver",
".",
"set_window_size",
"(",
"width",
",",
"height",
")",
"self",
".",
"driver",
".",
"get",
"(",
"'file://{path}/{filename}'",
".",
"format",
"(",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
",",
"filename",
"=",
"filename",
"+",
"\".html\"",
")",
")",
"time",
".",
"sleep",
"(",
"render_time",
")",
"self",
".",
"driver",
".",
"save_screenshot",
"(",
"filename",
"+",
"\".png\"",
")"
] | 59.428571 | 14.285714 |
def del_restriction(self, command, user, event_types):
"""
Removes restriction for given `command`.
:param command: command on which the restriction should be removed.
:type command: str
:param user: username for which restriction should be removed.
:type user: str
:param event_types: types of events that should be removed from restriction.
:type event_types: list
"""
if user.lower() in self.commands_rights[command]:
for event_type in event_types:
try:
self.commands_rights[command][user.lower()].remove(event_type)
except ValueError:
pass
if not self.commands_rights[command][user.lower()]:
self.commands_rights[command].pop(user.lower()) | [
"def",
"del_restriction",
"(",
"self",
",",
"command",
",",
"user",
",",
"event_types",
")",
":",
"if",
"user",
".",
"lower",
"(",
")",
"in",
"self",
".",
"commands_rights",
"[",
"command",
"]",
":",
"for",
"event_type",
"in",
"event_types",
":",
"try",
":",
"self",
".",
"commands_rights",
"[",
"command",
"]",
"[",
"user",
".",
"lower",
"(",
")",
"]",
".",
"remove",
"(",
"event_type",
")",
"except",
"ValueError",
":",
"pass",
"if",
"not",
"self",
".",
"commands_rights",
"[",
"command",
"]",
"[",
"user",
".",
"lower",
"(",
")",
"]",
":",
"self",
".",
"commands_rights",
"[",
"command",
"]",
".",
"pop",
"(",
"user",
".",
"lower",
"(",
")",
")"
] | 43.052632 | 18.947368 |
def _get_path(fname: str) -> str:
"""
:meth: download get path of file from pythainlp-corpus
:param str fname: file name
:return: path to downloaded file
"""
path = get_corpus_path(fname)
if not path:
download(fname)
path = get_corpus_path(fname)
return path | [
"def",
"_get_path",
"(",
"fname",
":",
"str",
")",
"->",
"str",
":",
"path",
"=",
"get_corpus_path",
"(",
"fname",
")",
"if",
"not",
"path",
":",
"download",
"(",
"fname",
")",
"path",
"=",
"get_corpus_path",
"(",
"fname",
")",
"return",
"path"
] | 26.909091 | 10.363636 |
def reload_repo_cache(i):
"""
Input: {
(force) - if 'yes', force recaching
}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
global cache_repo_uoa, cache_repo_info, paths_repos_all, cache_repo_init
if i.get('force','')=='yes': # pragma: no cover
cache_repo_init=False
paths_repos_all=[]
if not cache_repo_init:
# Load repo UOA -> UID disambiguator
r=load_json_file({'json_file':work['dir_cache_repo_uoa']})
if r['return']!=16 and r['return']>0: return r
cache_repo_uoa=r.get('dict',{})
# Load cached repo info
r=load_json_file({'json_file':work['dir_cache_repo_info']})
if r['return']!=16 and r['return']>0: return r
cache_repo_info=r.get('dict',{})
# Prepare all paths
for q in cache_repo_info:
qq=cache_repo_info[q]
dd=qq['dict']
p=dd.get('path','')
if p!='':
paths_repos_all.append({'path':os.path.normpath(p),
'repo_uoa':qq['data_uoa'],
'repo_uid':qq['data_uid'],
'repo_alias':qq['data_alias']})
cache_repo_init=True
return {'return':0} | [
"def",
"reload_repo_cache",
"(",
"i",
")",
":",
"global",
"cache_repo_uoa",
",",
"cache_repo_info",
",",
"paths_repos_all",
",",
"cache_repo_init",
"if",
"i",
".",
"get",
"(",
"'force'",
",",
"''",
")",
"==",
"'yes'",
":",
"# pragma: no cover",
"cache_repo_init",
"=",
"False",
"paths_repos_all",
"=",
"[",
"]",
"if",
"not",
"cache_repo_init",
":",
"# Load repo UOA -> UID disambiguator",
"r",
"=",
"load_json_file",
"(",
"{",
"'json_file'",
":",
"work",
"[",
"'dir_cache_repo_uoa'",
"]",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
"!=",
"16",
"and",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",
"r",
"cache_repo_uoa",
"=",
"r",
".",
"get",
"(",
"'dict'",
",",
"{",
"}",
")",
"# Load cached repo info",
"r",
"=",
"load_json_file",
"(",
"{",
"'json_file'",
":",
"work",
"[",
"'dir_cache_repo_info'",
"]",
"}",
")",
"if",
"r",
"[",
"'return'",
"]",
"!=",
"16",
"and",
"r",
"[",
"'return'",
"]",
">",
"0",
":",
"return",
"r",
"cache_repo_info",
"=",
"r",
".",
"get",
"(",
"'dict'",
",",
"{",
"}",
")",
"# Prepare all paths",
"for",
"q",
"in",
"cache_repo_info",
":",
"qq",
"=",
"cache_repo_info",
"[",
"q",
"]",
"dd",
"=",
"qq",
"[",
"'dict'",
"]",
"p",
"=",
"dd",
".",
"get",
"(",
"'path'",
",",
"''",
")",
"if",
"p",
"!=",
"''",
":",
"paths_repos_all",
".",
"append",
"(",
"{",
"'path'",
":",
"os",
".",
"path",
".",
"normpath",
"(",
"p",
")",
",",
"'repo_uoa'",
":",
"qq",
"[",
"'data_uoa'",
"]",
",",
"'repo_uid'",
":",
"qq",
"[",
"'data_uid'",
"]",
",",
"'repo_alias'",
":",
"qq",
"[",
"'data_alias'",
"]",
"}",
")",
"cache_repo_init",
"=",
"True",
"return",
"{",
"'return'",
":",
"0",
"}"
] | 31.363636 | 20.363636 |
def set_focus_to_state_model(self, state_m, ratio_requested=0.8):
""" Focus a state view of respective state model
:param rafcon.gui.model.state state_m: Respective state model of state view to be focused
:param ratio_requested: Minimum ratio of the screen which is requested, so can be more
:return:
"""
state_machine_m = self.model
state_v = self.canvas.get_view_for_model(state_m)
if state_v is None:
logger.warning('There is no view for state model {0}'.format(state_m))
self.move_item_into_viewport(state_v)
# check_relative size in view and call it again if the state is still very small
state_v = self.canvas.get_view_for_model(state_machine_m.root_state)
state_size = self.view.editor.get_matrix_i2v(state_v).transform_distance(state_v.width, state_v.height)
viewport_size = self.view.editor.get_allocation().width, self.view.editor.get_allocation().height
if state_size[0] < ratio_requested*viewport_size[0] and state_size[1] < ratio_requested*viewport_size[1]:
self.set_focus_to_state_model(state_m, ratio_requested) | [
"def",
"set_focus_to_state_model",
"(",
"self",
",",
"state_m",
",",
"ratio_requested",
"=",
"0.8",
")",
":",
"state_machine_m",
"=",
"self",
".",
"model",
"state_v",
"=",
"self",
".",
"canvas",
".",
"get_view_for_model",
"(",
"state_m",
")",
"if",
"state_v",
"is",
"None",
":",
"logger",
".",
"warning",
"(",
"'There is no view for state model {0}'",
".",
"format",
"(",
"state_m",
")",
")",
"self",
".",
"move_item_into_viewport",
"(",
"state_v",
")",
"# check_relative size in view and call it again if the state is still very small",
"state_v",
"=",
"self",
".",
"canvas",
".",
"get_view_for_model",
"(",
"state_machine_m",
".",
"root_state",
")",
"state_size",
"=",
"self",
".",
"view",
".",
"editor",
".",
"get_matrix_i2v",
"(",
"state_v",
")",
".",
"transform_distance",
"(",
"state_v",
".",
"width",
",",
"state_v",
".",
"height",
")",
"viewport_size",
"=",
"self",
".",
"view",
".",
"editor",
".",
"get_allocation",
"(",
")",
".",
"width",
",",
"self",
".",
"view",
".",
"editor",
".",
"get_allocation",
"(",
")",
".",
"height",
"if",
"state_size",
"[",
"0",
"]",
"<",
"ratio_requested",
"*",
"viewport_size",
"[",
"0",
"]",
"and",
"state_size",
"[",
"1",
"]",
"<",
"ratio_requested",
"*",
"viewport_size",
"[",
"1",
"]",
":",
"self",
".",
"set_focus_to_state_model",
"(",
"state_m",
",",
"ratio_requested",
")"
] | 67.411765 | 33 |
def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
"""Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r. Defaults require about 16 MiB.
Time taken is proportional to N*p. Defaults take <100ms of a recent x86.
The last one differs from libscrypt defaults, but matches the 'interactive'
work factor from the original paper. For long term storage where runtime of
key derivation is not a problem, you could use 16 as in libscrypt or better
yet increase N if memory is plentiful.
"""
check_args(password, salt, N, r, p, olen)
out = ctypes.create_string_buffer(olen)
ret = _libscrypt_scrypt(password, len(password), salt, len(salt),
N, r, p, out, len(out))
if ret:
raise ValueError
return out.raw | [
"def",
"scrypt",
"(",
"password",
",",
"salt",
",",
"N",
"=",
"SCRYPT_N",
",",
"r",
"=",
"SCRYPT_r",
",",
"p",
"=",
"SCRYPT_p",
",",
"olen",
"=",
"64",
")",
":",
"check_args",
"(",
"password",
",",
"salt",
",",
"N",
",",
"r",
",",
"p",
",",
"olen",
")",
"out",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"olen",
")",
"ret",
"=",
"_libscrypt_scrypt",
"(",
"password",
",",
"len",
"(",
"password",
")",
",",
"salt",
",",
"len",
"(",
"salt",
")",
",",
"N",
",",
"r",
",",
"p",
",",
"out",
",",
"len",
"(",
"out",
")",
")",
"if",
"ret",
":",
"raise",
"ValueError",
"return",
"out",
".",
"raw"
] | 37.178571 | 25.821429 |
def put_script(self, id, body, context=None, params=None):
"""
Create a script in given language with specified ID.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html>`_
:arg id: Script ID
:arg body: The document
"""
for param in (id, body):
if param in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument.")
return self.transport.perform_request(
"PUT", _make_path("_scripts", id, context), params=params, body=body
) | [
"def",
"put_script",
"(",
"self",
",",
"id",
",",
"body",
",",
"context",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"for",
"param",
"in",
"(",
"id",
",",
"body",
")",
":",
"if",
"param",
"in",
"SKIP_IN_PATH",
":",
"raise",
"ValueError",
"(",
"\"Empty value passed for a required argument.\"",
")",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"PUT\"",
",",
"_make_path",
"(",
"\"_scripts\"",
",",
"id",
",",
"context",
")",
",",
"params",
"=",
"params",
",",
"body",
"=",
"body",
")"
] | 41.285714 | 20.428571 |
def bookmark_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/bookmarks#create-bookmark"
api_path = "/api/v2/bookmarks.json"
return self.call(api_path, method="POST", data=data, **kwargs) | [
"def",
"bookmark_create",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/bookmarks.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"POST\"",
",",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 59.75 | 19.75 |
def get_terms(desc, geneset, assoc, obo_dag, log):
"""Get the terms in the study group
"""
_chk_gene2go(assoc)
term2itemids = defaultdict(set)
genes = [g for g in geneset if g in assoc]
for gene in genes:
for goid in assoc[gene]:
if goid in obo_dag:
term2itemids[obo_dag[goid].id].add(gene)
if log is not None:
num_stu = len(genes)
num_pop = len(geneset)
perc = 100.0*num_stu/num_pop if num_pop != 0 else 0.0
log.write("{P:3.0f}% {N:>6,} of {M:>6,} {DESC} items found in association\n".format(
DESC=desc, N=num_stu, M=num_pop, P=perc))
return term2itemids | [
"def",
"get_terms",
"(",
"desc",
",",
"geneset",
",",
"assoc",
",",
"obo_dag",
",",
"log",
")",
":",
"_chk_gene2go",
"(",
"assoc",
")",
"term2itemids",
"=",
"defaultdict",
"(",
"set",
")",
"genes",
"=",
"[",
"g",
"for",
"g",
"in",
"geneset",
"if",
"g",
"in",
"assoc",
"]",
"for",
"gene",
"in",
"genes",
":",
"for",
"goid",
"in",
"assoc",
"[",
"gene",
"]",
":",
"if",
"goid",
"in",
"obo_dag",
":",
"term2itemids",
"[",
"obo_dag",
"[",
"goid",
"]",
".",
"id",
"]",
".",
"add",
"(",
"gene",
")",
"if",
"log",
"is",
"not",
"None",
":",
"num_stu",
"=",
"len",
"(",
"genes",
")",
"num_pop",
"=",
"len",
"(",
"geneset",
")",
"perc",
"=",
"100.0",
"*",
"num_stu",
"/",
"num_pop",
"if",
"num_pop",
"!=",
"0",
"else",
"0.0",
"log",
".",
"write",
"(",
"\"{P:3.0f}% {N:>6,} of {M:>6,} {DESC} items found in association\\n\"",
".",
"format",
"(",
"DESC",
"=",
"desc",
",",
"N",
"=",
"num_stu",
",",
"M",
"=",
"num_pop",
",",
"P",
"=",
"perc",
")",
")",
"return",
"term2itemids"
] | 38.294118 | 13.588235 |
def _is_type_compatible(a, b):
"""helper for interval_range to check type compat of start/end/freq"""
is_ts_compat = lambda x: isinstance(x, (Timestamp, DateOffset))
is_td_compat = lambda x: isinstance(x, (Timedelta, DateOffset))
return ((is_number(a) and is_number(b)) or
(is_ts_compat(a) and is_ts_compat(b)) or
(is_td_compat(a) and is_td_compat(b)) or
com._any_none(a, b)) | [
"def",
"_is_type_compatible",
"(",
"a",
",",
"b",
")",
":",
"is_ts_compat",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"(",
"Timestamp",
",",
"DateOffset",
")",
")",
"is_td_compat",
"=",
"lambda",
"x",
":",
"isinstance",
"(",
"x",
",",
"(",
"Timedelta",
",",
"DateOffset",
")",
")",
"return",
"(",
"(",
"is_number",
"(",
"a",
")",
"and",
"is_number",
"(",
"b",
")",
")",
"or",
"(",
"is_ts_compat",
"(",
"a",
")",
"and",
"is_ts_compat",
"(",
"b",
")",
")",
"or",
"(",
"is_td_compat",
"(",
"a",
")",
"and",
"is_td_compat",
"(",
"b",
")",
")",
"or",
"com",
".",
"_any_none",
"(",
"a",
",",
"b",
")",
")"
] | 52.5 | 12.75 |
def update_records(self, domain, records):
"""
Modifies an existing records for a domain.
"""
if not isinstance(records, list):
raise TypeError("Expected records of type list")
uri = "/domains/%s/records" % utils.get_id(domain)
resp, resp_body = self._async_call(uri, method="PUT",
body={"records": records},
error_class=exc.DomainRecordUpdateFailed, has_response=False)
return resp_body | [
"def",
"update_records",
"(",
"self",
",",
"domain",
",",
"records",
")",
":",
"if",
"not",
"isinstance",
"(",
"records",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected records of type list\"",
")",
"uri",
"=",
"\"/domains/%s/records\"",
"%",
"utils",
".",
"get_id",
"(",
"domain",
")",
"resp",
",",
"resp_body",
"=",
"self",
".",
"_async_call",
"(",
"uri",
",",
"method",
"=",
"\"PUT\"",
",",
"body",
"=",
"{",
"\"records\"",
":",
"records",
"}",
",",
"error_class",
"=",
"exc",
".",
"DomainRecordUpdateFailed",
",",
"has_response",
"=",
"False",
")",
"return",
"resp_body"
] | 43.363636 | 11.545455 |
def set_xy_color(self, color_x, color_y, *, index=0, transition_time=None):
"""Set xy color of the light."""
self._value_validate(color_x, RANGE_X, "X color")
self._value_validate(color_y, RANGE_Y, "Y color")
values = {
ATTR_LIGHT_COLOR_X: color_x,
ATTR_LIGHT_COLOR_Y: color_y
}
if transition_time is not None:
values[ATTR_TRANSITION_TIME] = transition_time
return self.set_values(values, index=index) | [
"def",
"set_xy_color",
"(",
"self",
",",
"color_x",
",",
"color_y",
",",
"*",
",",
"index",
"=",
"0",
",",
"transition_time",
"=",
"None",
")",
":",
"self",
".",
"_value_validate",
"(",
"color_x",
",",
"RANGE_X",
",",
"\"X color\"",
")",
"self",
".",
"_value_validate",
"(",
"color_y",
",",
"RANGE_Y",
",",
"\"Y color\"",
")",
"values",
"=",
"{",
"ATTR_LIGHT_COLOR_X",
":",
"color_x",
",",
"ATTR_LIGHT_COLOR_Y",
":",
"color_y",
"}",
"if",
"transition_time",
"is",
"not",
"None",
":",
"values",
"[",
"ATTR_TRANSITION_TIME",
"]",
"=",
"transition_time",
"return",
"self",
".",
"set_values",
"(",
"values",
",",
"index",
"=",
"index",
")"
] | 34.5 | 19.5 |
def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,
target=None, rel=None):
"""Converts URLs in plain text into clickable links.
If you pass the filter an additional integer it will shorten the urls
to that number. Also a third argument exists that makes the urls
"nofollow":
.. sourcecode:: jinja
{{ mytext|urlize(40, true) }}
links are shortened to 40 chars and defined with rel="nofollow"
If *target* is specified, the ``target`` attribute will be added to the
``<a>`` tag:
.. sourcecode:: jinja
{{ mytext|urlize(40, target='_blank') }}
.. versionchanged:: 2.8+
The *target* parameter was added.
"""
policies = eval_ctx.environment.policies
rel = set((rel or '').split() or [])
if nofollow:
rel.add('nofollow')
rel.update((policies['urlize.rel'] or '').split())
if target is None:
target = policies['urlize.target']
rel = ' '.join(sorted(rel)) or None
rv = urlize(value, trim_url_limit, rel=rel, target=target)
if eval_ctx.autoescape:
rv = Markup(rv)
return rv | [
"def",
"do_urlize",
"(",
"eval_ctx",
",",
"value",
",",
"trim_url_limit",
"=",
"None",
",",
"nofollow",
"=",
"False",
",",
"target",
"=",
"None",
",",
"rel",
"=",
"None",
")",
":",
"policies",
"=",
"eval_ctx",
".",
"environment",
".",
"policies",
"rel",
"=",
"set",
"(",
"(",
"rel",
"or",
"''",
")",
".",
"split",
"(",
")",
"or",
"[",
"]",
")",
"if",
"nofollow",
":",
"rel",
".",
"add",
"(",
"'nofollow'",
")",
"rel",
".",
"update",
"(",
"(",
"policies",
"[",
"'urlize.rel'",
"]",
"or",
"''",
")",
".",
"split",
"(",
")",
")",
"if",
"target",
"is",
"None",
":",
"target",
"=",
"policies",
"[",
"'urlize.target'",
"]",
"rel",
"=",
"' '",
".",
"join",
"(",
"sorted",
"(",
"rel",
")",
")",
"or",
"None",
"rv",
"=",
"urlize",
"(",
"value",
",",
"trim_url_limit",
",",
"rel",
"=",
"rel",
",",
"target",
"=",
"target",
")",
"if",
"eval_ctx",
".",
"autoescape",
":",
"rv",
"=",
"Markup",
"(",
"rv",
")",
"return",
"rv"
] | 31.428571 | 19.914286 |
def _invertMapping(mapping):
"""Converts a protein to peptide or peptide to protein mapping.
:param mapping: dict, for each key contains a set of entries
:returns: an inverted mapping that each entry of the values points to a set
of initial keys.
"""
invertedMapping = ddict(set)
for key, values in viewitems(mapping):
for value in values:
invertedMapping[value].add(key)
return invertedMapping | [
"def",
"_invertMapping",
"(",
"mapping",
")",
":",
"invertedMapping",
"=",
"ddict",
"(",
"set",
")",
"for",
"key",
",",
"values",
"in",
"viewitems",
"(",
"mapping",
")",
":",
"for",
"value",
"in",
"values",
":",
"invertedMapping",
"[",
"value",
"]",
".",
"add",
"(",
"key",
")",
"return",
"invertedMapping"
] | 33.846154 | 16.153846 |
def importFromPath(self, path, fqname):
"""Import a dotted-name package whose tail is at path. In other words,
given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then
bar from path/to/foo/bar, returning bar.
"""
# find the base dir of the package
path_parts = os.path.normpath(os.path.abspath(path)).split(os.sep)
name_parts = fqname.split('.')
if path_parts[-1].startswith('__init__'):
path_parts.pop()
path_parts = path_parts[:-(len(name_parts))]
dir_path = os.sep.join(path_parts)
# then import fqname starting from that dir
return self.importFromDir(dir_path, fqname) | [
"def",
"importFromPath",
"(",
"self",
",",
"path",
",",
"fqname",
")",
":",
"# find the base dir of the package",
"path_parts",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
".",
"split",
"(",
"os",
".",
"sep",
")",
"name_parts",
"=",
"fqname",
".",
"split",
"(",
"'.'",
")",
"if",
"path_parts",
"[",
"-",
"1",
"]",
".",
"startswith",
"(",
"'__init__'",
")",
":",
"path_parts",
".",
"pop",
"(",
")",
"path_parts",
"=",
"path_parts",
"[",
":",
"-",
"(",
"len",
"(",
"name_parts",
")",
")",
"]",
"dir_path",
"=",
"os",
".",
"sep",
".",
"join",
"(",
"path_parts",
")",
"# then import fqname starting from that dir",
"return",
"self",
".",
"importFromDir",
"(",
"dir_path",
",",
"fqname",
")"
] | 48.642857 | 10.142857 |
def coverage(self):
"""
Will return a DataFrame with coverage information (if available) for each repo in the project).
If there is a .coverage file available, this will attempt to form a DataFrame with that information in it, which
will contain the columns:
* repository
* filename
* lines_covered
* total_lines
* coverage
If it can't be found or parsed, an empty DataFrame of that form will be returned.
:return: DataFrame
"""
df = pd.DataFrame(columns=['filename', 'lines_covered', 'total_lines', 'coverage', 'repository'])
for repo in self.repos:
try:
cov = repo.coverage()
cov['repository'] = repo.repo_name
df = df.append(cov)
except GitCommandError:
print('Warning! Repo: %s seems to not have coverage' % (repo, ))
df.reset_index()
return df | [
"def",
"coverage",
"(",
"self",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"columns",
"=",
"[",
"'filename'",
",",
"'lines_covered'",
",",
"'total_lines'",
",",
"'coverage'",
",",
"'repository'",
"]",
")",
"for",
"repo",
"in",
"self",
".",
"repos",
":",
"try",
":",
"cov",
"=",
"repo",
".",
"coverage",
"(",
")",
"cov",
"[",
"'repository'",
"]",
"=",
"repo",
".",
"repo_name",
"df",
"=",
"df",
".",
"append",
"(",
"cov",
")",
"except",
"GitCommandError",
":",
"print",
"(",
"'Warning! Repo: %s seems to not have coverage'",
"%",
"(",
"repo",
",",
")",
")",
"df",
".",
"reset_index",
"(",
")",
"return",
"df"
] | 30.548387 | 27.387097 |
def unwrap_stream(stream_name):
"""
Temporarily unwraps a given stream (stdin, stdout, or stderr) to undo the effects of wrap_stdio_in_codecs().
"""
wrapped_stream = None
try:
wrapped_stream = getattr(sys, stream_name)
if hasattr(wrapped_stream, '_original_stream'):
setattr(sys, stream_name, wrapped_stream._original_stream)
yield
finally:
if wrapped_stream:
setattr(sys, stream_name, wrapped_stream) | [
"def",
"unwrap_stream",
"(",
"stream_name",
")",
":",
"wrapped_stream",
"=",
"None",
"try",
":",
"wrapped_stream",
"=",
"getattr",
"(",
"sys",
",",
"stream_name",
")",
"if",
"hasattr",
"(",
"wrapped_stream",
",",
"'_original_stream'",
")",
":",
"setattr",
"(",
"sys",
",",
"stream_name",
",",
"wrapped_stream",
".",
"_original_stream",
")",
"yield",
"finally",
":",
"if",
"wrapped_stream",
":",
"setattr",
"(",
"sys",
",",
"stream_name",
",",
"wrapped_stream",
")"
] | 36.076923 | 20.384615 |
def generate_edit_credentials(self):
"""
request an edit token and update the cookie_jar in order to add the session cookie
:return: Returns a json with all relevant cookies, aka cookie jar
"""
params = {
'action': 'query',
'meta': 'tokens',
'format': 'json'
}
response = self.s.get(self.base_url, params=params)
self.edit_token = response.json()['query']['tokens']['csrftoken']
return self.s.cookies | [
"def",
"generate_edit_credentials",
"(",
"self",
")",
":",
"params",
"=",
"{",
"'action'",
":",
"'query'",
",",
"'meta'",
":",
"'tokens'",
",",
"'format'",
":",
"'json'",
"}",
"response",
"=",
"self",
".",
"s",
".",
"get",
"(",
"self",
".",
"base_url",
",",
"params",
"=",
"params",
")",
"self",
".",
"edit_token",
"=",
"response",
".",
"json",
"(",
")",
"[",
"'query'",
"]",
"[",
"'tokens'",
"]",
"[",
"'csrftoken'",
"]",
"return",
"self",
".",
"s",
".",
"cookies"
] | 35.428571 | 19.714286 |
def _on_return(self, text):
"""Called when the user presses return on the send message widget."""
# Ignore if the user hasn't typed a message.
if not text:
return
elif text.startswith('/image') and len(text.split(' ')) == 2:
# Temporary UI for testing image uploads
filename = text.split(' ')[1]
image_file = open(filename, 'rb')
text = ''
else:
image_file = None
text = replace_emoticons(text)
segments = hangups.ChatMessageSegment.from_str(text)
self._coroutine_queue.put(
self._handle_send_message(
self._conversation.send_message(
segments, image_file=image_file
)
)
) | [
"def",
"_on_return",
"(",
"self",
",",
"text",
")",
":",
"# Ignore if the user hasn't typed a message.",
"if",
"not",
"text",
":",
"return",
"elif",
"text",
".",
"startswith",
"(",
"'/image'",
")",
"and",
"len",
"(",
"text",
".",
"split",
"(",
"' '",
")",
")",
"==",
"2",
":",
"# Temporary UI for testing image uploads",
"filename",
"=",
"text",
".",
"split",
"(",
"' '",
")",
"[",
"1",
"]",
"image_file",
"=",
"open",
"(",
"filename",
",",
"'rb'",
")",
"text",
"=",
"''",
"else",
":",
"image_file",
"=",
"None",
"text",
"=",
"replace_emoticons",
"(",
"text",
")",
"segments",
"=",
"hangups",
".",
"ChatMessageSegment",
".",
"from_str",
"(",
"text",
")",
"self",
".",
"_coroutine_queue",
".",
"put",
"(",
"self",
".",
"_handle_send_message",
"(",
"self",
".",
"_conversation",
".",
"send_message",
"(",
"segments",
",",
"image_file",
"=",
"image_file",
")",
")",
")"
] | 36.761905 | 14.333333 |
def multicore(function, cores, multiargs, **singleargs):
"""
wrapper for multicore process execution
Parameters
----------
function
individual function to be applied to each process item
cores: int
the number of subprocesses started/CPUs used;
this value is reduced in case the number of subprocesses is smaller
multiargs: dict
a dictionary containing sub-function argument names as keys and lists of arguments to be
distributed among the processes as values
singleargs
all remaining arguments which are invariant among the subprocesses
Returns
-------
None or list
the return of the function for all subprocesses
Notes
-----
- all `multiargs` value lists must be of same length, i.e. all argument keys must be explicitly defined for each
subprocess
- all function arguments passed via `singleargs` must be provided with the full argument name and its value
(i.e. argname=argval); default function args are not accepted
- if the processes return anything else than None, this function will return a list of results
- if all processes return None, this function will be of type void
Examples
--------
>>> def add(x, y, z):
>>> return x + y + z
>>> multicore(add, cores=2, multiargs={'x': [1, 2]}, y=5, z=9)
[15, 16]
>>> multicore(add, cores=2, multiargs={'x': [1, 2], 'y': [5, 6]}, z=9)
[15, 17]
See Also
--------
:mod:`pathos.multiprocessing`
"""
tblib.pickling_support.install()
# compare the function arguments with the multi and single arguments and raise errors if mismatches occur
if sys.version_info >= (3, 0):
check = inspect.getfullargspec(function)
varkw = check.varkw
else:
check = inspect.getargspec(function)
varkw = check.keywords
if not check.varargs and not varkw:
multiargs_check = [x for x in multiargs if x not in check.args]
singleargs_check = [x for x in singleargs if x not in check.args]
if len(multiargs_check) > 0:
raise AttributeError('incompatible multi arguments: {0}'.format(', '.join(multiargs_check)))
if len(singleargs_check) > 0:
raise AttributeError('incompatible single arguments: {0}'.format(', '.join(singleargs_check)))
# compare the list lengths of the multi arguments and raise errors if they are of different length
arglengths = list(set([len(multiargs[x]) for x in multiargs]))
if len(arglengths) > 1:
raise AttributeError('multi argument lists of different length')
# prevent starting more threads than necessary
cores = cores if arglengths[0] >= cores else arglengths[0]
# create a list of dictionaries each containing the arguments for individual
# function calls to be passed to the multicore processes
processlist = [dictmerge(dict([(arg, multiargs[arg][i]) for arg in multiargs]), singleargs)
for i in range(len(multiargs[list(multiargs.keys())[0]]))]
if platform.system() == 'Windows':
# in Windows parallel processing needs to strictly be in a "if __name__ == '__main__':" wrapper
# it was thus necessary to outsource this to a different script and try to serialize all input for sharing objects
# https://stackoverflow.com/questions/38236211/why-multiprocessing-process-behave-differently-on-windows-and-linux-for-global-o
# a helper script to perform the parallel processing
script = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'multicore_helper.py')
# a temporary file to write the serialized function variables
tmpfile = os.path.join(tempfile.gettempdir(), 'spatialist_dump')
# check if everything can be serialized
if not dill.pickles([function, cores, processlist]):
raise RuntimeError('cannot fully serialize function arguments;\n'
' see https://github.com/uqfoundation/dill for supported types')
# write the serialized variables
with open(tmpfile, 'wb') as tmp:
dill.dump([function, cores, processlist], tmp, byref=False)
# run the helper script
proc = sp.Popen([sys.executable, script], stdin=sp.PIPE, stderr=sp.PIPE)
out, err = proc.communicate()
if proc.returncode != 0:
raise RuntimeError(err.decode())
# retrieve the serialized output of the processing which was written to the temporary file by the helper script
with open(tmpfile, 'rb') as tmp:
result = dill.load(tmp)
return result
else:
results = None
def wrapper(**kwargs):
try:
return function(**kwargs)
except Exception as e:
return ExceptionWrapper(e)
# block printing of the executed function
with HiddenPrints():
# start pool of processes and do the work
try:
pool = mp.Pool(processes=cores)
except NameError:
raise ImportError("package 'pathos' could not be imported")
results = pool.imap(lambda x: wrapper(**x), processlist)
pool.close()
pool.join()
i = 0
out = []
for item in results:
if isinstance(item, ExceptionWrapper):
item.ee = type(item.ee)(str(item.ee) +
"\n(called function '{}' with args {})"
.format(function.__name__, processlist[i]))
raise (item.re_raise())
out.append(item)
i += 1
# evaluate the return of the processing function;
# if any value is not None then the whole list of results is returned
eval = [x for x in out if x is not None]
if len(eval) == 0:
return None
else:
return out | [
"def",
"multicore",
"(",
"function",
",",
"cores",
",",
"multiargs",
",",
"*",
"*",
"singleargs",
")",
":",
"tblib",
".",
"pickling_support",
".",
"install",
"(",
")",
"# compare the function arguments with the multi and single arguments and raise errors if mismatches occur",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"check",
"=",
"inspect",
".",
"getfullargspec",
"(",
"function",
")",
"varkw",
"=",
"check",
".",
"varkw",
"else",
":",
"check",
"=",
"inspect",
".",
"getargspec",
"(",
"function",
")",
"varkw",
"=",
"check",
".",
"keywords",
"if",
"not",
"check",
".",
"varargs",
"and",
"not",
"varkw",
":",
"multiargs_check",
"=",
"[",
"x",
"for",
"x",
"in",
"multiargs",
"if",
"x",
"not",
"in",
"check",
".",
"args",
"]",
"singleargs_check",
"=",
"[",
"x",
"for",
"x",
"in",
"singleargs",
"if",
"x",
"not",
"in",
"check",
".",
"args",
"]",
"if",
"len",
"(",
"multiargs_check",
")",
">",
"0",
":",
"raise",
"AttributeError",
"(",
"'incompatible multi arguments: {0}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"multiargs_check",
")",
")",
")",
"if",
"len",
"(",
"singleargs_check",
")",
">",
"0",
":",
"raise",
"AttributeError",
"(",
"'incompatible single arguments: {0}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"singleargs_check",
")",
")",
")",
"# compare the list lengths of the multi arguments and raise errors if they are of different length",
"arglengths",
"=",
"list",
"(",
"set",
"(",
"[",
"len",
"(",
"multiargs",
"[",
"x",
"]",
")",
"for",
"x",
"in",
"multiargs",
"]",
")",
")",
"if",
"len",
"(",
"arglengths",
")",
">",
"1",
":",
"raise",
"AttributeError",
"(",
"'multi argument lists of different length'",
")",
"# prevent starting more threads than necessary",
"cores",
"=",
"cores",
"if",
"arglengths",
"[",
"0",
"]",
">=",
"cores",
"else",
"arglengths",
"[",
"0",
"]",
"# create a list of dictionaries each containing the arguments for individual",
"# function calls to be passed to the multicore processes",
"processlist",
"=",
"[",
"dictmerge",
"(",
"dict",
"(",
"[",
"(",
"arg",
",",
"multiargs",
"[",
"arg",
"]",
"[",
"i",
"]",
")",
"for",
"arg",
"in",
"multiargs",
"]",
")",
",",
"singleargs",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"multiargs",
"[",
"list",
"(",
"multiargs",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
"]",
")",
")",
"]",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
":",
"# in Windows parallel processing needs to strictly be in a \"if __name__ == '__main__':\" wrapper",
"# it was thus necessary to outsource this to a different script and try to serialize all input for sharing objects",
"# https://stackoverflow.com/questions/38236211/why-multiprocessing-process-behave-differently-on-windows-and-linux-for-global-o",
"# a helper script to perform the parallel processing",
"script",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
",",
"'multicore_helper.py'",
")",
"# a temporary file to write the serialized function variables",
"tmpfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tempfile",
".",
"gettempdir",
"(",
")",
",",
"'spatialist_dump'",
")",
"# check if everything can be serialized",
"if",
"not",
"dill",
".",
"pickles",
"(",
"[",
"function",
",",
"cores",
",",
"processlist",
"]",
")",
":",
"raise",
"RuntimeError",
"(",
"'cannot fully serialize function arguments;\\n'",
"' see https://github.com/uqfoundation/dill for supported types'",
")",
"# write the serialized variables",
"with",
"open",
"(",
"tmpfile",
",",
"'wb'",
")",
"as",
"tmp",
":",
"dill",
".",
"dump",
"(",
"[",
"function",
",",
"cores",
",",
"processlist",
"]",
",",
"tmp",
",",
"byref",
"=",
"False",
")",
"# run the helper script",
"proc",
"=",
"sp",
".",
"Popen",
"(",
"[",
"sys",
".",
"executable",
",",
"script",
"]",
",",
"stdin",
"=",
"sp",
".",
"PIPE",
",",
"stderr",
"=",
"sp",
".",
"PIPE",
")",
"out",
",",
"err",
"=",
"proc",
".",
"communicate",
"(",
")",
"if",
"proc",
".",
"returncode",
"!=",
"0",
":",
"raise",
"RuntimeError",
"(",
"err",
".",
"decode",
"(",
")",
")",
"# retrieve the serialized output of the processing which was written to the temporary file by the helper script",
"with",
"open",
"(",
"tmpfile",
",",
"'rb'",
")",
"as",
"tmp",
":",
"result",
"=",
"dill",
".",
"load",
"(",
"tmp",
")",
"return",
"result",
"else",
":",
"results",
"=",
"None",
"def",
"wrapper",
"(",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"function",
"(",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"return",
"ExceptionWrapper",
"(",
"e",
")",
"# block printing of the executed function",
"with",
"HiddenPrints",
"(",
")",
":",
"# start pool of processes and do the work",
"try",
":",
"pool",
"=",
"mp",
".",
"Pool",
"(",
"processes",
"=",
"cores",
")",
"except",
"NameError",
":",
"raise",
"ImportError",
"(",
"\"package 'pathos' could not be imported\"",
")",
"results",
"=",
"pool",
".",
"imap",
"(",
"lambda",
"x",
":",
"wrapper",
"(",
"*",
"*",
"x",
")",
",",
"processlist",
")",
"pool",
".",
"close",
"(",
")",
"pool",
".",
"join",
"(",
")",
"i",
"=",
"0",
"out",
"=",
"[",
"]",
"for",
"item",
"in",
"results",
":",
"if",
"isinstance",
"(",
"item",
",",
"ExceptionWrapper",
")",
":",
"item",
".",
"ee",
"=",
"type",
"(",
"item",
".",
"ee",
")",
"(",
"str",
"(",
"item",
".",
"ee",
")",
"+",
"\"\\n(called function '{}' with args {})\"",
".",
"format",
"(",
"function",
".",
"__name__",
",",
"processlist",
"[",
"i",
"]",
")",
")",
"raise",
"(",
"item",
".",
"re_raise",
"(",
")",
")",
"out",
".",
"append",
"(",
"item",
")",
"i",
"+=",
"1",
"# evaluate the return of the processing function;",
"# if any value is not None then the whole list of results is returned",
"eval",
"=",
"[",
"x",
"for",
"x",
"in",
"out",
"if",
"x",
"is",
"not",
"None",
"]",
"if",
"len",
"(",
"eval",
")",
"==",
"0",
":",
"return",
"None",
"else",
":",
"return",
"out"
] | 41.298611 | 26.270833 |
def sndread(path:str) -> Tuple[np.ndarray, int]:
"""
Read a soundfile as a numpy array. This is a float array defined
between -1 and 1, independently of the format of the soundfile
Returns (data:ndarray, sr:int)
"""
backend = _getBackend(path)
logger.debug(f"sndread: using backend {backend.name}")
return backend.read(path) | [
"def",
"sndread",
"(",
"path",
":",
"str",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"int",
"]",
":",
"backend",
"=",
"_getBackend",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"f\"sndread: using backend {backend.name}\"",
")",
"return",
"backend",
".",
"read",
"(",
"path",
")"
] | 35.3 | 14.3 |
def by_phone(self, phone, **kwargs):
"""
Fetch messages from chat with specified phone number.
:Example:
chat = client.chats.by_phone(phone="447624800500")
:param str phone: Phone number in E.164 format.
:param int page: Fetch specified results page. Default=1
:param int limit: How many results on page. Default=10
"""
chat_messages = ChatMessages(self.base_uri, self.auth)
return self.get_subresource_instances(uid=phone, instance=chat_messages, params=kwargs) | [
"def",
"by_phone",
"(",
"self",
",",
"phone",
",",
"*",
"*",
"kwargs",
")",
":",
"chat_messages",
"=",
"ChatMessages",
"(",
"self",
".",
"base_uri",
",",
"self",
".",
"auth",
")",
"return",
"self",
".",
"get_subresource_instances",
"(",
"uid",
"=",
"phone",
",",
"instance",
"=",
"chat_messages",
",",
"params",
"=",
"kwargs",
")"
] | 38.071429 | 23.214286 |
def from_events(self, instance, ev_args, ctx):
"""
Detect the object to instanciate from the arguments `ev_args` of the
``"start"`` event. The new object is stored at the corresponding
descriptor attribute on `instance`.
This method is suspendable.
"""
obj = yield from self._process(instance, ev_args, ctx)
self.__set__(instance, obj)
return obj | [
"def",
"from_events",
"(",
"self",
",",
"instance",
",",
"ev_args",
",",
"ctx",
")",
":",
"obj",
"=",
"yield",
"from",
"self",
".",
"_process",
"(",
"instance",
",",
"ev_args",
",",
"ctx",
")",
"self",
".",
"__set__",
"(",
"instance",
",",
"obj",
")",
"return",
"obj"
] | 37.181818 | 15.545455 |
def as_tuple(self, named=None):
"""
Create a structured schema that will pass stream tuples into callables as ``tuple`` instances.
If this instance represents a common schema then it will be returned
without modification. Stream tuples with common schemas are
always passed according to their definition.
**Passing as tuple**
When `named` evaluates to ``False`` then each stream tuple will
be passed as a ``tuple``. For example with a structured schema
of ``tuple<rstring id, float64 value>`` a value is passed as
``('TempSensor', 27.4)`` and access to the first attribute
is ``t[0]`` and the second as ``t[1]`` where ``t`` represents
the passed value..
**Passing as named tuple**
When `named` is ``True`` or a ``str`` then each stream tuple will
be passed as a named tuple. For example with a structured schema
of ``tuple<rstring id, float64 value>`` a value is passed as
``('TempSensor', 27.4)`` and access to the first attribute
is ``t.id`` (or ``t[0]``) and the second as ``t.value`` (``t[1]``)
where ``t`` represents the passed value.
.. warning:: If an schema's attribute name is not a valid Python identifier or
starts with an underscore then it will be renamed as positional name ``_n``.
For example, with the schema ``tuple<int32 a, int32 def, int32 id>`` the
field names are ``a``, ``_1``, ``_2``.
The value of `named` is used as the name of the named tuple
class with ``StreamTuple`` used when `named` is ``True``.
It is not guaranteed that the class of the namedtuple is the
same for all callables processing tuples with the same
structured schema, only that the tuple is a named tuple
with the correct field names.
Args:
named: Pass stream tuples as a named tuple.
If not set then stream tuples are passed as
instances of ``tuple``.
Returns:
StreamSchema: Schema passing stream tuples as ``tuple`` if allowed.
.. versionadded:: 1.8
.. versionadded:: 1.9 Addition of `named` parameter.
"""
if not named:
return self._copy(tuple)
if named == True or isinstance(named, basestring):
return self._copy(self._make_named_tuple(name=named))
return self._copy(tuple) | [
"def",
"as_tuple",
"(",
"self",
",",
"named",
"=",
"None",
")",
":",
"if",
"not",
"named",
":",
"return",
"self",
".",
"_copy",
"(",
"tuple",
")",
"if",
"named",
"==",
"True",
"or",
"isinstance",
"(",
"named",
",",
"basestring",
")",
":",
"return",
"self",
".",
"_copy",
"(",
"self",
".",
"_make_named_tuple",
"(",
"name",
"=",
"named",
")",
")",
"return",
"self",
".",
"_copy",
"(",
"tuple",
")"
] | 41.637931 | 26.706897 |
def _file_in_next_patches(self, filename, patch):
""" Checks if a backup file of the filename in the applied patches after
patch exists """
if not self.db.is_patch(patch):
# no patches applied
return
patches = self.db.patches_after(patch)
for patch in patches:
file = self.quilt_pc + File(os.path.join(patch.get_name(),
filename))
if file.exists():
raise QuiltError("File %s is modified by patch %s" %
(filename, patch.get_name())) | [
"def",
"_file_in_next_patches",
"(",
"self",
",",
"filename",
",",
"patch",
")",
":",
"if",
"not",
"self",
".",
"db",
".",
"is_patch",
"(",
"patch",
")",
":",
"# no patches applied",
"return",
"patches",
"=",
"self",
".",
"db",
".",
"patches_after",
"(",
"patch",
")",
"for",
"patch",
"in",
"patches",
":",
"file",
"=",
"self",
".",
"quilt_pc",
"+",
"File",
"(",
"os",
".",
"path",
".",
"join",
"(",
"patch",
".",
"get_name",
"(",
")",
",",
"filename",
")",
")",
"if",
"file",
".",
"exists",
"(",
")",
":",
"raise",
"QuiltError",
"(",
"\"File %s is modified by patch %s\"",
"%",
"(",
"filename",
",",
"patch",
".",
"get_name",
"(",
")",
")",
")"
] | 40.6 | 16.733333 |
def rsync(*args, **kwargs):
""" wrapper around the rsync command.
the ssh connection arguments are set automatically.
any args are just passed directly to rsync.
you can use {host_string} in place of the server.
the kwargs are passed on the 'local' fabric command.
if not set, 'capture' is set to False.
example usage:
rsync('-pthrvz', "{host_string}:/some/src/directory", "some/destination/")
"""
kwargs.setdefault('capture', False)
replacements = dict(
host_string="{user}@{host}".format(
user=env.instance.config.get('user', 'root'),
host=env.instance.config.get(
'host', env.instance.config.get(
'ip', env.instance.uid))))
args = [x.format(**replacements) for x in args]
ssh_info = env.instance.init_ssh_key()
ssh_info.pop('host')
ssh_info.pop('user')
ssh_args = env.instance.ssh_args_from_info(ssh_info)
cmd_parts = ['rsync']
cmd_parts.extend(['-e', "ssh %s" % shjoin(ssh_args)])
cmd_parts.extend(args)
cmd = shjoin(cmd_parts)
return local(cmd, **kwargs) | [
"def",
"rsync",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'capture'",
",",
"False",
")",
"replacements",
"=",
"dict",
"(",
"host_string",
"=",
"\"{user}@{host}\"",
".",
"format",
"(",
"user",
"=",
"env",
".",
"instance",
".",
"config",
".",
"get",
"(",
"'user'",
",",
"'root'",
")",
",",
"host",
"=",
"env",
".",
"instance",
".",
"config",
".",
"get",
"(",
"'host'",
",",
"env",
".",
"instance",
".",
"config",
".",
"get",
"(",
"'ip'",
",",
"env",
".",
"instance",
".",
"uid",
")",
")",
")",
")",
"args",
"=",
"[",
"x",
".",
"format",
"(",
"*",
"*",
"replacements",
")",
"for",
"x",
"in",
"args",
"]",
"ssh_info",
"=",
"env",
".",
"instance",
".",
"init_ssh_key",
"(",
")",
"ssh_info",
".",
"pop",
"(",
"'host'",
")",
"ssh_info",
".",
"pop",
"(",
"'user'",
")",
"ssh_args",
"=",
"env",
".",
"instance",
".",
"ssh_args_from_info",
"(",
"ssh_info",
")",
"cmd_parts",
"=",
"[",
"'rsync'",
"]",
"cmd_parts",
".",
"extend",
"(",
"[",
"'-e'",
",",
"\"ssh %s\"",
"%",
"shjoin",
"(",
"ssh_args",
")",
"]",
")",
"cmd_parts",
".",
"extend",
"(",
"args",
")",
"cmd",
"=",
"shjoin",
"(",
"cmd_parts",
")",
"return",
"local",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")"
] | 35.903226 | 15.709677 |
def _add_snps(
self,
snps,
discrepant_snp_positions_threshold,
discrepant_genotypes_threshold,
save_output,
):
""" Add SNPs to this Individual.
Parameters
----------
snps : SNPs
SNPs to add
discrepant_snp_positions_threshold : int
see above
discrepant_genotypes_threshold : int
see above
save_output
see above
Returns
-------
discrepant_positions : pandas.DataFrame
discrepant_genotypes : pandas.DataFrame
"""
discrepant_positions = pd.DataFrame()
discrepant_genotypes = pd.DataFrame()
if snps.snps is None:
return discrepant_positions, discrepant_genotypes
build = snps.build
source = [s.strip() for s in snps.source.split(",")]
if not snps.build_detected:
print("build not detected, assuming build {}".format(snps.build))
if self._build is None:
self._build = build
elif self._build != build:
print(
"build / assembly mismatch between current build of SNPs and SNPs being loaded"
)
# ensure there area always two X alleles
snps = self._double_single_alleles(snps.snps, "X")
if self._snps is None:
self._source.extend(source)
self._snps = snps
else:
common_snps = self._snps.join(snps, how="inner", rsuffix="_added")
discrepant_positions = common_snps.loc[
(common_snps["chrom"] != common_snps["chrom_added"])
| (common_snps["pos"] != common_snps["pos_added"])
]
if 0 < len(discrepant_positions) < discrepant_snp_positions_threshold:
print(
str(len(discrepant_positions)) + " SNP positions were discrepant; "
"keeping original positions"
)
if save_output:
self._discrepant_positions_file_count += 1
lineage.save_df_as_csv(
discrepant_positions,
self._output_dir,
self.get_var_name()
+ "_discrepant_positions_"
+ str(self._discrepant_positions_file_count)
+ ".csv",
)
elif len(discrepant_positions) >= discrepant_snp_positions_threshold:
print(
"too many SNPs differ in position; ensure same genome build is being used"
)
return discrepant_positions, discrepant_genotypes
# remove null genotypes
common_snps = common_snps.loc[
~common_snps["genotype"].isnull()
& ~common_snps["genotype_added"].isnull()
]
# discrepant genotypes are where alleles are not equivalent (i.e., alleles are not the
# same and not swapped)
discrepant_genotypes = common_snps.loc[
(
(common_snps["genotype"].str.len() == 1)
& (common_snps["genotype_added"].str.len() == 1)
& ~(
common_snps["genotype"].str[0]
== common_snps["genotype_added"].str[0]
)
)
| (
(common_snps["genotype"].str.len() == 2)
& (common_snps["genotype_added"].str.len() == 2)
& ~(
(
common_snps["genotype"].str[0]
== common_snps["genotype_added"].str[0]
)
& (
common_snps["genotype"].str[1]
== common_snps["genotype_added"].str[1]
)
)
& ~(
(
common_snps["genotype"].str[0]
== common_snps["genotype_added"].str[1]
)
& (
common_snps["genotype"].str[1]
== common_snps["genotype_added"].str[0]
)
)
)
]
if 0 < len(discrepant_genotypes) < discrepant_genotypes_threshold:
print(
str(len(discrepant_genotypes)) + " SNP genotypes were discrepant; "
"marking those as null"
)
if save_output:
self._discrepant_genotypes_file_count += 1
lineage.save_df_as_csv(
discrepant_genotypes,
self._output_dir,
self.get_var_name()
+ "_discrepant_genotypes_"
+ str(self._discrepant_genotypes_file_count)
+ ".csv",
)
elif len(discrepant_genotypes) >= discrepant_genotypes_threshold:
print(
"too many SNPs differ in their genotype; ensure file is for same "
"individual"
)
return discrepant_positions, discrepant_genotypes
# add new SNPs
self._source.extend(source)
self._snps = self._snps.combine_first(snps)
self._snps.loc[discrepant_genotypes.index, "genotype"] = np.nan
# combine_first converts position to float64, so convert it back to int64
self._snps["pos"] = self._snps["pos"].astype(np.int64)
self._snps = sort_snps(self._snps)
return discrepant_positions, discrepant_genotypes | [
"def",
"_add_snps",
"(",
"self",
",",
"snps",
",",
"discrepant_snp_positions_threshold",
",",
"discrepant_genotypes_threshold",
",",
"save_output",
",",
")",
":",
"discrepant_positions",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"discrepant_genotypes",
"=",
"pd",
".",
"DataFrame",
"(",
")",
"if",
"snps",
".",
"snps",
"is",
"None",
":",
"return",
"discrepant_positions",
",",
"discrepant_genotypes",
"build",
"=",
"snps",
".",
"build",
"source",
"=",
"[",
"s",
".",
"strip",
"(",
")",
"for",
"s",
"in",
"snps",
".",
"source",
".",
"split",
"(",
"\",\"",
")",
"]",
"if",
"not",
"snps",
".",
"build_detected",
":",
"print",
"(",
"\"build not detected, assuming build {}\"",
".",
"format",
"(",
"snps",
".",
"build",
")",
")",
"if",
"self",
".",
"_build",
"is",
"None",
":",
"self",
".",
"_build",
"=",
"build",
"elif",
"self",
".",
"_build",
"!=",
"build",
":",
"print",
"(",
"\"build / assembly mismatch between current build of SNPs and SNPs being loaded\"",
")",
"# ensure there area always two X alleles",
"snps",
"=",
"self",
".",
"_double_single_alleles",
"(",
"snps",
".",
"snps",
",",
"\"X\"",
")",
"if",
"self",
".",
"_snps",
"is",
"None",
":",
"self",
".",
"_source",
".",
"extend",
"(",
"source",
")",
"self",
".",
"_snps",
"=",
"snps",
"else",
":",
"common_snps",
"=",
"self",
".",
"_snps",
".",
"join",
"(",
"snps",
",",
"how",
"=",
"\"inner\"",
",",
"rsuffix",
"=",
"\"_added\"",
")",
"discrepant_positions",
"=",
"common_snps",
".",
"loc",
"[",
"(",
"common_snps",
"[",
"\"chrom\"",
"]",
"!=",
"common_snps",
"[",
"\"chrom_added\"",
"]",
")",
"|",
"(",
"common_snps",
"[",
"\"pos\"",
"]",
"!=",
"common_snps",
"[",
"\"pos_added\"",
"]",
")",
"]",
"if",
"0",
"<",
"len",
"(",
"discrepant_positions",
")",
"<",
"discrepant_snp_positions_threshold",
":",
"print",
"(",
"str",
"(",
"len",
"(",
"discrepant_positions",
")",
")",
"+",
"\" SNP positions were discrepant; \"",
"\"keeping original positions\"",
")",
"if",
"save_output",
":",
"self",
".",
"_discrepant_positions_file_count",
"+=",
"1",
"lineage",
".",
"save_df_as_csv",
"(",
"discrepant_positions",
",",
"self",
".",
"_output_dir",
",",
"self",
".",
"get_var_name",
"(",
")",
"+",
"\"_discrepant_positions_\"",
"+",
"str",
"(",
"self",
".",
"_discrepant_positions_file_count",
")",
"+",
"\".csv\"",
",",
")",
"elif",
"len",
"(",
"discrepant_positions",
")",
">=",
"discrepant_snp_positions_threshold",
":",
"print",
"(",
"\"too many SNPs differ in position; ensure same genome build is being used\"",
")",
"return",
"discrepant_positions",
",",
"discrepant_genotypes",
"# remove null genotypes",
"common_snps",
"=",
"common_snps",
".",
"loc",
"[",
"~",
"common_snps",
"[",
"\"genotype\"",
"]",
".",
"isnull",
"(",
")",
"&",
"~",
"common_snps",
"[",
"\"genotype_added\"",
"]",
".",
"isnull",
"(",
")",
"]",
"# discrepant genotypes are where alleles are not equivalent (i.e., alleles are not the",
"# same and not swapped)",
"discrepant_genotypes",
"=",
"common_snps",
".",
"loc",
"[",
"(",
"(",
"common_snps",
"[",
"\"genotype\"",
"]",
".",
"str",
".",
"len",
"(",
")",
"==",
"1",
")",
"&",
"(",
"common_snps",
"[",
"\"genotype_added\"",
"]",
".",
"str",
".",
"len",
"(",
")",
"==",
"1",
")",
"&",
"~",
"(",
"common_snps",
"[",
"\"genotype\"",
"]",
".",
"str",
"[",
"0",
"]",
"==",
"common_snps",
"[",
"\"genotype_added\"",
"]",
".",
"str",
"[",
"0",
"]",
")",
")",
"|",
"(",
"(",
"common_snps",
"[",
"\"genotype\"",
"]",
".",
"str",
".",
"len",
"(",
")",
"==",
"2",
")",
"&",
"(",
"common_snps",
"[",
"\"genotype_added\"",
"]",
".",
"str",
".",
"len",
"(",
")",
"==",
"2",
")",
"&",
"~",
"(",
"(",
"common_snps",
"[",
"\"genotype\"",
"]",
".",
"str",
"[",
"0",
"]",
"==",
"common_snps",
"[",
"\"genotype_added\"",
"]",
".",
"str",
"[",
"0",
"]",
")",
"&",
"(",
"common_snps",
"[",
"\"genotype\"",
"]",
".",
"str",
"[",
"1",
"]",
"==",
"common_snps",
"[",
"\"genotype_added\"",
"]",
".",
"str",
"[",
"1",
"]",
")",
")",
"&",
"~",
"(",
"(",
"common_snps",
"[",
"\"genotype\"",
"]",
".",
"str",
"[",
"0",
"]",
"==",
"common_snps",
"[",
"\"genotype_added\"",
"]",
".",
"str",
"[",
"1",
"]",
")",
"&",
"(",
"common_snps",
"[",
"\"genotype\"",
"]",
".",
"str",
"[",
"1",
"]",
"==",
"common_snps",
"[",
"\"genotype_added\"",
"]",
".",
"str",
"[",
"0",
"]",
")",
")",
")",
"]",
"if",
"0",
"<",
"len",
"(",
"discrepant_genotypes",
")",
"<",
"discrepant_genotypes_threshold",
":",
"print",
"(",
"str",
"(",
"len",
"(",
"discrepant_genotypes",
")",
")",
"+",
"\" SNP genotypes were discrepant; \"",
"\"marking those as null\"",
")",
"if",
"save_output",
":",
"self",
".",
"_discrepant_genotypes_file_count",
"+=",
"1",
"lineage",
".",
"save_df_as_csv",
"(",
"discrepant_genotypes",
",",
"self",
".",
"_output_dir",
",",
"self",
".",
"get_var_name",
"(",
")",
"+",
"\"_discrepant_genotypes_\"",
"+",
"str",
"(",
"self",
".",
"_discrepant_genotypes_file_count",
")",
"+",
"\".csv\"",
",",
")",
"elif",
"len",
"(",
"discrepant_genotypes",
")",
">=",
"discrepant_genotypes_threshold",
":",
"print",
"(",
"\"too many SNPs differ in their genotype; ensure file is for same \"",
"\"individual\"",
")",
"return",
"discrepant_positions",
",",
"discrepant_genotypes",
"# add new SNPs",
"self",
".",
"_source",
".",
"extend",
"(",
"source",
")",
"self",
".",
"_snps",
"=",
"self",
".",
"_snps",
".",
"combine_first",
"(",
"snps",
")",
"self",
".",
"_snps",
".",
"loc",
"[",
"discrepant_genotypes",
".",
"index",
",",
"\"genotype\"",
"]",
"=",
"np",
".",
"nan",
"# combine_first converts position to float64, so convert it back to int64",
"self",
".",
"_snps",
"[",
"\"pos\"",
"]",
"=",
"self",
".",
"_snps",
"[",
"\"pos\"",
"]",
".",
"astype",
"(",
"np",
".",
"int64",
")",
"self",
".",
"_snps",
"=",
"sort_snps",
"(",
"self",
".",
"_snps",
")",
"return",
"discrepant_positions",
",",
"discrepant_genotypes"
] | 36.579618 | 21.171975 |
def derivative(func, x0, dx=1.0, n=1, args=(), order=3):
'''Reimplementation of SciPy's derivative function, with more cached
coefficients and without using numpy. If new coefficients not cached are
needed, they are only calculated once and are remembered.
'''
if order < n + 1:
raise ValueError
if order % 2 == 0:
raise ValueError
weights = central_diff_weights(order, n)
tot = 0.0
ho = order >> 1
for k in range(order):
tot += weights[k]*func(x0 + (k - ho)*dx, *args)
return tot/product([dx]*n) | [
"def",
"derivative",
"(",
"func",
",",
"x0",
",",
"dx",
"=",
"1.0",
",",
"n",
"=",
"1",
",",
"args",
"=",
"(",
")",
",",
"order",
"=",
"3",
")",
":",
"if",
"order",
"<",
"n",
"+",
"1",
":",
"raise",
"ValueError",
"if",
"order",
"%",
"2",
"==",
"0",
":",
"raise",
"ValueError",
"weights",
"=",
"central_diff_weights",
"(",
"order",
",",
"n",
")",
"tot",
"=",
"0.0",
"ho",
"=",
"order",
">>",
"1",
"for",
"k",
"in",
"range",
"(",
"order",
")",
":",
"tot",
"+=",
"weights",
"[",
"k",
"]",
"*",
"func",
"(",
"x0",
"+",
"(",
"k",
"-",
"ho",
")",
"*",
"dx",
",",
"*",
"args",
")",
"return",
"tot",
"/",
"product",
"(",
"[",
"dx",
"]",
"*",
"n",
")"
] | 36.666667 | 19.866667 |
def cache_file(source):
'''
Wrapper for cp.cache_file which raises an error if the file was unable to
be cached.
CLI Example:
.. code-block:: bash
salt myminion container_resource.cache_file salt://foo/bar/baz.txt
'''
try:
# Don't just use cp.cache_file for this. Docker has its own code to
# pull down images from the web.
if source.startswith('salt://'):
cached_source = __salt__['cp.cache_file'](source)
if not cached_source:
raise CommandExecutionError(
'Unable to cache {0}'.format(source)
)
return cached_source
except AttributeError:
raise SaltInvocationError('Invalid source file {0}'.format(source))
return source | [
"def",
"cache_file",
"(",
"source",
")",
":",
"try",
":",
"# Don't just use cp.cache_file for this. Docker has its own code to",
"# pull down images from the web.",
"if",
"source",
".",
"startswith",
"(",
"'salt://'",
")",
":",
"cached_source",
"=",
"__salt__",
"[",
"'cp.cache_file'",
"]",
"(",
"source",
")",
"if",
"not",
"cached_source",
":",
"raise",
"CommandExecutionError",
"(",
"'Unable to cache {0}'",
".",
"format",
"(",
"source",
")",
")",
"return",
"cached_source",
"except",
"AttributeError",
":",
"raise",
"SaltInvocationError",
"(",
"'Invalid source file {0}'",
".",
"format",
"(",
"source",
")",
")",
"return",
"source"
] | 31.916667 | 23.25 |
def __Logout(si):
"""
Disconnect (logout) service instance
@param si: Service instance (returned from Connect)
"""
try:
if si:
content = si.RetrieveContent()
content.sessionManager.Logout()
except Exception as e:
pass | [
"def",
"__Logout",
"(",
"si",
")",
":",
"try",
":",
"if",
"si",
":",
"content",
"=",
"si",
".",
"RetrieveContent",
"(",
")",
"content",
".",
"sessionManager",
".",
"Logout",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"pass"
] | 23.181818 | 13.181818 |
def get_descendants(self):
"""
:returns: A queryset of all the node's descendants as DFS, doesn't
include the node itself
"""
if self.is_leaf():
return get_result_class(self.__class__).objects.none()
return self.__class__.get_tree(self).exclude(pk=self.pk) | [
"def",
"get_descendants",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_leaf",
"(",
")",
":",
"return",
"get_result_class",
"(",
"self",
".",
"__class__",
")",
".",
"objects",
".",
"none",
"(",
")",
"return",
"self",
".",
"__class__",
".",
"get_tree",
"(",
"self",
")",
".",
"exclude",
"(",
"pk",
"=",
"self",
".",
"pk",
")"
] | 39.125 | 14.625 |
def phytozome10(args):
"""
%prog phytozome species
Retrieve genomes and annotations from phytozome using Globus API. Available
species listed below. Use comma to give a list of species to download. For
example:
$ %prog phytozome Athaliana,Vvinifera,Osativa,Sbicolor,Slycopersicum
"""
from jcvi.apps.biomart import GlobusXMLParser
p = OptionParser(phytozome10.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
species, = args
"""
cookies = get_cookies()
# Get directory listing
dlist = \
"http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=PhytozomeV10"
d = download(dlist, debug=True, cookies=cookies)
"""
fp = open("get-directory.html")
g = GlobusXMLParser(fp)
g.parse_folder() | [
"def",
"phytozome10",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"apps",
".",
"biomart",
"import",
"GlobusXMLParser",
"p",
"=",
"OptionParser",
"(",
"phytozome10",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
"p",
".",
"print_help",
"(",
")",
")",
"species",
",",
"=",
"args",
"\"\"\"\n cookies = get_cookies()\n # Get directory listing\n dlist = \\\n \"http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=PhytozomeV10\"\n d = download(dlist, debug=True, cookies=cookies)\n \"\"\"",
"fp",
"=",
"open",
"(",
"\"get-directory.html\"",
")",
"g",
"=",
"GlobusXMLParser",
"(",
"fp",
")",
"g",
".",
"parse_folder",
"(",
")"
] | 27.793103 | 19.793103 |
async def rpc_message(self, request, message):
'''Publish a message via JSON-RPC'''
await self.pubsub.publish(self.channel, message)
return 'OK' | [
"async",
"def",
"rpc_message",
"(",
"self",
",",
"request",
",",
"message",
")",
":",
"await",
"self",
".",
"pubsub",
".",
"publish",
"(",
"self",
".",
"channel",
",",
"message",
")",
"return",
"'OK'"
] | 41.25 | 11.75 |
def add_file(self, filename):
"""Add a file and all its immediate dependencies to the graph."""
assert not self.final, 'Trying to mutate a final graph.'
self.add_source_file(filename)
resolved, unresolved = self.get_file_deps(filename)
self.graph.add_node(filename)
for f in resolved:
self.graph.add_node(f)
self.graph.add_edge(filename, f)
for imp in unresolved:
self.broken_deps[filename].add(imp) | [
"def",
"add_file",
"(",
"self",
",",
"filename",
")",
":",
"assert",
"not",
"self",
".",
"final",
",",
"'Trying to mutate a final graph.'",
"self",
".",
"add_source_file",
"(",
"filename",
")",
"resolved",
",",
"unresolved",
"=",
"self",
".",
"get_file_deps",
"(",
"filename",
")",
"self",
".",
"graph",
".",
"add_node",
"(",
"filename",
")",
"for",
"f",
"in",
"resolved",
":",
"self",
".",
"graph",
".",
"add_node",
"(",
"f",
")",
"self",
".",
"graph",
".",
"add_edge",
"(",
"filename",
",",
"f",
")",
"for",
"imp",
"in",
"unresolved",
":",
"self",
".",
"broken_deps",
"[",
"filename",
"]",
".",
"add",
"(",
"imp",
")"
] | 40.083333 | 11.666667 |
def getattrs(value, attrs, default=_no_default):
"""
Perform a chained application of ``getattr`` on ``value`` with the values
in ``attrs``.
If ``default`` is supplied, return it if any of the attribute lookups fail.
Parameters
----------
value : object
Root of the lookup chain.
attrs : iterable[str]
Sequence of attributes to look up.
default : object, optional
Value to return if any of the lookups fail.
Returns
-------
result : object
Result of the lookup sequence.
Examples
--------
>>> class EmptyObject(object):
... pass
...
>>> obj = EmptyObject()
>>> obj.foo = EmptyObject()
>>> obj.foo.bar = "value"
>>> getattrs(obj, ('foo', 'bar'))
'value'
>>> getattrs(obj, ('foo', 'buzz'))
Traceback (most recent call last):
...
AttributeError: 'EmptyObject' object has no attribute 'buzz'
>>> getattrs(obj, ('foo', 'buzz'), 'default')
'default'
"""
try:
for attr in attrs:
value = getattr(value, attr)
except AttributeError:
if default is _no_default:
raise
value = default
return value | [
"def",
"getattrs",
"(",
"value",
",",
"attrs",
",",
"default",
"=",
"_no_default",
")",
":",
"try",
":",
"for",
"attr",
"in",
"attrs",
":",
"value",
"=",
"getattr",
"(",
"value",
",",
"attr",
")",
"except",
"AttributeError",
":",
"if",
"default",
"is",
"_no_default",
":",
"raise",
"value",
"=",
"default",
"return",
"value"
] | 24.145833 | 19.895833 |
def BinToTri(self, a, b):
'''
Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of x,y,z
'''
if (b >= 0):
y = a - b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a + b / np.sqrt(3))
return (x, y, z)
else:
y = a + b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a - b / np.sqrt(3))
return (x, y, z) | [
"def",
"BinToTri",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"(",
"b",
">=",
"0",
")",
":",
"y",
"=",
"a",
"-",
"b",
"/",
"np",
".",
"sqrt",
"(",
"3",
")",
"z",
"=",
"b",
"*",
"2",
"/",
"np",
".",
"sqrt",
"(",
"3",
")",
"x",
"=",
"100",
"-",
"(",
"a",
"+",
"b",
"/",
"np",
".",
"sqrt",
"(",
"3",
")",
")",
"return",
"(",
"x",
",",
"y",
",",
"z",
")",
"else",
":",
"y",
"=",
"a",
"+",
"b",
"/",
"np",
".",
"sqrt",
"(",
"3",
")",
"z",
"=",
"b",
"*",
"2",
"/",
"np",
".",
"sqrt",
"(",
"3",
")",
"x",
"=",
"100",
"-",
"(",
"a",
"-",
"b",
"/",
"np",
".",
"sqrt",
"(",
"3",
")",
")",
"return",
"(",
"x",
",",
"y",
",",
"z",
")"
] | 32.571429 | 16.190476 |
def list(self, reservation_status=values.unset, limit=None, page_size=None):
"""
Lists ReservationInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param ReservationInstance.Status reservation_status: Filter by a worker's reservation status
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.taskrouter.v1.workspace.worker.reservation.ReservationInstance]
"""
return list(self.stream(reservation_status=reservation_status, limit=limit, page_size=page_size, )) | [
"def",
"list",
"(",
"self",
",",
"reservation_status",
"=",
"values",
".",
"unset",
",",
"limit",
"=",
"None",
",",
"page_size",
"=",
"None",
")",
":",
"return",
"list",
"(",
"self",
".",
"stream",
"(",
"reservation_status",
"=",
"reservation_status",
",",
"limit",
"=",
"limit",
",",
"page_size",
"=",
"page_size",
",",
")",
")"
] | 65.222222 | 38.222222 |
def check_credentials(self):
"""Verifies key/secret/host combination by making a balance inquiry"""
try:
return bool(self.mturk.get_account_balance())
except NoCredentialsError:
raise MTurkServiceException("No AWS credentials set!")
except ClientError:
raise MTurkServiceException("Invalid AWS credentials!")
except Exception as ex:
raise MTurkServiceException(
"Error checking credentials: {}".format(str(ex))
) | [
"def",
"check_credentials",
"(",
"self",
")",
":",
"try",
":",
"return",
"bool",
"(",
"self",
".",
"mturk",
".",
"get_account_balance",
"(",
")",
")",
"except",
"NoCredentialsError",
":",
"raise",
"MTurkServiceException",
"(",
"\"No AWS credentials set!\"",
")",
"except",
"ClientError",
":",
"raise",
"MTurkServiceException",
"(",
"\"Invalid AWS credentials!\"",
")",
"except",
"Exception",
"as",
"ex",
":",
"raise",
"MTurkServiceException",
"(",
"\"Error checking credentials: {}\"",
".",
"format",
"(",
"str",
"(",
"ex",
")",
")",
")"
] | 43.083333 | 15.75 |
def cmd_part(self, connection, sender, target, payload):
"""
Asks the bot to leave a channel
"""
if payload:
connection.part(payload)
else:
raise ValueError("No channel given") | [
"def",
"cmd_part",
"(",
"self",
",",
"connection",
",",
"sender",
",",
"target",
",",
"payload",
")",
":",
"if",
"payload",
":",
"connection",
".",
"part",
"(",
"payload",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"No channel given\"",
")"
] | 29.125 | 9.625 |
def shall_save(self, form, name, composite_form):
"""
Return ``True`` if the given ``composite_form`` (the nested form of
this field) shall be saved. Return ``False`` if the form shall not be
saved together with the super-form.
By default it will return ``False`` if the form was not changed and the
``empty_permitted`` argument for the form was set to ``True``. That way
you can allow empty forms.
"""
if composite_form.empty_permitted and not composite_form.has_changed():
return False
return True | [
"def",
"shall_save",
"(",
"self",
",",
"form",
",",
"name",
",",
"composite_form",
")",
":",
"if",
"composite_form",
".",
"empty_permitted",
"and",
"not",
"composite_form",
".",
"has_changed",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | 44.615385 | 21.846154 |
def init(self, context):
"""Initializes sitetree to handle new request.
:param Context|None context:
"""
self.cache = Cache()
self.current_page_context = context
self.current_request = context.get('request', None) if context else None
self.current_lang = get_language()
self._current_app_is_admin = None
self._current_user_permissions = _UNSET
self._items_urls = {} # Resolved urls are cache for a request.
self._current_items = {} | [
"def",
"init",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"cache",
"=",
"Cache",
"(",
")",
"self",
".",
"current_page_context",
"=",
"context",
"self",
".",
"current_request",
"=",
"context",
".",
"get",
"(",
"'request'",
",",
"None",
")",
"if",
"context",
"else",
"None",
"self",
".",
"current_lang",
"=",
"get_language",
"(",
")",
"self",
".",
"_current_app_is_admin",
"=",
"None",
"self",
".",
"_current_user_permissions",
"=",
"_UNSET",
"self",
".",
"_items_urls",
"=",
"{",
"}",
"# Resolved urls are cache for a request.",
"self",
".",
"_current_items",
"=",
"{",
"}"
] | 36.357143 | 14.571429 |
def get_notebook_status(self, name):
"""Get the running named Notebook status.
:return: None if no notebook is running, otherwise context dictionary
"""
context = comm.get_context(self.get_pid(name))
if not context:
return None
return context | [
"def",
"get_notebook_status",
"(",
"self",
",",
"name",
")",
":",
"context",
"=",
"comm",
".",
"get_context",
"(",
"self",
".",
"get_pid",
"(",
"name",
")",
")",
"if",
"not",
"context",
":",
"return",
"None",
"return",
"context"
] | 32.777778 | 16.333333 |
def confirm(self, msg, _timeout=-1):
''' Send a confirm prompt to the GUI
Arguments:
msg (string):
The message to display to the user.
_timeout (int):
The optional amount of time for which the prompt
should be displayed to the user before a timeout occurs.
Defaults to -1 which indicates there is no timeout limit.
'''
return self.msgBox('confirm', _timeout=_timeout, msg=msg) | [
"def",
"confirm",
"(",
"self",
",",
"msg",
",",
"_timeout",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"msgBox",
"(",
"'confirm'",
",",
"_timeout",
"=",
"_timeout",
",",
"msg",
"=",
"msg",
")"
] | 38 | 21.846154 |
def ReadMessageHandlerRequests(self):
"""Reads all message handler requests from the database."""
res = []
leases = self.message_handler_leases
for requests in itervalues(self.message_handler_requests):
for r in itervalues(requests):
res.append(r.Copy())
existing_lease = leases.get(r.handler_name, {}).get(r.request_id, None)
res[-1].leased_until = existing_lease
return sorted(res, key=lambda r: -1 * r.timestamp) | [
"def",
"ReadMessageHandlerRequests",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"leases",
"=",
"self",
".",
"message_handler_leases",
"for",
"requests",
"in",
"itervalues",
"(",
"self",
".",
"message_handler_requests",
")",
":",
"for",
"r",
"in",
"itervalues",
"(",
"requests",
")",
":",
"res",
".",
"append",
"(",
"r",
".",
"Copy",
"(",
")",
")",
"existing_lease",
"=",
"leases",
".",
"get",
"(",
"r",
".",
"handler_name",
",",
"{",
"}",
")",
".",
"get",
"(",
"r",
".",
"request_id",
",",
"None",
")",
"res",
"[",
"-",
"1",
"]",
".",
"leased_until",
"=",
"existing_lease",
"return",
"sorted",
"(",
"res",
",",
"key",
"=",
"lambda",
"r",
":",
"-",
"1",
"*",
"r",
".",
"timestamp",
")"
] | 41.454545 | 15.181818 |
def dna(self, dna):
"""
Replace this chromosome's DNA with new DNA of equal length,
assigning the new DNA to the chromosome's genes sequentially.
For example, if a chromosome contains these genes...
1. 100100
2. 011011
...and the new DNA is 111111000000, the genes become:
1. 111111
2. 000000
"""
assert self.length == len(dna)
i = 0
for gene in self.genes:
gene.dna = dna[i:i + gene.length]
i += gene.length | [
"def",
"dna",
"(",
"self",
",",
"dna",
")",
":",
"assert",
"self",
".",
"length",
"==",
"len",
"(",
"dna",
")",
"i",
"=",
"0",
"for",
"gene",
"in",
"self",
".",
"genes",
":",
"gene",
".",
"dna",
"=",
"dna",
"[",
"i",
":",
"i",
"+",
"gene",
".",
"length",
"]",
"i",
"+=",
"gene",
".",
"length"
] | 28.5 | 19.05 |
def check_in_bounds(self, date):
'''Check that left and right bounds are sane
:param date: date to validate left/right bounds for
'''
dt = Timestamp(date)
return ((self._lbound is None or dt >= self._lbound) and
(self._rbound is None or dt <= self._rbound)) | [
"def",
"check_in_bounds",
"(",
"self",
",",
"date",
")",
":",
"dt",
"=",
"Timestamp",
"(",
"date",
")",
"return",
"(",
"(",
"self",
".",
"_lbound",
"is",
"None",
"or",
"dt",
">=",
"self",
".",
"_lbound",
")",
"and",
"(",
"self",
".",
"_rbound",
"is",
"None",
"or",
"dt",
"<=",
"self",
".",
"_rbound",
")",
")"
] | 38.375 | 20.625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.