text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def querymany(self, sql_query, columns, seq_of_parameters):
"""
Same as .query() but eventually call the .executemany() method
of the underlying DBAPI2.0 cursor instead of .execute()
"""
tmp_query = self.__preparequery(sql_query, columns)
if self.__methods[METHOD_MODULE]... | [
"def",
"querymany",
"(",
"self",
",",
"sql_query",
",",
"columns",
",",
"seq_of_parameters",
")",
":",
"tmp_query",
"=",
"self",
".",
"__preparequery",
"(",
"sql_query",
",",
"columns",
")",
"if",
"self",
".",
"__methods",
"[",
"METHOD_MODULE",
"]",
".",
"... | 43.176471 | 25.411765 |
def new(self, br, ino, sector_count, load_seg, media_name, system_type,
platform_id, bootable):
# type: (headervd.BootRecord, inode.Inode, int, int, str, int, int, bool) -> None
'''
A method to create a new El Torito Boot Catalog.
Parameters:
br - The boot record th... | [
"def",
"new",
"(",
"self",
",",
"br",
",",
"ino",
",",
"sector_count",
",",
"load_seg",
",",
"media_name",
",",
"system_type",
",",
"platform_id",
",",
"bootable",
")",
":",
"# type: (headervd.BootRecord, inode.Inode, int, int, str, int, int, bool) -> None",
"if",
"se... | 42.6875 | 25.8125 |
def get_path(self, repo):
""" Return the path for the repo """
if repo.endswith('.git'):
repo = repo.split('.git')[0]
org, name = repo.split('/')[-2:]
path = self.plugins_dir
path = join(path, org, name)
return path, org, name | [
"def",
"get_path",
"(",
"self",
",",
"repo",
")",
":",
"if",
"repo",
".",
"endswith",
"(",
"'.git'",
")",
":",
"repo",
"=",
"repo",
".",
"split",
"(",
"'.git'",
")",
"[",
"0",
"]",
"org",
",",
"name",
"=",
"repo",
".",
"split",
"(",
"'/'",
")",... | 34.875 | 5.625 |
def http_request(self, path="/", method="GET", host=None, port=None, json=False, data=None):
"""
perform a HTTP request
:param path: str, path within the request, e.g. "/api/version"
:param method: str, HTTP method
:param host: str, if None, set to 127.0.0.1
:param port:... | [
"def",
"http_request",
"(",
"self",
",",
"path",
"=",
"\"/\"",
",",
"method",
"=",
"\"GET\"",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"json",
"=",
"False",
",",
"data",
"=",
"None",
")",
":",
"host",
"=",
"host",
"or",
"'127.0.0.1'... | 37.5 | 19.5 |
def get_composition(self, composition_id):
"""Gets the ``Composition`` specified by its ``Id``.
arg: composition_id (osid.id.Id): ``Id`` of the
``Composiiton``
return: (osid.repository.Composition) - the composition
raise: NotFound - ``composition_id`` not found
... | [
"def",
"get_composition",
"(",
"self",
",",
"composition_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resource",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'repository'",
... | 51.565217 | 20.043478 |
def _get_method_full_name(func):
"""
Return fully qualified function name.
This method will attempt to find "full name" of the given function object. This full name is either of
the form "<class name>.<method name>" if the function is a class method, or "<module name>.<func name>"
if it's a regular... | [
"def",
"_get_method_full_name",
"(",
"func",
")",
":",
"# Python 3.3 already has this information available...",
"if",
"hasattr",
"(",
"func",
",",
"\"__qualname__\"",
")",
":",
"return",
"func",
".",
"__qualname__",
"module",
"=",
"inspect",
".",
"getmodule",
"(",
... | 40.75 | 20.178571 |
def _get_block_result(chars_a, chars_b):
"""Get the first block from two character lists and compare
If character list ``a`` begins with a digit, the :any:`_pop_digit`
function is called on both lists to get blocks of all consecutive
digits at the start of each list. If the length of the block
retu... | [
"def",
"_get_block_result",
"(",
"chars_a",
",",
"chars_b",
")",
":",
"logger",
".",
"debug",
"(",
"'_get_block_result(%s, %s)'",
",",
"chars_a",
",",
"chars_b",
")",
"first_is_digit",
"=",
"chars_a",
"[",
"0",
"]",
".",
"isdigit",
"(",
")",
"pop_func",
"=",... | 45.885714 | 20.228571 |
def amalgamate(colcount, snode, snptr, snpar, snpost, merge_function):
"""
Supernodal amalgamation.
colcount, snode, snptr, snpar, snpost = ...
amalgamate(colcount, snode, snptr, snpar, snpost, merge_function)
PURPOSE
Iterates over the clique tree in topological order and greedily
... | [
"def",
"amalgamate",
"(",
"colcount",
",",
"snode",
",",
"snptr",
",",
"snpar",
",",
"snpost",
",",
"merge_function",
")",
":",
"N",
"=",
"len",
"(",
"snpost",
")",
"ch",
"=",
"{",
"}",
"for",
"j",
"in",
"snpost",
":",
"if",
"snpar",
"[",
"j",
"]... | 28.987654 | 20.444444 |
def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool:
"""
Check if the given exception handler catches
the given error_type.
The *handler* parameter is a node, representing an ExceptHandler node.
The *error_type* can be an exception, such as AttributeError,
the name of an excep... | [
"def",
"error_of_type",
"(",
"handler",
":",
"astroid",
".",
"ExceptHandler",
",",
"error_type",
")",
"->",
"bool",
":",
"def",
"stringify_error",
"(",
"error",
")",
":",
"if",
"not",
"isinstance",
"(",
"error",
",",
"str",
")",
":",
"return",
"error",
"... | 35.826087 | 18.956522 |
def Brkic_2011_1(Re, eD):
r'''Calculates Darcy friction factor using the method in Brkic
(2011) [2]_ as shown in [1]_.
.. math::
f_d = [-2\log(10^{-0.4343\beta} + \frac{\epsilon}{3.71D})]^{-2}
.. math::
\beta = \ln \frac{Re}{1.816\ln\left(\frac{1.1Re}{\ln(1+1.1Re)}\right)}
Paramet... | [
"def",
"Brkic_2011_1",
"(",
"Re",
",",
"eD",
")",
":",
"beta",
"=",
"log",
"(",
"Re",
"/",
"(",
"1.816",
"*",
"log",
"(",
"1.1",
"*",
"Re",
"/",
"log",
"(",
"1",
"+",
"1.1",
"*",
"Re",
")",
")",
")",
")",
"return",
"(",
"-",
"2",
"*",
"lo... | 28.409091 | 25 |
def from_apps(cls, apps):
"Takes in an Apps and returns a VersionedProjectState matching it"
app_models = {}
for model in apps.get_models(include_swapped=True):
model_state = VersionedModelState.from_model(model)
app_models[(model_state.app_label, model_state.name.lower()... | [
"def",
"from_apps",
"(",
"cls",
",",
"apps",
")",
":",
"app_models",
"=",
"{",
"}",
"for",
"model",
"in",
"apps",
".",
"get_models",
"(",
"include_swapped",
"=",
"True",
")",
":",
"model_state",
"=",
"VersionedModelState",
".",
"from_model",
"(",
"model",
... | 51.571429 | 23.571429 |
def render(self, text, add_header=False):
"""Render the HTML.
Parameters
----------
add_header: boolean (default: False)
If True, add HTML5 header and footer.
Returns
-------
str
The rendered HTML.
"""
html = mark_text(te... | [
"def",
"render",
"(",
"self",
",",
"text",
",",
"add_header",
"=",
"False",
")",
":",
"html",
"=",
"mark_text",
"(",
"text",
",",
"self",
".",
"aesthetics",
",",
"self",
".",
"rules",
")",
"html",
"=",
"html",
".",
"replace",
"(",
"'\\n'",
",",
"'<... | 27.9 | 19.2 |
def defer(self, *args, **kwargs):
"""Call the function and immediately return an asynchronous object.
The calling code will need to check for the result at a later time using:
In Python 2/3 using ThreadPools - an AsyncResult
(https://docs.python.org/2/library/multiprocessing.html#m... | [
"def",
"defer",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"LOG",
".",
"debug",
"(",
"'%s on %s (awaitable %s async %s provider %s)'",
",",
"'deferring'",
",",
"self",
".",
"_func",
",",
"self",
".",
"_is_awaitable",
",",
"self",
"."... | 37.7 | 19.7 |
def forward_for_single_feature_map(self, anchors, objectness, box_regression):
"""
Arguments:
anchors: list[BoxList]
objectness: tensor of size N, A, H, W
box_regression: tensor of size N, A * 4, H, W
"""
device = objectness.device
N, A, H, W =... | [
"def",
"forward_for_single_feature_map",
"(",
"self",
",",
"anchors",
",",
"objectness",
",",
"box_regression",
")",
":",
"device",
"=",
"objectness",
".",
"device",
"N",
",",
"A",
",",
"H",
",",
"W",
"=",
"objectness",
".",
"shape",
"# put in the same format ... | 37.625 | 21.333333 |
def loads(xml, force_list=None):
"""Cria um dicionário com os dados do XML.
O dicionário terá como chave o nome do nó root e como valor o conteúdo do nó root.
Quando o conteúdo de um nó é uma lista de nós então o valor do nó será
um dicionário com uma chave para cada nó.
Entretanto, se existir nós,... | [
"def",
"loads",
"(",
"xml",
",",
"force_list",
"=",
"None",
")",
":",
"if",
"force_list",
"is",
"None",
":",
"force_list",
"=",
"[",
"]",
"try",
":",
"xml",
"=",
"remove_illegal_characters",
"(",
"xml",
")",
"doc",
"=",
"parseString",
"(",
"xml",
")",
... | 34.642857 | 26.457143 |
def iofunctions(self):
"""Input/output functions of the model class."""
lines = Lines()
for func in ('open_files', 'close_files', 'load_data', 'save_data'):
if ((func == 'load_data') and
(getattr(self.model.sequences, 'inputs', None) is None)):
con... | [
"def",
"iofunctions",
"(",
"self",
")",
":",
"lines",
"=",
"Lines",
"(",
")",
"for",
"func",
"in",
"(",
"'open_files'",
",",
"'close_files'",
",",
"'load_data'",
",",
"'save_data'",
")",
":",
"if",
"(",
"(",
"func",
"==",
"'load_data'",
")",
"and",
"("... | 47.516129 | 14.935484 |
def load_texture(self, file_path):
"""Generate our sprite's surface by loading the specified image from disk.
Note that this automatically centers the origin."""
self.image = pygame.image.load(file_path)
self.apply_texture(self.image) | [
"def",
"load_texture",
"(",
"self",
",",
"file_path",
")",
":",
"self",
".",
"image",
"=",
"pygame",
".",
"image",
".",
"load",
"(",
"file_path",
")",
"self",
".",
"apply_texture",
"(",
"self",
".",
"image",
")"
] | 52.6 | 3.4 |
def plotstuff(self, T=[0, 1000]):
"""
Create a scatter plot of the contents of the database,
with entries on the interval T.
Parameters
----------
T : list
Time interval.
Returns
-------
None
... | [
"def",
"plotstuff",
"(",
"self",
",",
"T",
"=",
"[",
"0",
",",
"1000",
"]",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"(",
"10",
",",
"10",
")",
")",
"ax",
"=",
"fig",
".",
"add_subplot",
"(",
"111",
")",
"neurons",
"="... | 25.184211 | 20.552632 |
def visit_For(self, node):
"""
OUT = (node,) + last body statements
RAISES = body's that are not break or continue
"""
currs = (node,)
break_currs = tuple()
raises = ()
# handle body
for n in node.body:
self.result.add_node(n)
... | [
"def",
"visit_For",
"(",
"self",
",",
"node",
")",
":",
"currs",
"=",
"(",
"node",
",",
")",
"break_currs",
"=",
"tuple",
"(",
")",
"raises",
"=",
"(",
")",
"# handle body",
"for",
"n",
"in",
"node",
".",
"body",
":",
"self",
".",
"result",
".",
... | 34.472222 | 10.194444 |
def status(self):
"""
In most cases, reading status will return the same value as `mode`. In
cases where there is an `auto` mode additional values may be returned,
such as `no-device` or `error`. See individual port driver documentation
for the full list of possible values.
... | [
"def",
"status",
"(",
"self",
")",
":",
"self",
".",
"_status",
",",
"value",
"=",
"self",
".",
"get_attr_string",
"(",
"self",
".",
"_status",
",",
"'status'",
")",
"return",
"value"
] | 46 | 22 |
def _callable_contents(obj):
"""Return the signature contents of a callable Python object.
"""
try:
# Test if obj is a method.
return _function_contents(obj.__func__)
except AttributeError:
try:
# Test if obj is a callable object.
return _function_content... | [
"def",
"_callable_contents",
"(",
"obj",
")",
":",
"try",
":",
"# Test if obj is a method.",
"return",
"_function_contents",
"(",
"obj",
".",
"__func__",
")",
"except",
"AttributeError",
":",
"try",
":",
"# Test if obj is a callable object.",
"return",
"_function_conten... | 30 | 15.6 |
def get_text_path(self):
"""
Returns the path of the directory containing text if they exist in this dataset.
"""
for res in self.dsDoc['dataResources']:
resPath = res['resPath']
resType = res['resType']
isCollection = res['isCollection']
i... | [
"def",
"get_text_path",
"(",
"self",
")",
":",
"for",
"res",
"in",
"self",
".",
"dsDoc",
"[",
"'dataResources'",
"]",
":",
"resPath",
"=",
"res",
"[",
"'resPath'",
"]",
"resType",
"=",
"res",
"[",
"'resType'",
"]",
"isCollection",
"=",
"res",
"[",
"'is... | 43.307692 | 17.615385 |
def selection_index_to_idx(self, key, selection_index):
'''return a mission idx from a selection_index'''
a = key.split(' ')
if a[0] != 'mission' or len(a) != 2:
print("Bad mission object %s" % key)
return None
midx = int(a[1])
if midx < 0 or midx >= len(s... | [
"def",
"selection_index_to_idx",
"(",
"self",
",",
"key",
",",
"selection_index",
")",
":",
"a",
"=",
"key",
".",
"split",
"(",
"' '",
")",
"if",
"a",
"[",
"0",
"]",
"!=",
"'mission'",
"or",
"len",
"(",
"a",
")",
"!=",
"2",
":",
"print",
"(",
"\"... | 40.125 | 13.625 |
def init_opdata(l, from_mod, version=None, is_pypy=False):
"""Sets up a number of the structures found in Python's
opcode.py. Python opcode.py routines assign attributes to modules.
In order to do this in a modular way here, the local dictionary
for the module is passed.
"""
if version:
... | [
"def",
"init_opdata",
"(",
"l",
",",
"from_mod",
",",
"version",
"=",
"None",
",",
"is_pypy",
"=",
"False",
")",
":",
"if",
"version",
":",
"l",
"[",
"'python_version'",
"]",
"=",
"version",
"l",
"[",
"'is_pypy'",
"]",
"=",
"is_pypy",
"l",
"[",
"'cmp... | 37.035714 | 15.464286 |
def to_name(self) -> str:
"""
Convert to ANSI color name
:return: ANSI color name
"""
return {
self.BLACK: 'black',
self.RED: 'red',
self.GREEN: 'green',
self.YELLOW: 'yellow',
self.BLUE: 'blue',
self.MAGENTA... | [
"def",
"to_name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"{",
"self",
".",
"BLACK",
":",
"'black'",
",",
"self",
".",
"RED",
":",
"'red'",
",",
"self",
".",
"GREEN",
":",
"'green'",
",",
"self",
".",
"YELLOW",
":",
"'yellow'",
",",
"self",
... | 26.866667 | 9.266667 |
def clear_all(self):
"""Delete all Mentions from given split the database."""
logger.info("Clearing ALL Mentions.")
self.session.query(Mention).delete(synchronize_session="fetch")
# With no Mentions, there should be no Candidates also
self.session.query(Candidate).delete(synchro... | [
"def",
"clear_all",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"\"Clearing ALL Mentions.\"",
")",
"self",
".",
"session",
".",
"query",
"(",
"Mention",
")",
".",
"delete",
"(",
"synchronize_session",
"=",
"\"fetch\"",
")",
"# With no Mentions, there shou... | 49.5 | 21.5 |
def init_ui(self):
"""Setup control widget UI."""
self.control_layout = QHBoxLayout()
self.setLayout(self.control_layout)
self.reset_button = QPushButton()
self.reset_button.setFixedSize(40, 40)
self.reset_button.setIcon(QtGui.QIcon(WIN_PATH))
self.game_timer = QL... | [
"def",
"init_ui",
"(",
"self",
")",
":",
"self",
".",
"control_layout",
"=",
"QHBoxLayout",
"(",
")",
"self",
".",
"setLayout",
"(",
"self",
".",
"control_layout",
")",
"self",
".",
"reset_button",
"=",
"QPushButton",
"(",
")",
"self",
".",
"reset_button",... | 43.941176 | 11.588235 |
def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
super(DescriptionEditorController... | [
"def",
"register_actions",
"(",
"self",
",",
"shortcut_manager",
")",
":",
"super",
"(",
"DescriptionEditorController",
",",
"self",
")",
".",
"register_actions",
"(",
"shortcut_manager",
")",
"shortcut_manager",
".",
"add_callback_for_action",
"(",
"\"abort\"",
",",
... | 53.25 | 24.625 |
def cluster_assignments(self):
"""
Return an array of cluster assignments corresponding to the most recent set of instances clustered.
:return: the cluster assignments
:rtype: ndarray
"""
array = javabridge.call(self.jobject, "getClusterAssignments", "()[D")
if a... | [
"def",
"cluster_assignments",
"(",
"self",
")",
":",
"array",
"=",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"getClusterAssignments\"",
",",
"\"()[D\"",
")",
"if",
"array",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"j... | 36.083333 | 21.916667 |
def eventFilter(self, watchedObject, event):
""" Calls commitAndClose when the tab and back-tab are pressed.
This is necessary because, normally the event filter of QStyledItemDelegate does this
for us. However, that event filter works on this object, not on the sub editor.
"""
... | [
"def",
"eventFilter",
"(",
"self",
",",
"watchedObject",
",",
"event",
")",
":",
"if",
"event",
".",
"type",
"(",
")",
"==",
"QtCore",
".",
"QEvent",
".",
"KeyPress",
":",
"key",
"=",
"event",
".",
"key",
"(",
")",
"if",
"key",
"in",
"(",
"Qt",
"... | 45.142857 | 19.571429 |
def run(self):
"""
Kill any open Redshift sessions for the given database.
"""
connection = self.output().connect()
# kill any sessions other than ours and
# internal Redshift sessions (rdsdb)
query = ("select pg_terminate_backend(process) "
"from... | [
"def",
"run",
"(",
"self",
")",
":",
"connection",
"=",
"self",
".",
"output",
"(",
")",
".",
"connect",
"(",
")",
"# kill any sessions other than ours and",
"# internal Redshift sessions (rdsdb)",
"query",
"=",
"(",
"\"select pg_terminate_backend(process) \"",
"\"from ... | 41.5 | 18.131579 |
def submit_job(manager, job_config):
""" Launch new job from specified config. May have been previously 'setup'
if 'setup_params' in job_config is empty.
"""
# job_config is raw dictionary from JSON (from MQ or HTTP endpoint).
job_id = job_config.get('job_id')
try:
command_line = job_con... | [
"def",
"submit_job",
"(",
"manager",
",",
"job_config",
")",
":",
"# job_config is raw dictionary from JSON (from MQ or HTTP endpoint).",
"job_id",
"=",
"job_config",
".",
"get",
"(",
"'job_id'",
")",
"try",
":",
"command_line",
"=",
"job_config",
".",
"get",
"(",
"... | 42.285714 | 18.020408 |
def delete_dataset(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes a dataset and all of its contents. Returns empty response in the
``response`` field when it co... | [
"def",
"delete_dataset",
"(",
"self",
",",
"name",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadat... | 39.423529 | 22.364706 |
def download(url, fname=None):
"""
Downloads a file.
Args:
url (str): The URL to download.
fname (Optional[str]): The filename to store the downloaded file in. If
`None`, take the filename from the URL. Defaults to `None`.
Returns:
The filename the URL was downloa... | [
"def",
"download",
"(",
"url",
",",
"fname",
"=",
"None",
")",
":",
"# Determine the filename",
"if",
"fname",
"is",
"None",
":",
"fname",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
"# Stream the URL as a file, copying to local disk",
"wi... | 28.121212 | 21.333333 |
def swipe_bottom(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.down(steps=steps) | [
"def",
"swipe_bottom",
"(",
"self",
",",
"steps",
"=",
"10",
",",
"*",
"args",
",",
"*",
"*",
"selectors",
")",
":",
"self",
".",
"device",
"(",
"*",
"*",
"selectors",
")",
".",
"swipe",
".",
"down",
"(",
"steps",
"=",
"steps",
")"
] | 34.142857 | 13.857143 |
def _dictlist_to_lists(dl, *keys):
''' convert a list of dictionaries to a dictionary of lists
>>> dl = [{'a': 'test', 'b': 3}, {'a': 'zaz', 'b': 444},
{'a': 'wow', 'b': 300}]
>>> _dictlist_to_lists(dl)
(['test', 'zaz', 'wow'], [3, 444, 300])
'''
lists = []
for k in keys:
... | [
"def",
"_dictlist_to_lists",
"(",
"dl",
",",
"*",
"keys",
")",
":",
"lists",
"=",
"[",
"]",
"for",
"k",
"in",
"keys",
":",
"lists",
".",
"append",
"(",
"[",
"]",
")",
"for",
"item",
"in",
"dl",
":",
"for",
"i",
",",
"key",
"in",
"enumerate",
"(... | 29 | 16.111111 |
def get_cloud_service(self, cloud_service_id):
'''
The Get Cloud Service operation gets all the resources (job collections)
in the cloud service.
cloud_service_id:
The cloud service id
'''
_validate_not_none('cloud_service_id', cloud_service_id)
path ... | [
"def",
"get_cloud_service",
"(",
"self",
",",
"cloud_service_id",
")",
":",
"_validate_not_none",
"(",
"'cloud_service_id'",
",",
"cloud_service_id",
")",
"path",
"=",
"self",
".",
"_get_cloud_services_path",
"(",
"cloud_service_id",
")",
"return",
"self",
".",
"_pe... | 37.454545 | 21.454545 |
def create_table(table, connection, schema=None):
"""Create a single table, primarily used din migrations"""
orig_schemas = {}
# These schema shenanigans are almost certainly wrong.
# But they are expedient. For Postgres, it puts the library
# tables in the Library schema. We n... | [
"def",
"create_table",
"(",
"table",
",",
"connection",
",",
"schema",
"=",
"None",
")",
":",
"orig_schemas",
"=",
"{",
"}",
"# These schema shenanigans are almost certainly wrong.",
"# But they are expedient. For Postgres, it puts the library",
"# tables in the Library schema. W... | 42.916667 | 24.333333 |
def list_results(self, number, username):
"""
[deprecated] 建議使用方法 `get_question_results()`
"""
# 取得新 API 的結果
data = self.get_question_results(number, username)
# 實作相容的結構
result = []
for number in data:
# 儲存題目資訊
result += [(number, d... | [
"def",
"list_results",
"(",
"self",
",",
"number",
",",
"username",
")",
":",
"# 取得新 API 的結果",
"data",
"=",
"self",
".",
"get_question_results",
"(",
"number",
",",
"username",
")",
"# 實作相容的結構",
"result",
"=",
"[",
"]",
"for",
"number",
"in",
"data",
":",
... | 27.538462 | 13.692308 |
def load(self, format=None, *, kwargs={}):
'''
deserialize object from the file.
auto detect format by file extension name if `format` is None.
for example, `.json` will detect as `json`.
* raise `FormatNotFoundError` on unknown format.
* raise `SerializeError` on any s... | [
"def",
"load",
"(",
"self",
",",
"format",
"=",
"None",
",",
"*",
",",
"kwargs",
"=",
"{",
"}",
")",
":",
"return",
"load",
"(",
"self",
",",
"format",
"=",
"format",
",",
"kwargs",
"=",
"kwargs",
")"
] | 36.181818 | 21.272727 |
def reasonable_desired_version(self, desired_version, allow_equal=False,
allow_patch_skip=False):
"""
Determine whether the desired version is a reasonable next version.
Parameters
----------
desired_version: str
the proposed next ve... | [
"def",
"reasonable_desired_version",
"(",
"self",
",",
"desired_version",
",",
"allow_equal",
"=",
"False",
",",
"allow_patch_skip",
"=",
"False",
")",
":",
"try",
":",
"desired_version",
"=",
"desired_version",
".",
"base_version",
"except",
":",
"pass",
"(",
"... | 33.425532 | 20.957447 |
def _serialize_input_list(input_value):
"""Recursively serialize task input list"""
input_list = []
for item in input_value:
if isinstance(item, list):
input_list.append(Task._serialize_input_list(item))
else:
if isinstance(item, File):
... | [
"def",
"_serialize_input_list",
"(",
"input_value",
")",
":",
"input_list",
"=",
"[",
"]",
"for",
"item",
"in",
"input_value",
":",
"if",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"input_list",
".",
"append",
"(",
"Task",
".",
"_serialize_input_list"... | 39.090909 | 10.272727 |
def modified_lines(self, r, file_name):
"""Returns the line numbers of a file which have been changed."""
cmd = self.file_diff_cmd(r, file_name)
diff = shell_out_ignore_exitcode(cmd, cwd=self.root)
return list(self.modified_lines_from_diff(diff)) | [
"def",
"modified_lines",
"(",
"self",
",",
"r",
",",
"file_name",
")",
":",
"cmd",
"=",
"self",
".",
"file_diff_cmd",
"(",
"r",
",",
"file_name",
")",
"diff",
"=",
"shell_out_ignore_exitcode",
"(",
"cmd",
",",
"cwd",
"=",
"self",
".",
"root",
")",
"ret... | 54.8 | 8.6 |
def skew_matrix(w):
'''Return the skew matrix of a direction w.'''
return np.array([[0, -w[2], w[1]],
[w[2], 0, -w[0]],
[-w[1], w[0], 0]]) | [
"def",
"skew_matrix",
"(",
"w",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"0",
",",
"-",
"w",
"[",
"2",
"]",
",",
"w",
"[",
"1",
"]",
"]",
",",
"[",
"w",
"[",
"2",
"]",
",",
"0",
",",
"-",
"w",
"[",
"0",
"]",
"]",
",",
... | 36.8 | 7.2 |
def bezout(a, b):
'''Compute the bezout algorithm of a and b, i.e. it returns u, v, p such as:
p = GCD(a,b)
a * u + b * v = p
Copied from http://www.labri.fr/perso/betrema/deug/poly/euclide.html.
'''
u = 1
v = 0
s = 0
t = 1
while b > 0:
q = a // b
... | [
"def",
"bezout",
"(",
"a",
",",
"b",
")",
":",
"u",
"=",
"1",
"v",
"=",
"0",
"s",
"=",
"0",
"t",
"=",
"1",
"while",
"b",
">",
"0",
":",
"q",
"=",
"a",
"//",
"b",
"r",
"=",
"a",
"%",
"b",
"a",
"=",
"b",
"b",
"=",
"r",
"tmp",
"=",
"... | 19.25 | 27.083333 |
def untar_file(filename, location):
"""Untar the file (tar file located at filename) to the destination location"""
if not os.path.exists(location):
os.makedirs(location)
if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'):
mode = 'r:gz'
elif filename.lower().endswit... | [
"def",
"untar_file",
"(",
"filename",
",",
"location",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"location",
")",
":",
"os",
".",
"makedirs",
"(",
"location",
")",
"if",
"filename",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
... | 39.156863 | 15.019608 |
def get_all_cpv_use(cp):
'''
.. versionadded:: 2015.8.0
Uses portage to determine final USE flags and settings for an emerge.
@type cp: string
@param cp: eg cat/pkg
@rtype: lists
@return use, use_expand_hidden, usemask, useforce
'''
cpv = _get_cpv(cp)
portage = _get_portage()
... | [
"def",
"get_all_cpv_use",
"(",
"cp",
")",
":",
"cpv",
"=",
"_get_cpv",
"(",
"cp",
")",
"portage",
"=",
"_get_portage",
"(",
")",
"use",
"=",
"None",
"_porttree",
"(",
")",
".",
"dbapi",
".",
"settings",
".",
"unlock",
"(",
")",
"try",
":",
"_porttree... | 33.103448 | 18.827586 |
def AddIndex(self, path_segment_index):
"""Adds a path segment index and sets its weight to 0.
Args:
path_segment_index: an integer containing the path segment index.
Raises:
ValueError: if the path segment weights already contains
the path segment index.
"""
if path_... | [
"def",
"AddIndex",
"(",
"self",
",",
"path_segment_index",
")",
":",
"if",
"path_segment_index",
"in",
"self",
".",
"_weight_per_index",
":",
"raise",
"ValueError",
"(",
"'Path segment index already set.'",
")",
"self",
".",
"_weight_per_index",
"[",
"path_segment_ind... | 32.642857 | 19.571429 |
def _work_path_to_rel_final_path(path, upload_path_mapping, upload_base_dir):
""" Check if `path` is a work-rooted path, and convert to a relative final-rooted path
"""
if not path or not isinstance(path, str):
return path
upload_path = None
# First, check in the mapping: if it's there is a... | [
"def",
"_work_path_to_rel_final_path",
"(",
"path",
",",
"upload_path_mapping",
",",
"upload_base_dir",
")",
":",
"if",
"not",
"path",
"or",
"not",
"isinstance",
"(",
"path",
",",
"str",
")",
":",
"return",
"path",
"upload_path",
"=",
"None",
"# First, check in ... | 39.785714 | 21.178571 |
def _default_bridge(self):
""" Get an instance of the ENBridge object using ctypes. """
objc = self.objc
ENBridge = objc.objc_getClass('ENBridge')
return objc.objc_msgSend(ENBridge, objc.sel_registerName('instance')) | [
"def",
"_default_bridge",
"(",
"self",
")",
":",
"objc",
"=",
"self",
".",
"objc",
"ENBridge",
"=",
"objc",
".",
"objc_getClass",
"(",
"'ENBridge'",
")",
"return",
"objc",
".",
"objc_msgSend",
"(",
"ENBridge",
",",
"objc",
".",
"sel_registerName",
"(",
"'i... | 48.8 | 15.2 |
def _try_switches(self, lines, index):
"""
For each switch in the Collector object, pass a list of string,
representing lines of text in a file, and an index to the current
line to try to flip the switch. A switch will only flip on if the line
passes its 'test_on' method, and wil... | [
"def",
"_try_switches",
"(",
"self",
",",
"lines",
",",
"index",
")",
":",
"for",
"s",
"in",
"self",
".",
"_switches",
":",
"s",
".",
"switch",
"(",
"lines",
",",
"index",
")"
] | 45.384615 | 18.923077 |
def write_object_to_file(self,
query_results,
filename,
fmt="csv",
coerce_to_timestamp=False,
record_time_added=False):
"""
Write query results to file.
... | [
"def",
"write_object_to_file",
"(",
"self",
",",
"query_results",
",",
"filename",
",",
"fmt",
"=",
"\"csv\"",
",",
"coerce_to_timestamp",
"=",
"False",
",",
"record_time_added",
"=",
"False",
")",
":",
"fmt",
"=",
"fmt",
".",
"lower",
"(",
")",
"if",
"fmt... | 49.231481 | 25.305556 |
def plot_monthly_ic_heatmap(mean_monthly_ic, ax=None):
"""
Plots a heatmap of the information coefficient or returns by month.
Parameters
----------
mean_monthly_ic : pd.DataFrame
The mean monthly IC for N periods forward.
Returns
-------
ax : matplotlib.Axes
The axes t... | [
"def",
"plot_monthly_ic_heatmap",
"(",
"mean_monthly_ic",
",",
"ax",
"=",
"None",
")",
":",
"mean_monthly_ic",
"=",
"mean_monthly_ic",
".",
"copy",
"(",
")",
"num_plots",
"=",
"len",
"(",
"mean_monthly_ic",
".",
"columns",
")",
"v_spaces",
"=",
"(",
"(",
"nu... | 24.857143 | 19.964286 |
def recv_file_from_remote(dev, src_filename, dst_file, filesize):
"""Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with send_file_to_host.
"""
bytes_remaining = filesize
if not HAS_BUFFER:
bytes_remaining *= 2 # hexlify makes each byte into 2
bu... | [
"def",
"recv_file_from_remote",
"(",
"dev",
",",
"src_filename",
",",
"dst_file",
",",
"filesize",
")",
":",
"bytes_remaining",
"=",
"filesize",
"if",
"not",
"HAS_BUFFER",
":",
"bytes_remaining",
"*=",
"2",
"# hexlify makes each byte into 2",
"buf_size",
"=",
"BUFFE... | 40.666667 | 12.037037 |
def inverse(x):
"""
Transform to Timedelta from numerical format
"""
try:
x = [pd.Timedelta(int(i)) for i in x]
except TypeError:
x = pd.Timedelta(int(x))
return x | [
"def",
"inverse",
"(",
"x",
")",
":",
"try",
":",
"x",
"=",
"[",
"pd",
".",
"Timedelta",
"(",
"int",
"(",
"i",
")",
")",
"for",
"i",
"in",
"x",
"]",
"except",
"TypeError",
":",
"x",
"=",
"pd",
".",
"Timedelta",
"(",
"int",
"(",
"x",
")",
")... | 25.222222 | 13 |
def get_file(self, commit, path, offset_bytes=0, size_bytes=0, extract_value=True):
"""
Returns an iterator of the contents contents of a file at a specific Commit.
Params:
* commit: A tuple, string, or Commit object representing the commit.
* path: The path of the file.
... | [
"def",
"get_file",
"(",
"self",
",",
"commit",
",",
"path",
",",
"offset_bytes",
"=",
"0",
",",
"size_bytes",
"=",
"0",
",",
"extract_value",
"=",
"True",
")",
":",
"req",
"=",
"proto",
".",
"GetFileRequest",
"(",
"file",
"=",
"proto",
".",
"File",
"... | 46.615385 | 22.153846 |
def create_comment(self, body):
"""Create a comment on this issue.
:param str body: (required), comment body
:returns: :class:`IssueComment <github3.issues.comment.IssueComment>`
"""
json = None
if body:
url = self._build_url('comments', base_url=self._api)
... | [
"def",
"create_comment",
"(",
"self",
",",
"body",
")",
":",
"json",
"=",
"None",
"if",
"body",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'comments'",
",",
"base_url",
"=",
"self",
".",
"_api",
")",
"json",
"=",
"self",
".",
"_json",
"(",
"... | 39 | 17.916667 |
def unique(s):
"""Return a list of the elements in s, but without duplicates.
For example, unique([1,2,3,1,2,3]) is some permutation of [1,2,3],
unique("abcabc") some permutation of ["a", "b", "c"], and
unique(([1, 2], [2, 3], [1, 2])) some permutation of
[[2, 3], [1, 2]].
For best speed, all ... | [
"def",
"unique",
"(",
"s",
")",
":",
"n",
"=",
"len",
"(",
"s",
")",
"if",
"n",
"==",
"0",
":",
"return",
"[",
"]",
"# Try using a dict first, as that's the fastest and will usually",
"# work. If it doesn't work, it will usually fail quickly, so it",
"# usually doesn't c... | 31.823529 | 23.014706 |
def from_path_by_size(dir_path, min_size=0, max_size=1 << 40):
"""Create a new FileCollection, and select all files that size in
a range::
dir_path = "your/path"
# select by file size larger than 100MB
fc = FileCollection.from_path_by_size(
... | [
"def",
"from_path_by_size",
"(",
"dir_path",
",",
"min_size",
"=",
"0",
",",
"max_size",
"=",
"1",
"<<",
"40",
")",
":",
"def",
"filter",
"(",
"winfile",
")",
":",
"if",
"(",
"winfile",
".",
"size_on_disk",
">=",
"min_size",
")",
"and",
"(",
"winfile",... | 37.925926 | 15.333333 |
def _schema_options(p):
""" Add options specific to schema subcommand. """
p.add_argument(
'resource', metavar='selector', nargs='?',
default=None).completer = _schema_tab_completer
p.add_argument(
'--summary', action="store_true",
help="Summarize counts of available resourc... | [
"def",
"_schema_options",
"(",
"p",
")",
":",
"p",
".",
"add_argument",
"(",
"'resource'",
",",
"metavar",
"=",
"'selector'",
",",
"nargs",
"=",
"'?'",
",",
"default",
"=",
"None",
")",
".",
"completer",
"=",
"_schema_tab_completer",
"p",
".",
"add_argumen... | 48.461538 | 22.615385 |
def parse(self, fail_callback=None):
""" Parse text fields and file fields for values and files """
# get text fields
for field in self.field_arguments:
self.values[field['name']] = self.__get_value(field['name'])
if self.values[field['name']] is None and field['requ... | [
"def",
"parse",
"(",
"self",
",",
"fail_callback",
"=",
"None",
")",
":",
"# get text fields\r",
"for",
"field",
"in",
"self",
".",
"field_arguments",
":",
"self",
".",
"values",
"[",
"field",
"[",
"'name'",
"]",
"]",
"=",
"self",
".",
"__get_value",
"("... | 49.5625 | 12.5 |
def _get_client(self):
"""
S3 Boto3 client
Returns:
boto3.session.Session.client: client
"""
client_kwargs = self._storage_parameters.get('client', dict())
# Handles unsecure mode
if self._unsecure:
client_kwargs = client_kwargs.copy()
... | [
"def",
"_get_client",
"(",
"self",
")",
":",
"client_kwargs",
"=",
"self",
".",
"_storage_parameters",
".",
"get",
"(",
"'client'",
",",
"dict",
"(",
")",
")",
"# Handles unsecure mode",
"if",
"self",
".",
"_unsecure",
":",
"client_kwargs",
"=",
"client_kwargs... | 27.6 | 18.4 |
def text(files):
'''Returns the whole transcribed text'''
sentences = convert_timestamps(files)
out = []
for s in sentences:
out.append(' '.join([w[0] for w in s['words']]))
return '\n'.join(out) | [
"def",
"text",
"(",
"files",
")",
":",
"sentences",
"=",
"convert_timestamps",
"(",
"files",
")",
"out",
"=",
"[",
"]",
"for",
"s",
"in",
"sentences",
":",
"out",
".",
"append",
"(",
"' '",
".",
"join",
"(",
"[",
"w",
"[",
"0",
"]",
"for",
"w",
... | 31 | 15 |
def find_range(self, interval):
"""wrapper for find"""
return self.find(self.tree, interval, self.start, self.end) | [
"def",
"find_range",
"(",
"self",
",",
"interval",
")",
":",
"return",
"self",
".",
"find",
"(",
"self",
".",
"tree",
",",
"interval",
",",
"self",
".",
"start",
",",
"self",
".",
"end",
")"
] | 42.666667 | 12 |
def ystep(self):
r"""Minimise Augmented Lagrangian with respect to
:math:`\mathbf{y}`.
"""
self.Y = np.asarray(sp.prox_l2(
self.AX + self.U, (self.lmbda/self.rho)*self.Wtvna,
axis=self.saxes), dtype=self.dtype) | [
"def",
"ystep",
"(",
"self",
")",
":",
"self",
".",
"Y",
"=",
"np",
".",
"asarray",
"(",
"sp",
".",
"prox_l2",
"(",
"self",
".",
"AX",
"+",
"self",
".",
"U",
",",
"(",
"self",
".",
"lmbda",
"/",
"self",
".",
"rho",
")",
"*",
"self",
".",
"W... | 32.5 | 13.5 |
def _find_files(dirpath: str) -> 'Iterable[str]':
"""Find files recursively.
Returns a generator that yields paths in no particular order.
"""
for dirpath, dirnames, filenames in os.walk(dirpath, topdown=True,
followlinks=True):
if os.path.basenam... | [
"def",
"_find_files",
"(",
"dirpath",
":",
"str",
")",
"->",
"'Iterable[str]'",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"dirpath",
",",
"topdown",
"=",
"True",
",",
"followlinks",
"=",
"True",
")",
":",
"... | 40.909091 | 15.545455 |
def install_twisted():
"""
If twisted is available, make `emit' return a DeferredList
This has been successfully tested with Twisted 14.0 and later.
"""
global emit, _call_partial
try:
from twisted.internet import defer
emit = _emit_twisted
_call_partial = defer.maybeDef... | [
"def",
"install_twisted",
"(",
")",
":",
"global",
"emit",
",",
"_call_partial",
"try",
":",
"from",
"twisted",
".",
"internet",
"import",
"defer",
"emit",
"=",
"_emit_twisted",
"_call_partial",
"=",
"defer",
".",
"maybeDeferred",
"return",
"True",
"except",
"... | 28.933333 | 16 |
def draw(self, **kwargs):
"""
Called from the fit method, this method creates the canvas and
draws the distribution plot on it.
Parameters
----------
kwargs: generic keyword arguments.
"""
# Prepare the data
bins = np.arange(self.N)
word... | [
"def",
"draw",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# Prepare the data",
"bins",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"N",
")",
"words",
"=",
"[",
"self",
".",
"features",
"[",
"i",
"]",
"for",
"i",
"in",
"self",
".",
"sorted_"... | 32.064516 | 18.064516 |
def create_all(self, progress_callback: Optional[callable] = None) -> Dict[str, object]:
"""
Creates all the models discovered from fixture files in :attr:`fixtures_dir`.
:param progress_callback: An optional function to track progress. It must take three
paramete... | [
"def",
"create_all",
"(",
"self",
",",
"progress_callback",
":",
"Optional",
"[",
"callable",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"object",
"]",
":",
"if",
"not",
"self",
".",
"_loaded",
":",
"self",
".",
"_load_data",
"(",
")",
"# ... | 46.953488 | 25.697674 |
def concat(cls, variables, dim='concat_dim', positions=None,
shortcut=False):
"""Specialized version of Variable.concat for IndexVariable objects.
This exists because we want to avoid converting Index objects to NumPy
arrays, if possible.
"""
if not isinstance(dim... | [
"def",
"concat",
"(",
"cls",
",",
"variables",
",",
"dim",
"=",
"'concat_dim'",
",",
"positions",
"=",
"None",
",",
"shortcut",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"dim",
",",
"str",
")",
":",
"dim",
",",
"=",
"dim",
".",
"dims"... | 34.324324 | 19 |
def make_xeditable(instance=None, extra_attrs=[], *args, **kwargs):
"""
Converts the contents of the column into an ``<a>`` tag with the required DOM attributes to
power the X-Editable UI.
The following keyword arguments are all optional, but may be provided when pre-calling the
helper, to customiz... | [
"def",
"make_xeditable",
"(",
"instance",
"=",
"None",
",",
"extra_attrs",
"=",
"[",
"]",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"instance",
"is",
"None",
":",
"# Preloading kwargs into the helper for deferred execution",
"helper",
"=",
"pa... | 45.315315 | 26.297297 |
def _exec_config_str(self, lhs, rhs):
"""execute self.config.<lhs> = <rhs>
* expands ~ with expanduser
* tries to assign with raw eval, otherwise assigns with just the string,
allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not*
equivalent are `--C.a... | [
"def",
"_exec_config_str",
"(",
"self",
",",
"lhs",
",",
"rhs",
")",
":",
"rhs",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"rhs",
")",
"try",
":",
"# Try to see if regular Python syntax will work. This",
"# won't handle strings as the quote marks are removed",
"... | 39.421053 | 16 |
def current_time(self) -> datetime:
"""Extract current time."""
_date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d")
_time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M")
return datetime.combine(_date.date(), _time.time()) | [
"def",
"current_time",
"(",
"self",
")",
"->",
"datetime",
":",
"_date",
"=",
"datetime",
".",
"strptime",
"(",
"self",
".",
"obj",
".",
"SBRes",
".",
"SBReq",
".",
"StartT",
".",
"get",
"(",
"\"date\"",
")",
",",
"\"%Y%m%d\"",
")",
"_time",
"=",
"da... | 59.2 | 22.2 |
def make_url(contents, domain=DEFAULT_DOMAIN, force_gist=False,
size_for_gist=MAX_URL_LEN):
"""
Returns the URL to open given the domain and contents.
If the file contents are large, an anonymous gist will be created.
Parameters
----------
contents
* string - assumed to be... | [
"def",
"make_url",
"(",
"contents",
",",
"domain",
"=",
"DEFAULT_DOMAIN",
",",
"force_gist",
"=",
"False",
",",
"size_for_gist",
"=",
"MAX_URL_LEN",
")",
":",
"contents",
"=",
"make_geojson",
"(",
"contents",
")",
"if",
"len",
"(",
"contents",
")",
"<=",
"... | 33.176471 | 19.588235 |
def get_choices(module_name):
"""
Retrieve members from ``module_name``'s ``__all__`` list.
:rtype: list
"""
try:
module = importlib.import_module(module_name)
if hasattr(module, '__all__'):
return module.__all__
else:
return [name for name, _ in insp... | [
"def",
"get_choices",
"(",
"module_name",
")",
":",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"module_name",
")",
"if",
"hasattr",
"(",
"module",
",",
"'__all__'",
")",
":",
"return",
"module",
".",
"__all__",
"else",
":",
"return"... | 28.533333 | 17.333333 |
def get_repo_data(saltenv='base'):
'''
Returns the existing package metadata db. Will create it, if it does not
exist, however will not refresh it.
Args:
saltenv (str): Salt environment. Default ``base``
Returns:
dict: A dict containing contents of metadata db.
CLI Example:
... | [
"def",
"get_repo_data",
"(",
"saltenv",
"=",
"'base'",
")",
":",
"# we only call refresh_db if it does not exist, as we want to return",
"# the existing data even if its old, other parts of the code call this,",
"# but they will call refresh if they need too.",
"repo_details",
"=",
"_get_r... | 32.446809 | 22.021277 |
def _error_repr(error):
"""A compact unique representation of an error."""
error_repr = repr(error)
if len(error_repr) > 200:
error_repr = hash(type(error))
return error_repr | [
"def",
"_error_repr",
"(",
"error",
")",
":",
"error_repr",
"=",
"repr",
"(",
"error",
")",
"if",
"len",
"(",
"error_repr",
")",
">",
"200",
":",
"error_repr",
"=",
"hash",
"(",
"type",
"(",
"error",
")",
")",
"return",
"error_repr"
] | 32.166667 | 10.166667 |
def _mitogen_reset(self, mode):
"""
Forget everything we know about the connected context. This function
cannot be called _reset() since that name is used as a public API by
Ansible 2.4 wait_for_connection plug-in.
:param str mode:
Name of ContextService method to us... | [
"def",
"_mitogen_reset",
"(",
"self",
",",
"mode",
")",
":",
"if",
"not",
"self",
".",
"context",
":",
"return",
"self",
".",
"chain",
".",
"reset",
"(",
")",
"self",
".",
"parent",
".",
"call_service",
"(",
"service_name",
"=",
"'ansible_mitogen.services.... | 31.208333 | 18.541667 |
def _next_pattern(self):
"""Parses the next pattern by matching each in turn."""
current_state = self.state_stack[-1]
position = self._position
for pattern in self.patterns:
if current_state not in pattern.states:
continue
m = pattern.regex.match(... | [
"def",
"_next_pattern",
"(",
"self",
")",
":",
"current_state",
"=",
"self",
".",
"state_stack",
"[",
"-",
"1",
"]",
"position",
"=",
"self",
".",
"_position",
"for",
"pattern",
"in",
"self",
".",
"patterns",
":",
"if",
"current_state",
"not",
"in",
"pat... | 32.868421 | 17.789474 |
def notebook_system_output():
"""Get a context manager that attempts to use `wurlitzer
<https://github.com/minrk/wurlitzer>`__ to capture system-level
stdout/stderr within a Jupyter Notebook shell, without affecting normal
operation when run as a Python script. For example:
>>> sys_pipes = sporco.u... | [
"def",
"notebook_system_output",
"(",
")",
":",
"from",
"contextlib",
"import",
"contextmanager",
"@",
"contextmanager",
"def",
"null_context_manager",
"(",
")",
":",
"yield",
"if",
"in_notebook",
"(",
")",
":",
"try",
":",
"from",
"wurlitzer",
"import",
"sys_pi... | 28 | 20.46875 |
def output_after_run(self, run):
"""
The method output_after_run() prints filename, result, time and status
of a run to terminal and stores all data in XML
"""
# format times, type is changed from float to string!
cputime_str = util.format_number(run.cputime, TIME_PRECIS... | [
"def",
"output_after_run",
"(",
"self",
",",
"run",
")",
":",
"# format times, type is changed from float to string!",
"cputime_str",
"=",
"util",
".",
"format_number",
"(",
"run",
".",
"cputime",
",",
"TIME_PRECISION",
")",
"walltime_str",
"=",
"util",
".",
"format... | 44.119403 | 26.268657 |
def variant_support(variants, allele_support_df, ignore_missing=False):
'''
Collect the read evidence support for the given variants.
Parameters
----------
variants : iterable of varcode.Variant
allele_support_df : dataframe
Allele support dataframe, as output by the varlens-allele-su... | [
"def",
"variant_support",
"(",
"variants",
",",
"allele_support_df",
",",
"ignore_missing",
"=",
"False",
")",
":",
"missing",
"=",
"[",
"c",
"for",
"c",
"in",
"EXPECTED_COLUMNS",
"if",
"c",
"not",
"in",
"allele_support_df",
".",
"columns",
"]",
"if",
"missi... | 35.14433 | 22.587629 |
def get_template(template_file='', **kwargs):
"""Get the Jinja2 template and renders with dict _kwargs_.
Args:
template_file (str): name of the template file
kwargs: Keywords to use for rendering the Jinja2 template.
Returns:
String of rendered JSON template.
"""
template ... | [
"def",
"get_template",
"(",
"template_file",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"template",
"=",
"get_template_object",
"(",
"template_file",
")",
"LOG",
".",
"info",
"(",
"'Rendering template %s'",
",",
"template",
".",
"filename",
")",
"for",
"k... | 28.47619 | 19.285714 |
def commutes(
m1: np.ndarray,
m2: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if two matrices approximately commute.
Two matrices A and B commute if they are square and have the same size and
AB = BA.
Args:
m1: One of th... | [
"def",
"commutes",
"(",
"m1",
":",
"np",
".",
"ndarray",
",",
"m2",
":",
"np",
".",
"ndarray",
",",
"*",
",",
"rtol",
":",
"float",
"=",
"1e-5",
",",
"atol",
":",
"float",
"=",
"1e-8",
")",
"->",
"bool",
":",
"return",
"(",
"m1",
".",
"shape",
... | 31.458333 | 21 |
def create_new_csv(samples, args):
"""create csv file that can be use with bcbio -w template"""
out_fn = os.path.splitext(args.csv)[0] + "-merged.csv"
logger.info("Preparing new csv: %s" % out_fn)
with file_transaction(out_fn) as tx_out:
with open(tx_out, 'w') as handle:
handle.write... | [
"def",
"create_new_csv",
"(",
"samples",
",",
"args",
")",
":",
"out_fn",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"args",
".",
"csv",
")",
"[",
"0",
"]",
"+",
"\"-merged.csv\"",
"logger",
".",
"info",
"(",
"\"Preparing new csv: %s\"",
"%",
"out_fn"... | 56.3 | 17.3 |
def store_hash_configuration(self, lshash):
"""
Stores hash configuration
"""
self.redis_object.set(lshash.hash_name+'_conf', pickle.dumps(lshash.get_config())) | [
"def",
"store_hash_configuration",
"(",
"self",
",",
"lshash",
")",
":",
"self",
".",
"redis_object",
".",
"set",
"(",
"lshash",
".",
"hash_name",
"+",
"'_conf'",
",",
"pickle",
".",
"dumps",
"(",
"lshash",
".",
"get_config",
"(",
")",
")",
")"
] | 37.6 | 12 |
def args(self) -> str:
"""Provides arguments for the command."""
return '{}{}{}{}{}{}{}{}{}{}{}'.format(
to_ascii_hex(self._index, 2),
to_ascii_hex(self._group_number, 2),
to_ascii_hex(self._unit_number, 2),
to_ascii_hex(int(self._enable_status), 4),
... | [
"def",
"args",
"(",
"self",
")",
"->",
"str",
":",
"return",
"'{}{}{}{}{}{}{}{}{}{}{}'",
".",
"format",
"(",
"to_ascii_hex",
"(",
"self",
".",
"_index",
",",
"2",
")",
",",
"to_ascii_hex",
"(",
"self",
".",
"_group_number",
",",
"2",
")",
",",
"to_ascii_... | 56.714286 | 18.642857 |
def clinvar_submission_lines(submission_objs, submission_header):
"""Create the lines to include in a Clinvar submission csv file from a list of submission objects and a custom document header
Args:
submission_objs(list): a list of objects (variants or casedata) to include in a csv file
... | [
"def",
"clinvar_submission_lines",
"(",
"submission_objs",
",",
"submission_header",
")",
":",
"submission_lines",
"=",
"[",
"]",
"for",
"submission_obj",
"in",
"submission_objs",
":",
"# Loop over the submission objects. Each of these is a line",
"csv_line",
"=",
"[",
"]",... | 54.5 | 35.636364 |
def main(argv: Optional[Sequence[str]] = None) -> None:
"""Parse arguments and process the exam assignment."""
parser = ArgumentParser(description="Convert Jupyter Notebook exams to PDFs")
parser.add_argument(
"--exam",
type=int,
required=True,
help="Exam number to convert",
... | [
"def",
"main",
"(",
"argv",
":",
"Optional",
"[",
"Sequence",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"None",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Convert Jupyter Notebook exams to PDFs\"",
")",
"parser",
".",
"add_argument",... | 35.388889 | 21.166667 |
def create_waf(self, name, waf_type):
"""
Creates a WAF with the given type.
:param name: Name of the WAF.
:param waf_type: WAF type. ('mod_security', 'Snort', 'Imperva SecureSphere', 'F5 BigIP ASM', 'DenyAll rWeb')
"""
params = {
'name': name,
'ty... | [
"def",
"create_waf",
"(",
"self",
",",
"name",
",",
"waf_type",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
",",
"'type'",
":",
"waf_type",
"}",
"return",
"self",
".",
"_request",
"(",
"'POST'",
",",
"'rest/wafs/new'",
",",
"params",
")"
] | 35.909091 | 16.818182 |
def hms(self, msg, tic=None, prt=sys.stdout):
"""Print elapsed time and message."""
if tic is None:
tic = self.tic
now = timeit.default_timer()
hms = str(datetime.timedelta(seconds=(now-tic)))
prt.write('{HMS}: {MSG}\n'.format(HMS=hms, MSG=msg))
return now | [
"def",
"hms",
"(",
"self",
",",
"msg",
",",
"tic",
"=",
"None",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"tic",
"is",
"None",
":",
"tic",
"=",
"self",
".",
"tic",
"now",
"=",
"timeit",
".",
"default_timer",
"(",
")",
"hms",
"=",
... | 38.625 | 12.25 |
def tree_token_generator(el, indentation_level=0):
"""
Internal generator that yields tokens for the given HTML element as
follows:
- A tuple (LXML element, BEGIN, indentation_level)
- Text right after the start of the tag, or None.
- Recursively calls the token generator for all child objects
... | [
"def",
"tree_token_generator",
"(",
"el",
",",
"indentation_level",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"el",
".",
"tag",
",",
"string_class",
")",
":",
"return",
"tag_name",
"=",
"el",
".",
"tag",
".",
"lower",
"(",
")",
"is_indentation"... | 24.944444 | 21.833333 |
def south_field_triple(self):
"Returns a suitable description of this field for South."
from south.modelsinspector import introspector
field_class = "django.db.models.fields.CharField"
args, kwargs = introspector(self)
return (field_class, args, kwargs) | [
"def",
"south_field_triple",
"(",
"self",
")",
":",
"from",
"south",
".",
"modelsinspector",
"import",
"introspector",
"field_class",
"=",
"\"django.db.models.fields.CharField\"",
"args",
",",
"kwargs",
"=",
"introspector",
"(",
"self",
")",
"return",
"(",
"field_cl... | 48 | 11.666667 |
def allByAge(self, cascadeFetch=False):
'''
allByAge - Get the underlying objects which match the filter criteria, ordered oldest -> newest
If you are doing a queue or just need the head/tail, consider .first() and .last() instead.
@param cascadeFetch <bool> Default False, If True, all Foreign objects ass... | [
"def",
"allByAge",
"(",
"self",
",",
"cascadeFetch",
"=",
"False",
")",
":",
"matchedKeys",
"=",
"self",
".",
"getPrimaryKeys",
"(",
"sortByAge",
"=",
"True",
")",
"if",
"matchedKeys",
":",
"return",
"self",
".",
"getMultiple",
"(",
"matchedKeys",
",",
"ca... | 43.5625 | 35.3125 |
def getPrinted(self):
""" returns "0", "1" or "2" to indicate Printed state.
0 -> Never printed.
1 -> Printed after last publish
2 -> Printed but republished afterwards.
"""
workflow = getToolByName(self, 'portal_workflow')
review_state = workflow.getI... | [
"def",
"getPrinted",
"(",
"self",
")",
":",
"workflow",
"=",
"getToolByName",
"(",
"self",
",",
"'portal_workflow'",
")",
"review_state",
"=",
"workflow",
".",
"getInfoFor",
"(",
"self",
",",
"'review_state'",
",",
"''",
")",
"if",
"review_state",
"not",
"in... | 37.954545 | 12.727273 |
def do_build(self, argv):
"""\
build [TARGETS] Build the specified TARGETS and their
dependencies. 'b' is a synonym.
"""
import SCons.Node
import SCons.SConsign
import SCons.Script.Main
options = copy.deepcopy(self.options... | [
"def",
"do_build",
"(",
"self",
",",
"argv",
")",
":",
"import",
"SCons",
".",
"Node",
"import",
"SCons",
".",
"SConsign",
"import",
"SCons",
".",
"Script",
".",
"Main",
"options",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"options",
")",
"option... | 39.927928 | 22.333333 |
def _define_jco_args(cmd_parser):
"""
Define job configuration arguments.
Returns groups defined, currently one.
"""
jo_group = cmd_parser.add_argument_group('Job options', 'Job configuration options')
jo_group.add_argument('--job-name', help='Job name')
jo_group.add_argument('--preload', a... | [
"def",
"_define_jco_args",
"(",
"cmd_parser",
")",
":",
"jo_group",
"=",
"cmd_parser",
".",
"add_argument_group",
"(",
"'Job options'",
",",
"'Job configuration options'",
")",
"jo_group",
".",
"add_argument",
"(",
"'--job-name'",
",",
"help",
"=",
"'Job name'",
")"... | 53.625 | 41.25 |
def build_dependencies(self):
"""
Build the dependencies for this module.
Parse the code with ast, find all the import statements, convert
them into Dependency objects.
"""
highest = self.dsm or self.root
if self is highest:
highest = LeafNode()
... | [
"def",
"build_dependencies",
"(",
"self",
")",
":",
"highest",
"=",
"self",
".",
"dsm",
"or",
"self",
".",
"root",
"if",
"self",
"is",
"highest",
":",
"highest",
"=",
"LeafNode",
"(",
")",
"for",
"_import",
"in",
"self",
".",
"parse_code",
"(",
")",
... | 37.555556 | 11.333333 |
def get_fixed_argv(self): # pragma: no cover
"""Get proper arguments for re-running the command.
This is primarily for fixing some issues under Windows.
First, there was a bug in Windows when running an executable
located at a path with a space in it. This has become a
non-iss... | [
"def",
"get_fixed_argv",
"(",
"self",
")",
":",
"# pragma: no cover",
"argv",
"=",
"sys",
".",
"argv",
"[",
":",
"]",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"and",
"argv",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.py'",
")",
":",
"argv",
".",
... | 44.142857 | 23.190476 |
def copy_package(owner, repo, identifier, destination):
"""Copy a package to another repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_copy_with_http_info(
owner=owner,
repo=repo,
identifier=identifier... | [
"def",
"copy_package",
"(",
"owner",
",",
"repo",
",",
"identifier",
",",
"destination",
")",
":",
"client",
"=",
"get_packages_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
"client",
".",
"packa... | 32.285714 | 15.642857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.