text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def GetParsersInformation(cls):
"""Retrieves the parsers information.
Returns:
list[tuple[str, str]]: parser names and descriptions.
"""
parsers_information = []
for _, parser_class in cls.GetParsers():
description = getattr(parser_class, 'DESCRIPTION', '')
parsers_information.app... | [
"def",
"GetParsersInformation",
"(",
"cls",
")",
":",
"parsers_information",
"=",
"[",
"]",
"for",
"_",
",",
"parser_class",
"in",
"cls",
".",
"GetParsers",
"(",
")",
":",
"description",
"=",
"getattr",
"(",
"parser_class",
",",
"'DESCRIPTION'",
",",
"''",
... | 31.5 | 17.333333 |
def get_message_dict(self):
"""
Generate the various parts of the message and return them in a
dictionary, suitable for passing directly as keyword arguments
to ``django.core.mail.send_mail()``.
By default, the following values are returned:
* ``from_email``
* ... | [
"def",
"get_message_dict",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_valid",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Message cannot be sent from invalid contact form\"",
")",
"message_dict",
"=",
"{",
"}",
"for",
"message_part",
"in",
"(",
"'fro... | 29.777778 | 21.111111 |
def queue_message(self, message):
"""Queue a message to be sent later.
This operation should be followed up with send_pending_messages.
:param message: The message to be sent.
:type message: ~azure.servicebus.common.message.Message
Example:
.. literalinclude:: ../e... | [
"def",
"queue_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"self",
".",
"running",
":",
"self",
".",
"open",
"(",
")",
"if",
"self",
".",
"session_id",
"and",
"not",
"message",
".",
"properties",
".",
"group_id",
":",
"message",
".",
... | 36.173913 | 18.652174 |
def delete_folder(self, id, force=None):
"""
Delete folder.
Remove the specified folder. You can only delete empty folders unless you
set the 'force' flag
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - id
"""ID"""
... | [
"def",
"delete_folder",
"(",
"self",
",",
"id",
",",
"force",
"=",
"None",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"id\"",
"]",
"=",
"id",
"# OPTIONAL... | 34.590909 | 24.318182 |
def set(self, value):
"""
Sets the value of the object
:param value:
A byte string
"""
if not isinstance(value, byte_cls):
raise TypeError(unwrap(
'''
%s value must be a byte string, not %s
''',
... | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"byte_cls",
")",
":",
"raise",
"TypeError",
"(",
"unwrap",
"(",
"'''\n %s value must be a byte string, not %s\n '''",
",",
"type_name",
"("... | 24.44 | 14.6 |
def plot_movie_of_trajectory2d_with_matplotlib(
obs, plane='xy', figsize=6, grid=True,
wireframe=False, max_count=None, angle=None, noaxis=False,
interval=0.16, repeat_delay=3000, stride=1, rotate=None,
legend=True, output=None, crf=10, bitrate='1M', plot_range=None, **kwargs):
"""
... | [
"def",
"plot_movie_of_trajectory2d_with_matplotlib",
"(",
"obs",
",",
"plane",
"=",
"'xy'",
",",
"figsize",
"=",
"6",
",",
"grid",
"=",
"True",
",",
"wireframe",
"=",
"False",
",",
"max_count",
"=",
"None",
",",
"angle",
"=",
"None",
",",
"noaxis",
"=",
... | 36.352381 | 18.066667 |
def decorator(func):
r"""Makes the passed decorators to support optional args.
"""
def wrapper(__decorated__=None, *Args, **KwArgs):
if __decorated__ is None: # the decorator has some optional arguments.
return lambda _func: func(_func, *Args, **KwArgs)
else:
return func(__decorated__, *Args,... | [
"def",
"decorator",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"__decorated__",
"=",
"None",
",",
"*",
"Args",
",",
"*",
"*",
"KwArgs",
")",
":",
"if",
"__decorated__",
"is",
"None",
":",
"# the decorator has some optional arguments.",
"return",
"lambda",
... | 31.818182 | 19.272727 |
def checkConditions(self,verbose=False,verbose_reference=False,public_call=False):
'''
This method checks whether the instance's type satisfies the growth impatience condition
(GIC), return impatience condition (RIC), absolute impatience condition (AIC), weak return
impatience condition ... | [
"def",
"checkConditions",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"verbose_reference",
"=",
"False",
",",
"public_call",
"=",
"False",
")",
":",
"if",
"self",
".",
"cycles",
"!=",
"0",
"or",
"self",
".",
"T_cycle",
">",
"1",
":",
"if",
"verbose... | 53.442623 | 40 |
def char_offsets_to_xpaths(html, char_offsets):
'''Converts HTML and a sequence of char offsets to xpath offsets.
Returns a generator of :class:`streamcorpus.XpathRange` objects
in correspondences with the sequence of ``char_offsets`` given.
Namely, each ``XpathRange`` should address precisely the same... | [
"def",
"char_offsets_to_xpaths",
"(",
"html",
",",
"char_offsets",
")",
":",
"html",
"=",
"uni",
"(",
"html",
")",
"parser",
"=",
"XpathTextCollector",
"(",
")",
"prev_end",
"=",
"0",
"prev_progress",
"=",
"True",
"for",
"start",
",",
"end",
"in",
"char_of... | 43.517647 | 21.047059 |
async def recv_multipart(self):
"""
Read from all the associated sockets.
:returns: A list of tuples (socket, frames) for each socket that
returned a result.
"""
if not self._sockets:
return []
results = []
async def recv_and_store(socke... | [
"async",
"def",
"recv_multipart",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_sockets",
":",
"return",
"[",
"]",
"results",
"=",
"[",
"]",
"async",
"def",
"recv_and_store",
"(",
"socket",
")",
":",
"frames",
"=",
"await",
"socket",
".",
"recv_mu... | 25.03125 | 19.21875 |
def other_punctuation():
"""Match other punctuation.
Match other punctuation to split on; punctuation that naturally
inserts a break in speech.
"""
punc = ''.join(
set(symbols.ALL_PUNC) -
set(symbols.TONE_MARKS) -
set(symbols.PERIOD_COMMA) -
set(symbols.COLON))
... | [
"def",
"other_punctuation",
"(",
")",
":",
"punc",
"=",
"''",
".",
"join",
"(",
"set",
"(",
"symbols",
".",
"ALL_PUNC",
")",
"-",
"set",
"(",
"symbols",
".",
"TONE_MARKS",
")",
"-",
"set",
"(",
"symbols",
".",
"PERIOD_COMMA",
")",
"-",
"set",
"(",
... | 27.133333 | 15.4 |
def xcom_pull(
self,
task_ids=None,
dag_id=None,
key=XCOM_RETURN_KEY,
include_prior_dates=False):
"""
Pull XComs that optionally meet certain criteria.
The default value for `key` limits the search to XComs
that were returned b... | [
"def",
"xcom_pull",
"(",
"self",
",",
"task_ids",
"=",
"None",
",",
"dag_id",
"=",
"None",
",",
"key",
"=",
"XCOM_RETURN_KEY",
",",
"include_prior_dates",
"=",
"False",
")",
":",
"if",
"dag_id",
"is",
"None",
":",
"dag_id",
"=",
"self",
".",
"dag_id",
... | 41.94 | 22.26 |
def multiply(df, new_column, column_1, column_2):
"""
DEPRECATED - use `formula` instead
"""
return _basic_math_operation(df, new_column, column_1, column_2, op='mul') | [
"def",
"multiply",
"(",
"df",
",",
"new_column",
",",
"column_1",
",",
"column_2",
")",
":",
"return",
"_basic_math_operation",
"(",
"df",
",",
"new_column",
",",
"column_1",
",",
"column_2",
",",
"op",
"=",
"'mul'",
")"
] | 36 | 9.6 |
def devpiserver_cmdline_run(xom):
'''
Load theme when `theme` parameter is 'semantic-ui'.
'''
if xom.config.args.theme == 'semantic-ui':
xom.config.args.theme = resource_filename('devpi_semantic_ui', '')
xom.log.info("Semantic UI Theme loaded") | [
"def",
"devpiserver_cmdline_run",
"(",
"xom",
")",
":",
"if",
"xom",
".",
"config",
".",
"args",
".",
"theme",
"==",
"'semantic-ui'",
":",
"xom",
".",
"config",
".",
"args",
".",
"theme",
"=",
"resource_filename",
"(",
"'devpi_semantic_ui'",
",",
"''",
")"... | 38.571429 | 19.428571 |
def _build_js(inputs, outputs, name, implementation, support_code):
"""Creates a BigQuery SQL UDF javascript object.
Args:
inputs: a list of (name, type) tuples representing the schema of input.
outputs: a list of (name, type) tuples representing the schema of the output.
name: the name of th... | [
"def",
"_build_js",
"(",
"inputs",
",",
"outputs",
",",
"name",
",",
"implementation",
",",
"support_code",
")",
":",
"# Construct a comma-separated list of input field names",
"# For example, field1,field2,...",
"input_fields",
"=",
"json",
".",
"dumps",
"(",
"[",
"f",... | 51.230769 | 26.5 |
def description_from_content(self):
"""
Returns the first block or sentence of the first content-like
field.
"""
description = ""
# Use the first RichTextField, or TextField if none found.
for field_type in (RichTextField, models.TextField):
if not des... | [
"def",
"description_from_content",
"(",
"self",
")",
":",
"description",
"=",
"\"\"",
"# Use the first RichTextField, or TextField if none found.",
"for",
"field_type",
"in",
"(",
"RichTextField",
",",
"models",
".",
"TextField",
")",
":",
"if",
"not",
"description",
... | 42.111111 | 16.444444 |
def FromMany(cls, samples):
"""Constructs a single sample that best represents a list of samples.
Args:
samples: An iterable collection of `IOSample` instances.
Returns:
An `IOSample` instance representing `samples`.
Raises:
ValueError: If `samples` is empty.
"""
if not samp... | [
"def",
"FromMany",
"(",
"cls",
",",
"samples",
")",
":",
"if",
"not",
"samples",
":",
"raise",
"ValueError",
"(",
"\"Empty `samples` argument\"",
")",
"return",
"IOSample",
"(",
"timestamp",
"=",
"max",
"(",
"sample",
".",
"timestamp",
"for",
"sample",
"in",... | 30.210526 | 22 |
def is_union_type(type_):
""" Checks if the given type is a union type.
:param type_: The type to check
:return: True if the type is a union type, otherwise False
:rtype: bool
"""
if is_typing_type(type_) and hasattr(type_, "__origin__"):
# NOTE: union types can only be from typing mod... | [
"def",
"is_union_type",
"(",
"type_",
")",
":",
"if",
"is_typing_type",
"(",
"type_",
")",
"and",
"hasattr",
"(",
"type_",
",",
"\"__origin__\"",
")",
":",
"# NOTE: union types can only be from typing module",
"return",
"type_",
".",
"__origin__",
"in",
"_get_types"... | 32.333333 | 19 |
def register_handler(self, handler):
""" Register a new namespace handler. """
self._handlers[handler.namespace] = handler
handler.registered(self) | [
"def",
"register_handler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"_handlers",
"[",
"handler",
".",
"namespace",
"]",
"=",
"handler",
"handler",
".",
"registered",
"(",
"self",
")"
] | 33.6 | 12.6 |
def DownloadFile(ID, season=None, mission='k2', cadence='lc',
filename=None, clobber=False):
'''
Download a given :py:mod:`everest` file from MAST.
:param str mission: The mission name. Default `k2`
:param str cadence: The light curve cadence. Default `lc`
:param str filename: The ... | [
"def",
"DownloadFile",
"(",
"ID",
",",
"season",
"=",
"None",
",",
"mission",
"=",
"'k2'",
",",
"cadence",
"=",
"'lc'",
",",
"filename",
"=",
"None",
",",
"clobber",
"=",
"False",
")",
":",
"# Get season",
"if",
"season",
"is",
"None",
":",
"season",
... | 33.891304 | 20.021739 |
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
"""Asynchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
... | [
"async",
"def",
"send_rpc",
"(",
"self",
",",
"conn_id",
",",
"address",
",",
"rpc_id",
",",
"payload",
",",
"timeout",
")",
":",
"self",
".",
"_ensure_connection",
"(",
"conn_id",
",",
"True",
")",
"dev",
"=",
"self",
".",
"_get_property",
"(",
"conn_id... | 42.692308 | 24.692308 |
def _url(self, path: str) -> str:
"""
Computes the URL for a resource located at a given path on the server.
"""
url = "{}/{}".format(self.__base_url, path)
logger.debug("transformed path [%s] into url: %s", path, url)
return url | [
"def",
"_url",
"(",
"self",
",",
"path",
":",
"str",
")",
"->",
"str",
":",
"url",
"=",
"\"{}/{}\"",
".",
"format",
"(",
"self",
".",
"__base_url",
",",
"path",
")",
"logger",
".",
"debug",
"(",
"\"transformed path [%s] into url: %s\"",
",",
"path",
",",... | 38.714286 | 15.285714 |
def notify(self):
"""Notify the client.
The function passed to ``App.respond`` will get called.
"""
if flask.has_request_context():
emit(_NAME + str(self._uuid))
else:
sio = flask.current_app.extensions['socketio']
sio.emit(_NAME + str(self._u... | [
"def",
"notify",
"(",
"self",
")",
":",
"if",
"flask",
".",
"has_request_context",
"(",
")",
":",
"emit",
"(",
"_NAME",
"+",
"str",
"(",
"self",
".",
"_uuid",
")",
")",
"else",
":",
"sio",
"=",
"flask",
".",
"current_app",
".",
"extensions",
"[",
"... | 30.909091 | 14 |
def schedule_enabled():
'''
Check the status of automatic update scheduling.
:return: True if scheduling is enabled, False if disabled
:rtype: bool
CLI Example:
.. code-block:: bash
salt '*' softwareupdate.schedule_enabled
'''
cmd = ['softwareupdate', '--schedule']
ret = ... | [
"def",
"schedule_enabled",
"(",
")",
":",
"cmd",
"=",
"[",
"'softwareupdate'",
",",
"'--schedule'",
"]",
"ret",
"=",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_result",
"(",
"cmd",
")",
"enabled",
"=",
"ret",
".",
"split",
"(",
")",
"["... | 22.3 | 26.1 |
def docs_init_to_class(self):
"""If found a __init__ method's docstring and the class
without any docstring, so set the class docstring with __init__one,
and let __init__ without docstring.
:returns: True if done
:rtype: boolean
"""
result = False
if not... | [
"def",
"docs_init_to_class",
"(",
"self",
")",
":",
"result",
"=",
"False",
"if",
"not",
"self",
".",
"parsed",
":",
"self",
".",
"_parse",
"(",
")",
"einit",
"=",
"[",
"]",
"eclass",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"docs_list",
":",
... | 36.848485 | 14.545455 |
def _prepare_init_params_from_job_description(cls, job_details, model_channel_name=None):
"""Convert the job description to init params that can be handled by the class constructor
Args:
job_details: the returned job details from a describe_training_job API call.
model_channel_n... | [
"def",
"_prepare_init_params_from_job_description",
"(",
"cls",
",",
"job_details",
",",
"model_channel_name",
"=",
"None",
")",
":",
"init_params",
"=",
"super",
"(",
"Estimator",
",",
"cls",
")",
".",
"_prepare_init_params_from_job_description",
"(",
"job_details",
... | 45.066667 | 33.133333 |
def is_university(addr):
# type: (Union[str, unicode]) -> bool
""" Check if provided email has a university domain
- either in .edu domain
(except public sercices like england.edu or australia.edu)
- or in .edu.TLD (non-US based institutions, like edu.au)
- or listed in a public list of uni... | [
"def",
"is_university",
"(",
"addr",
")",
":",
"# type: (Union[str, unicode]) -> bool",
"addr_domain",
"=",
"domain",
"(",
"addr",
")",
"if",
"not",
"addr_domain",
":",
"# invalid email",
"return",
"False",
"chunks",
"=",
"addr_domain",
".",
"split",
"(",
"\".\"",... | 40.363636 | 20.181818 |
def _get_bit(self, n, hash_bytes):
"""
Determines if the n-th bit of passed bytes is 1 or 0.
Arguments:
hash_bytes - List of hash byte values for which the n-th bit value
should be checked. Each element of the list should be an integer from
0 to 255.
Retu... | [
"def",
"_get_bit",
"(",
"self",
",",
"n",
",",
"hash_bytes",
")",
":",
"if",
"hash_bytes",
"[",
"n",
"//",
"8",
"]",
">>",
"int",
"(",
"8",
"-",
"(",
"(",
"n",
"%",
"8",
")",
"+",
"1",
")",
")",
"&",
"1",
"==",
"1",
":",
"return",
"True",
... | 25.631579 | 25.526316 |
def json_rpc_format(self):
""" return the Exception data in a format for JSON-RPC """
error = {
'name': smart_text(self.__class__.__name__),
'code': self.code,
'message': "%s: %s" %
(smart_text(self.__class__.__name__), smart_text(self.message)),
... | [
"def",
"json_rpc_format",
"(",
"self",
")",
":",
"error",
"=",
"{",
"'name'",
":",
"smart_text",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
",",
"'code'",
":",
"self",
".",
"code",
",",
"'message'",
":",
"\"%s: %s\"",
"%",
"(",
"smart_text",
... | 29.473684 | 19.368421 |
def configure(self, reboot=1):
"""
Assigns a name to the server accessible from user space.
Note, we add the name to /etc/hosts since not all programs use
/etc/hostname to reliably identify the server hostname.
"""
r = self.local_renderer
for ip, hostname in self... | [
"def",
"configure",
"(",
"self",
",",
"reboot",
"=",
"1",
")",
":",
"r",
"=",
"self",
".",
"local_renderer",
"for",
"ip",
",",
"hostname",
"in",
"self",
".",
"iter_hostnames",
"(",
")",
":",
"self",
".",
"vprint",
"(",
"'ip/hostname:'",
",",
"ip",
",... | 44.333333 | 16.111111 |
def post_execute(self):
"""
Gets executed after the actual execution.
:return: None if successful, otherwise error message
:rtype: str
"""
result = super(Sink, self).post_execute()
if result is None:
self._input = None
return result | [
"def",
"post_execute",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
"Sink",
",",
"self",
")",
".",
"post_execute",
"(",
")",
"if",
"result",
"is",
"None",
":",
"self",
".",
"_input",
"=",
"None",
"return",
"result"
] | 27.181818 | 14.454545 |
def atlasdb_open( path ):
"""
Open the atlas db.
Return a connection.
Return None if it doesn't exist
"""
if not os.path.exists(path):
log.debug("Atlas DB doesn't exist at %s" % path)
return None
con = sqlite3.connect( path, isolation_level=None )
con.row_factory = atlas... | [
"def",
"atlasdb_open",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"log",
".",
"debug",
"(",
"\"Atlas DB doesn't exist at %s\"",
"%",
"path",
")",
"return",
"None",
"con",
"=",
"sqlite3",
".",
"connect",
... | 25.923077 | 13.923077 |
def train_async(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None):
"""Train model. The output can be used for batch prediction or online deployment.
Args:
input_dir: A directory path containing preprocessed results. Can be local or GCS path.
batch_size: size of batch used for train... | [
"def",
"train_async",
"(",
"input_dir",
",",
"batch_size",
",",
"max_steps",
",",
"output_dir",
",",
"checkpoint",
"=",
"None",
",",
"cloud",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
... | 47.619048 | 28.285714 |
def _wait_for_outputs(self, timeout=-1):
"""wait for the 'status=idle' message that indicates we have all outputs
"""
if not self._success:
# don't wait on errors
return
tic = time.time()
while not all(md['outputs_ready'] for md in self._metadata):
... | [
"def",
"_wait_for_outputs",
"(",
"self",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"if",
"not",
"self",
".",
"_success",
":",
"# don't wait on errors",
"return",
"tic",
"=",
"time",
".",
"time",
"(",
")",
"while",
"not",
"all",
"(",
"md",
"[",
"'outputs... | 39.916667 | 13.166667 |
def _set_show_firmware_version(self, v, load=False):
"""
Setter method for show_firmware_version, mapped from YANG variable /brocade_firmware_ext_rpc/show_firmware_version (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_firmware_version is considered as a priv... | [
"def",
"_set_show_firmware_version",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | 75.041667 | 36.833333 |
def ExceptionHook(exctype, value, tb):
'''
A custom exception handler that logs errors to file.
'''
for line in traceback.format_exception_only(exctype, value):
log.error(line.replace('\n', ''))
for line in traceback.format_tb(tb):
log.error(line.replace('\n', ''))
sys.__except... | [
"def",
"ExceptionHook",
"(",
"exctype",
",",
"value",
",",
"tb",
")",
":",
"for",
"line",
"in",
"traceback",
".",
"format_exception_only",
"(",
"exctype",
",",
"value",
")",
":",
"log",
".",
"error",
"(",
"line",
".",
"replace",
"(",
"'\\n'",
",",
"''"... | 30.545455 | 17.454545 |
def format_price_commas(price):
"""
Formats prices, rounding (i.e. to the nearest whole number of pounds) with commas
"""
if price is None:
return None
if price >= 0:
return jinja2.Markup('£{:,.2f}'.format(price))
else:
return jinja2.Markup('-£{:,.2f}'.format(... | [
"def",
"format_price_commas",
"(",
"price",
")",
":",
"if",
"price",
"is",
"None",
":",
"return",
"None",
"if",
"price",
">=",
"0",
":",
"return",
"jinja2",
".",
"Markup",
"(",
"'£{:,.2f}'",
".",
"format",
"(",
"price",
")",
")",
"else",
":",
"re... | 31.9 | 18.9 |
def post(self, request, bot_id, format=None):
"""
Add a new chat state
---
serializer: TelegramChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"TelegramChatStateList",
",",
"self",
")",
".",
"post",
"(",
"request",
",",
"bot_id",
",",
"format",
")"
] | 31.916667 | 11.75 |
def copy_path_to_clipboard(self):
"""
Copies the file path to the clipboard
"""
path = self.get_current_path()
QtWidgets.QApplication.clipboard().setText(path)
debug('path copied: %s' % path) | [
"def",
"copy_path_to_clipboard",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"get_current_path",
"(",
")",
"QtWidgets",
".",
"QApplication",
".",
"clipboard",
"(",
")",
".",
"setText",
"(",
"path",
")",
"debug",
"(",
"'path copied: %s'",
"%",
"path",
... | 33.285714 | 4.428571 |
def _latch_file_info(self):
"""Internal function to update the dictionaries
keeping track of input and output files
"""
self.files.file_dict.clear()
self.files.latch_file_info(self.args) | [
"def",
"_latch_file_info",
"(",
"self",
")",
":",
"self",
".",
"files",
".",
"file_dict",
".",
"clear",
"(",
")",
"self",
".",
"files",
".",
"latch_file_info",
"(",
"self",
".",
"args",
")"
] | 36.833333 | 4.833333 |
def simulateSytematicError(N_SAMPLES=5, N_IMAGES=10,
SHOW_DETECTED_PATTERN=True, # GRAYSCALE=False,
HEIGHT=500, PLOT_RESULTS=True, PLOT_ERROR_ARRAY=True,
CAMERA_PARAM=None, PERSPECTIVE=True, ROTATION=True,
R... | [
"def",
"simulateSytematicError",
"(",
"N_SAMPLES",
"=",
"5",
",",
"N_IMAGES",
"=",
"10",
",",
"SHOW_DETECTED_PATTERN",
"=",
"True",
",",
"# GRAYSCALE=False,\r",
"HEIGHT",
"=",
"500",
",",
"PLOT_RESULTS",
"=",
"True",
",",
"PLOT_ERROR_ARRAY",
"=",
"True",
",",
... | 38.310249 | 20.969529 |
def fix_base(fix_environ):
"""Activate the base compatibility."""
def _is_android():
import os
vm_path = os.sep+"system"+os.sep+"bin"+os.sep+"dalvikvm"
if os.path.exists(vm_path) or os.path.exists(os.sep+"system"+vm_path):
return True
try:
import android
... | [
"def",
"fix_base",
"(",
"fix_environ",
")",
":",
"def",
"_is_android",
"(",
")",
":",
"import",
"os",
"vm_path",
"=",
"os",
".",
"sep",
"+",
"\"system\"",
"+",
"os",
".",
"sep",
"+",
"\"bin\"",
"+",
"os",
".",
"sep",
"+",
"\"dalvikvm\"",
"if",
"os",
... | 31.163636 | 19.163636 |
def _load_with_overrides(base) -> Dict[str, str]:
""" Load an config or write its defaults """
should_write = False
overrides = _get_environ_overrides()
try:
index = json.load((base/_CONFIG_FILENAME).open())
except (OSError, json.JSONDecodeError) as e:
sys.stderr.write("Error loading... | [
"def",
"_load_with_overrides",
"(",
"base",
")",
"->",
"Dict",
"[",
"str",
",",
"str",
"]",
":",
"should_write",
"=",
"False",
"overrides",
"=",
"_get_environ_overrides",
"(",
")",
"try",
":",
"index",
"=",
"json",
".",
"load",
"(",
"(",
"base",
"/",
"... | 36.53125 | 15.84375 |
def plot_ion_relaxation(self, **kwargs):
"""
Plot the history of the ion-cell relaxation.
kwargs are passed to the plot method of :class:`HistFile`
Return `matplotlib` figure or None if hist file is not found.
"""
with self.ion_task.open_hist() as hist:
retur... | [
"def",
"plot_ion_relaxation",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"ion_task",
".",
"open_hist",
"(",
")",
"as",
"hist",
":",
"return",
"hist",
".",
"plot",
"(",
"*",
"*",
"kwargs",
")",
"if",
"hist",
"else",
"None"
] | 39 | 14.333333 |
def saveSV(fname, X, comments=None, metadata=None, printmetadict=None,
dialect=None, delimiter=None, doublequote=True,
lineterminator='\n', escapechar = None,
quoting=csv.QUOTE_MINIMAL, quotechar='"',
skipinitialspace=False, stringifier=None... | [
"def",
"saveSV",
"(",
"fname",
",",
"X",
",",
"comments",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"printmetadict",
"=",
"None",
",",
"dialect",
"=",
"None",
",",
"delimiter",
"=",
"None",
",",
"doublequote",
"=",
"True",
",",
"lineterminator",
... | 39.536842 | 23.989474 |
def _assoc_prop_matches(prop, ref_classname,
assoc_classes, result_classes, result_role):
"""
Test filters of a reference property and its associated entity
Returns `True` if matches the criteria. Returns `False` if it does not
match.
Matches if ref_c... | [
"def",
"_assoc_prop_matches",
"(",
"prop",
",",
"ref_classname",
",",
"assoc_classes",
",",
"result_classes",
",",
"result_role",
")",
":",
"assert",
"prop",
".",
"type",
"==",
"'reference'",
"if",
"assoc_classes",
"and",
"ref_classname",
"not",
"in",
"assoc_class... | 38 | 21.578947 |
def get_status_display(self, **kwargs):
"""
Define how status is displayed in UIs (add units etc.).
"""
if 'value' in kwargs:
value = kwargs['value']
else:
value = self.status
if self.show_stdev_seconds:
stdev = self.stdev(self.sho... | [
"def",
"get_status_display",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'value'",
"in",
"kwargs",
":",
"value",
"=",
"kwargs",
"[",
"'value'",
"]",
"else",
":",
"value",
"=",
"self",
".",
"status",
"if",
"self",
".",
"show_stdev_seconds",
"... | 29.214286 | 12.785714 |
def fetch_pdb(pdbid):
"""Get the newest entry from the RCSB server for the given PDB ID. Exits with '1' if PDB ID is invalid."""
pdbid = pdbid.lower()
write_message('\nChecking status of PDB ID %s ... ' % pdbid)
state, current_entry = check_pdb_status(pdbid) # Get state and current PDB ID
if state... | [
"def",
"fetch_pdb",
"(",
"pdbid",
")",
":",
"pdbid",
"=",
"pdbid",
".",
"lower",
"(",
")",
"write_message",
"(",
"'\\nChecking status of PDB ID %s ... '",
"%",
"pdbid",
")",
"state",
",",
"current_entry",
"=",
"check_pdb_status",
"(",
"pdbid",
")",
"# Get state ... | 52.347826 | 24.695652 |
def get_document_field_display(self, field_name, field):
""" Render a link to a document """
document = getattr(self.instance, field_name)
if document:
return mark_safe(
'<a href="%s">%s <span class="meta">(%s, %s)</span></a>' % (
document.url,
... | [
"def",
"get_document_field_display",
"(",
"self",
",",
"field_name",
",",
"field",
")",
":",
"document",
"=",
"getattr",
"(",
"self",
".",
"instance",
",",
"field_name",
")",
"if",
"document",
":",
"return",
"mark_safe",
"(",
"'<a href=\"%s\">%s <span class=\"meta... | 41.461538 | 15.538462 |
def populate_tree(self, master, parent, element,from_file=False):
"""Reads xml nodes and populates tree item"""
data = WidgetDescr(None, None)
data.from_xml_node(element)
cname = data.get_class()
uniqueid = self.get_unique_id(cname, data.get_id())
data.set_property('id',... | [
"def",
"populate_tree",
"(",
"self",
",",
"master",
",",
"parent",
",",
"element",
",",
"from_file",
"=",
"False",
")",
":",
"data",
"=",
"WidgetDescr",
"(",
"None",
",",
"None",
")",
"data",
".",
"from_xml_node",
"(",
"element",
")",
"cname",
"=",
"da... | 39.75 | 18.6 |
def tabfile2list(fname):
"tabfile2list"
#dat = mylib1.readfileasmac(fname)
#data = string.strip(dat)
data = mylib1.readfileasmac(fname)
#data = data[:-2]#remove the last return
alist = data.split('\r')#since I read it as a mac file
blist = alist[1].split('\t')
clist = []
for num in ... | [
"def",
"tabfile2list",
"(",
"fname",
")",
":",
"#dat = mylib1.readfileasmac(fname)",
"#data = string.strip(dat)",
"data",
"=",
"mylib1",
".",
"readfileasmac",
"(",
"fname",
")",
"#data = data[:-2]#remove the last return",
"alist",
"=",
"data",
".",
"split",
"(",
"'\\r'"... | 32.133333 | 14.4 |
def add(i):
"""
Input: {
(repo_uoa) - repo UOA
module_uoa - module UOA
data_uoa - data UOA
(data_uid) - data UID (if uoa is an alias)
(data_name) - user friendly data name
... | [
"def",
"add",
"(",
"i",
")",
":",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"t",
"=",
"'added'",
"ra",
"=",
"i",
".",
"get",
"(",
"'repo_uoa'",
",",
"''",
")",
"m",
"=",
"i",
".",
"get",
"(",
"'module_uoa'",
",",
"''",
")",
... | 28.589812 | 21.715818 |
def _var_uint_field_handler(handler, ctx):
"""Handler co-routine for variable unsigned integer fields that.
Invokes the given ``handler`` function with the read field and context,
then immediately yields to the resulting co-routine.
"""
_, self = yield
queue = ctx.queue
value = 0
while ... | [
"def",
"_var_uint_field_handler",
"(",
"handler",
",",
"ctx",
")",
":",
"_",
",",
"self",
"=",
"yield",
"queue",
"=",
"ctx",
".",
"queue",
"value",
"=",
"0",
"while",
"True",
":",
"if",
"len",
"(",
"queue",
")",
"==",
"0",
":",
"# We don't know when th... | 36.578947 | 15.578947 |
async def handler(event):
"""#ot, #offtopic: Tells the user to move to @TelethonOffTopic."""
await asyncio.wait([
event.delete(),
event.respond(OFFTOPIC[event.chat_id], reply_to=event.reply_to_msg_id)
]) | [
"async",
"def",
"handler",
"(",
"event",
")",
":",
"await",
"asyncio",
".",
"wait",
"(",
"[",
"event",
".",
"delete",
"(",
")",
",",
"event",
".",
"respond",
"(",
"OFFTOPIC",
"[",
"event",
".",
"chat_id",
"]",
",",
"reply_to",
"=",
"event",
".",
"r... | 37.666667 | 20 |
def process_git_configs(git_short=''):
"""Retrieve _application.json_ files from GitLab.
Args:
git_short (str): Short Git representation of repository, e.g.
forrest/core.
Returns:
collections.defaultdict: Configurations stored for each environment
found.
"""
LOG... | [
"def",
"process_git_configs",
"(",
"git_short",
"=",
"''",
")",
":",
"LOG",
".",
"info",
"(",
"'Processing application.json files from GitLab \"%s\".'",
",",
"git_short",
")",
"file_lookup",
"=",
"FileLookup",
"(",
"git_short",
"=",
"git_short",
")",
"app_configs",
... | 41.285714 | 21.285714 |
def copy_image(source_region, image_id, name, profile, description=None, **libcloud_kwargs):
'''
Copies an image from a source region to the current region.
:param source_region: Region to copy the node from.
:type source_region: ``str``
:param image_id: Image to copy.
:type image_id: ``str``
... | [
"def",
"copy_image",
"(",
"source_region",
",",
"image_id",
",",
"name",
",",
"profile",
",",
"description",
"=",
"None",
",",
"*",
"*",
"libcloud_kwargs",
")",
":",
"conn",
"=",
"_get_driver",
"(",
"profile",
"=",
"profile",
")",
"libcloud_kwargs",
"=",
"... | 31.882353 | 24.705882 |
def connect_by_uri(uri):
"""General URI syntax:
mysql://user:passwd@host:port/db?opt1=val1&opt2=val2&...
where opt_n is in the list of options supported by MySQLdb:
host,user,passwd,db,compress,connect_timeout,read_default_file,
read_default_group,unix_socket,port
NOTE: the authority... | [
"def",
"connect_by_uri",
"(",
"uri",
")",
":",
"puri",
"=",
"urisup",
".",
"uri_help_split",
"(",
"uri",
")",
"params",
"=",
"__dict_from_query",
"(",
"puri",
"[",
"QUERY",
"]",
")",
"if",
"puri",
"[",
"AUTHORITY",
"]",
":",
"user",
",",
"passwd",
",",... | 40.917647 | 23.188235 |
def _initLayerCtors(self):
'''
Registration for built-in Layer ctors
'''
ctors = {
'lmdb': s_lmdblayer.LmdbLayer,
'remote': s_remotelayer.RemoteLayer,
}
self.layrctors.update(**ctors) | [
"def",
"_initLayerCtors",
"(",
"self",
")",
":",
"ctors",
"=",
"{",
"'lmdb'",
":",
"s_lmdblayer",
".",
"LmdbLayer",
",",
"'remote'",
":",
"s_remotelayer",
".",
"RemoteLayer",
",",
"}",
"self",
".",
"layrctors",
".",
"update",
"(",
"*",
"*",
"ctors",
")"
... | 27.444444 | 15.888889 |
def register_prop(name, handler_get, handler_set):
"""
register a property handler
"""
global props_get, props_set
if handler_get:
props_get[name] = handler_get
if handler_set:
props_set[name] = handler_set | [
"def",
"register_prop",
"(",
"name",
",",
"handler_get",
",",
"handler_set",
")",
":",
"global",
"props_get",
",",
"props_set",
"if",
"handler_get",
":",
"props_get",
"[",
"name",
"]",
"=",
"handler_get",
"if",
"handler_set",
":",
"props_set",
"[",
"name",
"... | 26.444444 | 8.444444 |
def _set_label(self, which, label, **kwargs):
"""Private method for setting labels.
Args:
which (str): The indicator of which part of the plots
to adjust. This currently handles `xlabel`/`ylabel`,
and `title`.
label (str): The label to be added.
... | [
"def",
"_set_label",
"(",
"self",
",",
"which",
",",
"label",
",",
"*",
"*",
"kwargs",
")",
":",
"prop_default",
"=",
"{",
"'fontsize'",
":",
"18",
",",
"}",
"for",
"prop",
",",
"default",
"in",
"prop_default",
".",
"items",
"(",
")",
":",
"kwargs",
... | 31.5 | 19.954545 |
def delete_query(self, project, query):
"""DeleteQuery.
[Preview API] Delete a query or a folder. This deletes any permission change on the deleted query or folder and any of its descendants if it is a folder. It is important to note that the deleted permission changes cannot be recovered upon undeletin... | [
"def",
"delete_query",
"(",
"self",
",",
"project",
",",
"query",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'project'",
"... | 61.333333 | 29.2 |
def AsServer(port=80, services=()):
'''port --
services -- list of service instances
'''
address = ('', port)
sc = ServiceContainer(address, services)
sc.serve_forever() | [
"def",
"AsServer",
"(",
"port",
"=",
"80",
",",
"services",
"=",
"(",
")",
")",
":",
"address",
"=",
"(",
"''",
",",
"port",
")",
"sc",
"=",
"ServiceContainer",
"(",
"address",
",",
"services",
")",
"sc",
".",
"serve_forever",
"(",
")"
] | 27.142857 | 15.142857 |
def _spec_fft(self, complex_data):
'''
Calculates the DFT of the complex_data along axis = 1. This assumes complex_data is a 2D array.
This uses numpy and the code is straight forward
np.fft.fftshift( np.fft.fft(complex_data), 1)
Note that we automatically shift the FFT frequency bins so that alo... | [
"def",
"_spec_fft",
"(",
"self",
",",
"complex_data",
")",
":",
"return",
"np",
".",
"fft",
".",
"fftshift",
"(",
"np",
".",
"fft",
".",
"fft",
"(",
"complex_data",
")",
",",
"1",
")"
] | 45.454545 | 33.090909 |
def fill_nulls(self, col: str):
"""
Fill all null values with NaN values in a column.
Null values are ``None`` or en empty string
:param col: column name
:type col: str
:example: ``ds.fill_nulls("mycol")``
"""
n = [None, ""]
try:
self... | [
"def",
"fill_nulls",
"(",
"self",
",",
"col",
":",
"str",
")",
":",
"n",
"=",
"[",
"None",
",",
"\"\"",
"]",
"try",
":",
"self",
".",
"df",
"[",
"col",
"]",
"=",
"self",
".",
"df",
"[",
"col",
"]",
".",
"replace",
"(",
"n",
",",
"nan",
")",... | 26.666667 | 15.733333 |
def generate(self, local_go_targets):
"""Automatically generates a Go target graph for the given local go targets.
:param iter local_go_targets: The target roots to fill in a target graph for.
:raises: :class:`GoTargetGenerator.GenerationError` if any missing targets cannot be generated.
"""
visite... | [
"def",
"generate",
"(",
"self",
",",
"local_go_targets",
")",
":",
"visited",
"=",
"{",
"l",
".",
"import_path",
":",
"l",
".",
"address",
"for",
"l",
"in",
"local_go_targets",
"}",
"with",
"temporary_dir",
"(",
")",
"as",
"gopath",
":",
"for",
"local_go... | 52 | 20.75 |
def entries(self, start = None, end = None):
'''Retrieves entries from all people/tasks logged to this project.
Can be filtered based on time by specifying start/end datetimes.'''
if not start:
start = self.earliest_record
if not end:
end = self.latest_record
... | [
"def",
"entries",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"if",
"not",
"start",
":",
"start",
"=",
"self",
".",
"earliest_record",
"if",
"not",
"end",
":",
"end",
"=",
"self",
".",
"latest_record",
"fr",
"=",
"sta... | 34.611111 | 17.722222 |
def get_inflators_cn_to_cn(target_year):
'''
Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale.
'''
data_year = find_nearest_inferior(data_years, target_year)
data_year_cn_aggregates = get_cn_aggregates(data_year)['consoCN_COICOP_{}'.format(data_year)].to_dict()... | [
"def",
"get_inflators_cn_to_cn",
"(",
"target_year",
")",
":",
"data_year",
"=",
"find_nearest_inferior",
"(",
"data_years",
",",
"target_year",
")",
"data_year_cn_aggregates",
"=",
"get_cn_aggregates",
"(",
"data_year",
")",
"[",
"'consoCN_COICOP_{}'",
".",
"format",
... | 48.166667 | 35 |
def persistent_object_context_changed(self):
""" Override from PersistentObject. """
super().persistent_object_context_changed()
def source_registered(source):
self.__source = source
def source_unregistered(source=None):
pass
def reference_registered(pr... | [
"def",
"persistent_object_context_changed",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"persistent_object_context_changed",
"(",
")",
"def",
"source_registered",
"(",
"source",
")",
":",
"self",
".",
"__source",
"=",
"source",
"def",
"source_unregistered",
"("... | 49.321429 | 35.5 |
def filter(self, model=None, context=None):
"""
Perform filtering on the model. Will change model in place.
:param model: object or dict
:param context: object, dict or None
:return: None
"""
if model is None:
return
# properties
self.... | [
"def",
"filter",
"(",
"self",
",",
"model",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"model",
"is",
"None",
":",
"return",
"# properties",
"self",
".",
"filter_properties",
"(",
"model",
",",
"context",
"=",
"context",
")",
"# entities",... | 27.555556 | 17.555556 |
def configure(server=None, username=None, password=None, tid=None, auto=False):
"""
Configure tmc.py to use your account.
"""
if not server and not username and not password and not tid:
if Config.has():
if not yn_prompt("Override old configuration", False):
return Fa... | [
"def",
"configure",
"(",
"server",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"tid",
"=",
"None",
",",
"auto",
"=",
"False",
")",
":",
"if",
"not",
"server",
"and",
"not",
"username",
"and",
"not",
"password",
"and"... | 35.245614 | 15.982456 |
def run_server(working_dir, foreground=False, expected_snapshots=GENESIS_SNAPSHOT, port=None, api_port=None, use_api=None, use_indexer=None, indexer_url=None, recover=False):
"""
Run blockstackd. Optionally daemonize.
Return 0 on success
Return negative on error
"""
global rpc_server
global... | [
"def",
"run_server",
"(",
"working_dir",
",",
"foreground",
"=",
"False",
",",
"expected_snapshots",
"=",
"GENESIS_SNAPSHOT",
",",
"port",
"=",
"None",
",",
"api_port",
"=",
"None",
",",
"use_api",
"=",
"None",
",",
"use_indexer",
"=",
"None",
",",
"indexer_... | 30.684211 | 21.921053 |
def check_pianoroll(arr):
"""
Return True if the array is a standard piano-roll matrix. Otherwise,
return False. Raise TypeError if the input object is not a numpy array.
"""
if not isinstance(arr, np.ndarray):
raise TypeError("`arr` must be of np.ndarray type")
if not (np.issubdtype(ar... | [
"def",
"check_pianoroll",
"(",
"arr",
")",
":",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"\"`arr` must be of np.ndarray type\"",
")",
"if",
"not",
"(",
"np",
".",
"issubdtype",
"(",
"arr",
".",
... | 31.5625 | 17.3125 |
def trace_engine(engine):
"""Register the event before cursor execute and after cursor execute
to the event listner of the engine.
"""
event.listen(engine, 'before_cursor_execute', _before_cursor_execute)
event.listen(engine, 'after_cursor_execute', _after_cursor_execute) | [
"def",
"trace_engine",
"(",
"engine",
")",
":",
"event",
".",
"listen",
"(",
"engine",
",",
"'before_cursor_execute'",
",",
"_before_cursor_execute",
")",
"event",
".",
"listen",
"(",
"engine",
",",
"'after_cursor_execute'",
",",
"_after_cursor_execute",
")"
] | 47.833333 | 13.333333 |
async def check(self, message: types.Message):
"""
If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler
:param message:
:return:
"""
check = await super(CommandStart, self).check(message)
if check and self... | [
"async",
"def",
"check",
"(",
"self",
",",
"message",
":",
"types",
".",
"Message",
")",
":",
"check",
"=",
"await",
"super",
"(",
"CommandStart",
",",
"self",
")",
".",
"check",
"(",
"message",
")",
"if",
"check",
"and",
"self",
".",
"deep_link",
"i... | 32.578947 | 22.578947 |
def add_grid(self, *args, **kwargs):
"""
Create a new Grid and add it as a child widget.
All arguments are given to Grid().
"""
from .grid import Grid
grid = Grid(*args, **kwargs)
return self.add_widget(grid) | [
"def",
"add_grid",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"grid",
"import",
"Grid",
"grid",
"=",
"Grid",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"add_widget",
"(",
"grid",
")"... | 28.555556 | 8.777778 |
def add_css(self, subdir, file_name_prefix):
"""Add a css file for this resource.
If self.minify is True, checks if the .min.css file exists. If not, falls back to non-minified file. If that
file also doesn't exist, IOError is raised.
Positional arguments:
subdir -- sub directo... | [
"def",
"add_css",
"(",
"self",
",",
"subdir",
",",
"file_name_prefix",
")",
":",
"suffix_maxify",
"=",
"'.css'",
"suffix_minify",
"=",
"'.min.css'",
"if",
"self",
".",
"minify",
"and",
"self",
".",
"file_exists",
"(",
"subdir",
",",
"file_name_prefix",
",",
... | 57.526316 | 32.947368 |
def ne_(self, value):
''' Creates a query expression where ``this field != value``
.. note:: The prefered usage is via an operator: ``User.name != value``
'''
if isinstance(value, QueryField):
return self.__cached_id != value.__cached_id
return self.__comparator(... | [
"def",
"ne_",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"QueryField",
")",
":",
"return",
"self",
".",
"__cached_id",
"!=",
"value",
".",
"__cached_id",
"return",
"self",
".",
"__comparator",
"(",
"'$ne'",
",",
"value",
... | 40.75 | 22.75 |
def delete(self, id ):
""" Delete a token """
target_url = self.client.get_url('TOKEN', 'DELETE', 'single', {'id':id})
r = self.client.request('DELETE', target_url, headers={'Content-type': 'application/json'})
r.raise_for_status() | [
"def",
"delete",
"(",
"self",
",",
"id",
")",
":",
"target_url",
"=",
"self",
".",
"client",
".",
"get_url",
"(",
"'TOKEN'",
",",
"'DELETE'",
",",
"'single'",
",",
"{",
"'id'",
":",
"id",
"}",
")",
"r",
"=",
"self",
".",
"client",
".",
"request",
... | 43.166667 | 28.166667 |
def _connect_model_signals(model):
"""Connect signals for a single model."""
dispatch_uid = "%s.post_save" % model._meta.model_name
logger.debug("Connecting search index model post_save signal: %s", dispatch_uid)
signals.post_save.connect(_on_model_save, sender=model, dispatch_uid=dispatch_uid)
disp... | [
"def",
"_connect_model_signals",
"(",
"model",
")",
":",
"dispatch_uid",
"=",
"\"%s.post_save\"",
"%",
"model",
".",
"_meta",
".",
"model_name",
"logger",
".",
"debug",
"(",
"\"Connecting search index model post_save signal: %s\"",
",",
"dispatch_uid",
")",
"signals",
... | 55.5 | 24.8 |
def emit(self, record):
"""
Throws an error based on the information that the logger reported,
given the logging level.
:param record | <logging.LogRecord>
"""
# if we've already processed this record, ignore it
if record in self._recordQueu... | [
"def",
"emit",
"(",
"self",
",",
"record",
")",
":",
"# if we've already processed this record, ignore it\r",
"if",
"record",
"in",
"self",
".",
"_recordQueue",
":",
"return",
"if",
"self",
".",
"_activeLevels",
"and",
"not",
"record",
".",
"levelno",
"in",
"sel... | 30.692308 | 17.115385 |
def find_descriptor_schemas(self, schema_file):
"""Find descriptor schemas in given path."""
if not schema_file.lower().endswith(('.yml', '.yaml')):
return []
with open(schema_file) as fn:
schemas = yaml.load(fn, Loader=yaml.FullLoader)
if not schemas:
... | [
"def",
"find_descriptor_schemas",
"(",
"self",
",",
"schema_file",
")",
":",
"if",
"not",
"schema_file",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"(",
"'.yml'",
",",
"'.yaml'",
")",
")",
":",
"return",
"[",
"]",
"with",
"open",
"(",
"schema_file",
... | 31.789474 | 18.736842 |
def remove_all_bucket_notification(self, bucket_name):
"""
Removes all bucket notification configs configured
previously, this call disable event notifications
on a bucket. This operation cannot be undone, to
set notifications again you should use
``set_bucket_notificatio... | [
"def",
"remove_all_bucket_notification",
"(",
"self",
",",
"bucket_name",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"content_bytes",
"=",
"xml_marshal_bucket_notifications",
"(",
"{",
"}",
")",
"headers",
"=",
"{",
"'Content-Length'",
":",
"str",
"(... | 34.846154 | 15 |
def __create_heatmap_plot(self):
"""Method to actually create the heatmap from profile stats."""
# Define the heatmap plot.
height = len(self.pyfile.lines) / 3
width = max(map(lambda x: len(x), self.pyfile.lines)) / 8
self.fig, self.ax = plt.subplots(figsize=(width, height))
... | [
"def",
"__create_heatmap_plot",
"(",
"self",
")",
":",
"# Define the heatmap plot.",
"height",
"=",
"len",
"(",
"self",
".",
"pyfile",
".",
"lines",
")",
"/",
"3",
"width",
"=",
"max",
"(",
"map",
"(",
"lambda",
"x",
":",
"len",
"(",
"x",
")",
",",
"... | 36.962264 | 17.924528 |
def searchRnaQuantificationsInDb(
self, rnaQuantificationId=""):
"""
:param rnaQuantificationId: string restrict search by id
:return an array of dictionaries, representing the returned data.
"""
sql = ("SELECT * FROM RnaQuantification")
sql_args = ()
... | [
"def",
"searchRnaQuantificationsInDb",
"(",
"self",
",",
"rnaQuantificationId",
"=",
"\"\"",
")",
":",
"sql",
"=",
"(",
"\"SELECT * FROM RnaQuantification\"",
")",
"sql_args",
"=",
"(",
")",
"if",
"len",
"(",
"rnaQuantificationId",
")",
">",
"0",
":",
"sql",
"... | 39.588235 | 11.588235 |
def scales(key=None, scales={}):
"""Creates and switches between context scales.
If no key is provided, a new blank context is created.
If a key is provided for which a context already exists, the existing
context is set as the current context.
If a key is provided and no corresponding context ex... | [
"def",
"scales",
"(",
"key",
"=",
"None",
",",
"scales",
"=",
"{",
"}",
")",
":",
"old_ctxt",
"=",
"_context",
"[",
"'scales'",
"]",
"if",
"key",
"is",
"None",
":",
"# No key provided",
"_context",
"[",
"'scales'",
"]",
"=",
"{",
"_get_attribute_dimensio... | 35.884615 | 23.576923 |
def get(self,
hyp_lengths: Union[mx.nd.NDArray, int, float],
reference_lengths: Optional[Union[mx.nd.NDArray, int, float]]) -> Union[mx.nd.NDArray, float]:
"""
Calculate the length penalty for the given vector of lengths.
:param hyp_lengths: Hypotheses lengths.
:... | [
"def",
"get",
"(",
"self",
",",
"hyp_lengths",
":",
"Union",
"[",
"mx",
".",
"nd",
".",
"NDArray",
",",
"int",
",",
"float",
"]",
",",
"reference_lengths",
":",
"Optional",
"[",
"Union",
"[",
"mx",
".",
"nd",
".",
"NDArray",
",",
"int",
",",
"float... | 43.714286 | 24.285714 |
def articles(self):
''' Tries to scrape the correct articles for singular and plural from vandale.nl. '''
result = [None, None]
element = self._first('NN')
if element:
if re.search('(de|het/?de|het);', element, re.U):
result[0] = re.findall('(de|het/?de|het);', element, re.U)[0].split('/')
if re.sear... | [
"def",
"articles",
"(",
"self",
")",
":",
"result",
"=",
"[",
"None",
",",
"None",
"]",
"element",
"=",
"self",
".",
"_first",
"(",
"'NN'",
")",
"if",
"element",
":",
"if",
"re",
".",
"search",
"(",
"'(de|het/?de|het);'",
",",
"element",
",",
"re",
... | 32.6 | 21.4 |
def add_layer2image_int(grid2d, x_pos, y_pos, kernel):
"""
adds a kernel on the grid2d image at position x_pos, y_pos at integer positions of pixel
:param grid2d: 2d pixel grid (i.e. image)
:param x_pos: x-position center (pixel coordinate) of the layer to be added
:param y_pos: y-position center (p... | [
"def",
"add_layer2image_int",
"(",
"grid2d",
",",
"x_pos",
",",
"y_pos",
",",
"kernel",
")",
":",
"nx",
",",
"ny",
"=",
"np",
".",
"shape",
"(",
"kernel",
")",
"if",
"nx",
"%",
"2",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"kernel needs odd number... | 39.638889 | 18.972222 |
def languages(self, key, value):
"""Populate the ``languages`` key."""
languages = self.get('languages', [])
values = force_list(value.get('a'))
for value in values:
for language in RE_LANGUAGE.split(value):
try:
name = language.strip().capitalize()
l... | [
"def",
"languages",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"languages",
"=",
"self",
".",
"get",
"(",
"'languages'",
",",
"[",
"]",
")",
"values",
"=",
"force_list",
"(",
"value",
".",
"get",
"(",
"'a'",
")",
")",
"for",
"value",
"in",
... | 31.285714 | 17.071429 |
def recipients(preferences, message, valid_paths, config):
""" The main API function.
Accepts a fedmsg message as an argument.
Returns a dict mapping context names to lists of recipients.
"""
rule_cache = dict()
results = defaultdict(list)
notified = set()
for preference in preferenc... | [
"def",
"recipients",
"(",
"preferences",
",",
"message",
",",
"valid_paths",
",",
"config",
")",
":",
"rule_cache",
"=",
"dict",
"(",
")",
"results",
"=",
"defaultdict",
"(",
"list",
")",
"notified",
"=",
"set",
"(",
")",
"for",
"preference",
"in",
"pref... | 38 | 20.25 |
def pad_trunc(data, maxlen):
""" For a given dataset pad with zero vectors or truncate to maxlen """
new_data = []
# Create a vector of 0's the length of our word vectors
zero_vector = []
for _ in range(len(data[0][0])):
zero_vector.append(0.0)
for sample in data:
if len(sampl... | [
"def",
"pad_trunc",
"(",
"data",
",",
"maxlen",
")",
":",
"new_data",
"=",
"[",
"]",
"# Create a vector of 0's the length of our word vectors",
"zero_vector",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"data",
"[",
"0",
"]",
"[",
"0",
"]",
... | 28.909091 | 15.863636 |
def get_requires(self, ignored=tuple()):
""" a map of requirements to what requires it. ignored is an
optional list of globbed patterns indicating packages,
classes, etc that shouldn't be included in the provides map"""
if self._requires is None:
self._collect_requires_provi... | [
"def",
"get_requires",
"(",
"self",
",",
"ignored",
"=",
"tuple",
"(",
")",
")",
":",
"if",
"self",
".",
"_requires",
"is",
"None",
":",
"self",
".",
"_collect_requires_provides",
"(",
")",
"d",
"=",
"self",
".",
"_requires",
"if",
"ignored",
":",
"d",... | 36.923077 | 14.769231 |
def post_to_twitter(self, message=None):
"""Update twitter status, i.e., post a tweet"""
consumer = oauth2.Consumer(key=conf.TWITTER_CONSUMER_KEY,
secret=conf.TWITTER_CONSUMER_SECRET)
token = oauth2.Token(key=conf.TWITTER_ACCESS_TOKEN, secret=conf.TWITTER_ACCES... | [
"def",
"post_to_twitter",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"consumer",
"=",
"oauth2",
".",
"Consumer",
"(",
"key",
"=",
"conf",
".",
"TWITTER_CONSUMER_KEY",
",",
"secret",
"=",
"conf",
".",
"TWITTER_CONSUMER_SECRET",
")",
"token",
"=",
"... | 44.769231 | 26.115385 |
def view(self, request):
""" Debug Toolbar. """
auth = yield from self.authorize(request)
if not auth:
raise HTTPForbidden()
request_id = request.match_info.get('request_id')
state = self.history.get(request_id, None)
response = yield from self.app.ps.jinja2... | [
"def",
"view",
"(",
"self",
",",
"request",
")",
":",
"auth",
"=",
"yield",
"from",
"self",
".",
"authorize",
"(",
"request",
")",
"if",
"not",
"auth",
":",
"raise",
"HTTPForbidden",
"(",
")",
"request_id",
"=",
"request",
".",
"match_info",
".",
"get"... | 35.894737 | 15.368421 |
def job_data(job_id):
'''Get the raw data that the job returned. The mimetype
will be the value provided in the metdata for the key ``mimetype``.
**Results:**
:rtype: string
:statuscode 200: no error
:statuscode 403: not authorized to view the job's data
:statuscode 404: job id not found
... | [
"def",
"job_data",
"(",
"job_id",
")",
":",
"job_dict",
"=",
"db",
".",
"get_job",
"(",
"job_id",
")",
"if",
"not",
"job_dict",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"'job_id not found'",
"}",
")",
",",
"404",
",",
"headers",
... | 36.136364 | 21.681818 |
def signature(self):
"""Create a signature for this method, only in Python > 3.4"""
if not use_signature:
raise NotImplementedError("Python 3 only.")
if self.static:
parameters = \
(Parameter(name='cls',
kind=Parameter.POSITIONA... | [
"def",
"signature",
"(",
"self",
")",
":",
"if",
"not",
"use_signature",
":",
"raise",
"NotImplementedError",
"(",
"\"Python 3 only.\"",
")",
"if",
"self",
".",
"static",
":",
"parameters",
"=",
"(",
"Parameter",
"(",
"name",
"=",
"'cls'",
",",
"kind",
"="... | 35.290323 | 17.032258 |
def _get_cache(cache_file, source_file=None):
"""Get cached taxonomy using the cPickle module.
No check is done at that stage.
:param cache_file: full path to the file holding pickled data
:param source_file: if we discover the cache is obsolete, we
will build a new cache, therefore we need th... | [
"def",
"_get_cache",
"(",
"cache_file",
",",
"source_file",
"=",
"None",
")",
":",
"timer_start",
"=",
"time",
".",
"clock",
"(",
")",
"filestream",
"=",
"open",
"(",
"cache_file",
",",
"\"rb\"",
")",
"try",
":",
"cached_data",
"=",
"cPickle",
".",
"load... | 35.753846 | 18.138462 |
def _create_api(self):
"""Creates a new CrunchyrollAPI object, initiates it's session and
tries to authenticate it either by using saved credentials or the
user's username and password.
"""
if self.options.get("purge_credentials"):
self.cache.set("session_id", None, 0... | [
"def",
"_create_api",
"(",
"self",
")",
":",
"if",
"self",
".",
"options",
".",
"get",
"(",
"\"purge_credentials\"",
")",
":",
"self",
".",
"cache",
".",
"set",
"(",
"\"session_id\"",
",",
"None",
",",
"0",
")",
"self",
".",
"cache",
".",
"set",
"(",... | 45.613636 | 20.863636 |
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
self.DeserializeUnsigned(reader)
self.scripts = reader.ReadSerializableArray()
self.OnDeserialized() | [
"def",
"Deserialize",
"(",
"self",
",",
"reader",
")",
":",
"self",
".",
"DeserializeUnsigned",
"(",
"reader",
")",
"self",
".",
"scripts",
"=",
"reader",
".",
"ReadSerializableArray",
"(",
")",
"self",
".",
"OnDeserialized",
"(",
")"
] | 23.636364 | 13.636364 |
def hook_focus_events(self):
""" Install the hooks for focus events.
This method may be overridden by subclasses as needed.
"""
widget = self.widget
widget.focusInEvent = self.focusInEvent
widget.focusOutEvent = self.focusOutEvent | [
"def",
"hook_focus_events",
"(",
"self",
")",
":",
"widget",
"=",
"self",
".",
"widget",
"widget",
".",
"focusInEvent",
"=",
"self",
".",
"focusInEvent",
"widget",
".",
"focusOutEvent",
"=",
"self",
".",
"focusOutEvent"
] | 30.222222 | 15.777778 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.