text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def with_aad_user_password_authentication(cls, connection_string, user_id, password, authority_id="common"):
"""Creates a KustoConnection string builder that will authenticate with AAD user name and
password.
:param str connection_string: Kusto connection string should by of the format: https... | [
"def",
"with_aad_user_password_authentication",
"(",
"cls",
",",
"connection_string",
",",
"user_id",
",",
"password",
",",
"authority_id",
"=",
"\"common\"",
")",
":",
"_assert_value_is_valid",
"(",
"user_id",
")",
"_assert_value_is_valid",
"(",
"password",
")",
"kcs... | 53.823529 | 21.941176 |
def predict_y(self, model, pos):
"""return the predict y of 'model' when epoch = pos
Parameters
----------
model: string
name of the curve function model
pos: int
the epoch number of the position you want to predict
Returns
------... | [
"def",
"predict_y",
"(",
"self",
",",
"model",
",",
"pos",
")",
":",
"if",
"model_para_num",
"[",
"model",
"]",
"==",
"2",
":",
"y",
"=",
"all_models",
"[",
"model",
"]",
"(",
"pos",
",",
"model_para",
"[",
"model",
"]",
"[",
"0",
"]",
",",
"mode... | 37.136364 | 22.409091 |
def ipv6_ipv6route_route_next_ipv6_hop_next_hop(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ipv6 = ET.SubElement(config, "ipv6", xmlns="urn:brocade.com:mgmt:brocade-common-def")
ipv6route = ET.SubElement(ipv6, "ipv6route", xmlns="urn:brocade.com:mgmt... | [
"def",
"ipv6_ipv6route_route_next_ipv6_hop_next_hop",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"ipv6",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"ipv6\"",
",",
"xmlns",
"=",
"\"u... | 47.1875 | 16.125 |
def genus_specific(self):
"""
For genus-specific targets, MLST and serotyping, determine if the closest refseq genus is known - i.e. if 16S
analyses have been performed. Perform the analyses if required
"""
# Initialise a variable to store whether the necessary analyses have alre... | [
"def",
"genus_specific",
"(",
"self",
")",
":",
"# Initialise a variable to store whether the necessary analyses have already been performed",
"closestrefseqgenus",
"=",
"False",
"for",
"sample",
"in",
"self",
".",
"runmetadata",
".",
"samples",
":",
"if",
"sample",
".",
... | 46.684211 | 19 |
def _unbind(cls, boundname):
"""
Unbinds a bound form to a WFN.
:param string boundname: CPE name
:returns: WFN object associated with boundname.
:rtype: CPE2_3_WFN
"""
try:
fs = CPE2_3_FS(boundname)
except:
# CPE name is not form... | [
"def",
"_unbind",
"(",
"cls",
",",
"boundname",
")",
":",
"try",
":",
"fs",
"=",
"CPE2_3_FS",
"(",
"boundname",
")",
"except",
":",
"# CPE name is not formatted string",
"try",
":",
"uri",
"=",
"CPE2_3_URI",
"(",
"boundname",
")",
"except",
":",
"# CPE name ... | 27.545455 | 13.727273 |
async def get_sender(self):
"""
Returns `sender`, but will make an API call to find the
sender unless it's already cached.
"""
# ``sender.min`` is present both in :tl:`User` and :tl:`Channel`.
# It's a flag that will be set if only minimal information is
# availab... | [
"async",
"def",
"get_sender",
"(",
"self",
")",
":",
"# ``sender.min`` is present both in :tl:`User` and :tl:`Channel`.",
"# It's a flag that will be set if only minimal information is",
"# available (such as display name, but username may be missing),",
"# in which case we want to force fetch t... | 47.157895 | 17.473684 |
def record(self, record=True, tag=None):
"""Enable/disable recording.
Return a coroutine.
"""
path = '/startvideo?force=1' if record else '/stopvideo?force=1'
if record and tag is not None:
path = '/startvideo?force=1&tag={}'.format(URL(tag).raw_path)
return... | [
"def",
"record",
"(",
"self",
",",
"record",
"=",
"True",
",",
"tag",
"=",
"None",
")",
":",
"path",
"=",
"'/startvideo?force=1'",
"if",
"record",
"else",
"'/stopvideo?force=1'",
"if",
"record",
"and",
"tag",
"is",
"not",
"None",
":",
"path",
"=",
"'/sta... | 33.1 | 16.6 |
def get(self, sid):
"""
Constructs a AvailableAddOnExtensionContext
:param sid: The unique Extension Sid
:returns: twilio.rest.preview.marketplace.available_add_on.available_add_on_extension.AvailableAddOnExtensionContext
:rtype: twilio.rest.preview.marketplace.available_add_on... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"AvailableAddOnExtensionContext",
"(",
"self",
".",
"_version",
",",
"available_add_on_sid",
"=",
"self",
".",
"_solution",
"[",
"'available_add_on_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 39.642857 | 27.5 |
def cursor_moved(self, filename0, position0, filename1, position1):
"""Cursor was just moved: 'go to'"""
if position0 is not None:
self.add_cursor_position_to_history(filename0, position0)
self.add_cursor_position_to_history(filename1, position1) | [
"def",
"cursor_moved",
"(",
"self",
",",
"filename0",
",",
"position0",
",",
"filename1",
",",
"position1",
")",
":",
"if",
"position0",
"is",
"not",
"None",
":",
"self",
".",
"add_cursor_position_to_history",
"(",
"filename0",
",",
"position0",
")",
"self",
... | 56.4 | 17.8 |
def Barati_high(Re):
r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_.
.. math::
C_D = 8\times 10^{-6}\left[(Re/6530)^2 + \tanh(Re) - 8\ln(Re)/\ln(10)\right]
- 0.4119\exp(-2.08\times10^{43}/[Re + Re^2]^4)
-2.1344\exp(-\{[\ln(Re^2 + 10.7563)/\ln(10)]^2 + 9.... | [
"def",
"Barati_high",
"(",
"Re",
")",
":",
"Cd",
"=",
"(",
"8E-6",
"*",
"(",
"(",
"Re",
"/",
"6530.",
")",
"**",
"2",
"+",
"tanh",
"(",
"Re",
")",
"-",
"8",
"*",
"log",
"(",
"Re",
")",
"/",
"log",
"(",
"10.",
")",
")",
"-",
"0.4119",
"*",... | 32.183673 | 26.346939 |
def experiments_predictions_update_state_active(self, experiment_id, run_id):
"""Update state of given prediction to active.
Parameters
----------
experiment_id : string
Unique experiment identifier
run_id : string
Unique model run identifier
Ret... | [
"def",
"experiments_predictions_update_state_active",
"(",
"self",
",",
"experiment_id",
",",
"run_id",
")",
":",
"# Get prediction to ensure that it exists",
"model_run",
"=",
"self",
".",
"experiments_predictions_get",
"(",
"experiment_id",
",",
"run_id",
")",
"if",
"mo... | 31.458333 | 18 |
def get_db_version(session):
"""
:param session: actually it is a sqlalchemy session
:return: version number
"""
value = session.query(ProgramInformation.value).filter(ProgramInformation.name == "db_version").scalar()
return int(value) | [
"def",
"get_db_version",
"(",
"session",
")",
":",
"value",
"=",
"session",
".",
"query",
"(",
"ProgramInformation",
".",
"value",
")",
".",
"filter",
"(",
"ProgramInformation",
".",
"name",
"==",
"\"db_version\"",
")",
".",
"scalar",
"(",
")",
"return",
"... | 36.142857 | 18.142857 |
def search(self, conn, filters, order_by, offset=None, count=None, timeout=None):
'''
Search for model ids that match the provided filters.
Arguments:
* *filters* - A list of filters that apply to the search of one of
the following two forms:
1. ``'co... | [
"def",
"search",
"(",
"self",
",",
"conn",
",",
"filters",
",",
"order_by",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"# prepare the filters",
"pipe",
",",
"intersect",
",",
"temp_id",
"=",
"self",
".... | 42.710145 | 28.043478 |
def get_parameters_by_path(self, path, with_decryption, recursive, filters=None):
"""Implement the get-parameters-by-path-API in the backend."""
result = []
# path could be with or without a trailing /. we handle this
# difference here.
path = path.rstrip('/') + '/'
for p... | [
"def",
"get_parameters_by_path",
"(",
"self",
",",
"path",
",",
"with_decryption",
",",
"recursive",
",",
"filters",
"=",
"None",
")",
":",
"result",
"=",
"[",
"]",
"# path could be with or without a trailing /. we handle this",
"# difference here.",
"path",
"=",
"pat... | 42.1875 | 18.6875 |
def ReadHuntCounters(self, hunt_id):
"""Reads hunt counters."""
num_clients = self.CountHuntFlows(hunt_id)
num_successful_clients = self.CountHuntFlows(
hunt_id, filter_condition=db.HuntFlowsCondition.SUCCEEDED_FLOWS_ONLY)
num_failed_clients = self.CountHuntFlows(
hunt_id, filter_conditi... | [
"def",
"ReadHuntCounters",
"(",
"self",
",",
"hunt_id",
")",
":",
"num_clients",
"=",
"self",
".",
"CountHuntFlows",
"(",
"hunt_id",
")",
"num_successful_clients",
"=",
"self",
".",
"CountHuntFlows",
"(",
"hunt_id",
",",
"filter_condition",
"=",
"db",
".",
"Hu... | 43.516129 | 14.612903 |
def guess_pygments_highlighter(filename):
"""Factory to generate syntax highlighter for the given filename.
If a syntax highlighter is not available for a particular file, this
function will attempt to generate one based on the lexers in Pygments. If
Pygments is not available or does not have an ... | [
"def",
"guess_pygments_highlighter",
"(",
"filename",
")",
":",
"try",
":",
"from",
"pygments",
".",
"lexers",
"import",
"get_lexer_for_filename",
",",
"get_lexer_by_name",
"except",
"Exception",
":",
"return",
"TextSH",
"root",
",",
"ext",
"=",
"os",
".",
"path... | 35.555556 | 19.62963 |
def create_certificate(
path=None, text=False, overwrite=True, ca_server=None, **kwargs):
'''
Create an X509 certificate.
path:
Path to write the certificate to.
text:
If ``True``, return the PEM text without writing to a file.
Default ``False``.
overwrite:
... | [
"def",
"create_certificate",
"(",
"path",
"=",
"None",
",",
"text",
"=",
"False",
",",
"overwrite",
"=",
"True",
",",
"ca_server",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"path",
"and",
"not",
"text",
"and",
"(",
"'testrun'",
"no... | 35.471698 | 23.530398 |
def shutdown_host(kwargs=None, call=None):
'''
Shut down the specified host system in this VMware environment
.. note::
If the host system is not in maintenance mode, it will not be shut down. If you
want to shut down the host system regardless of whether it is in maintenance mode,
... | [
"def",
"shutdown_host",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The shutdown_host function must be called with '",
"'-f or --function.'",
")",
"host_name",
"=",
"kw... | 32.823529 | 26.147059 |
def overrideable_partial(func, *args, **default_kwargs):
""" like partial, but given kwargs can be overrideden at calltime """
import functools
@functools.wraps(func)
def partial_wrapper(*given_args, **given_kwargs):
kwargs = default_kwargs.copy()
kwargs.update(given_kwargs)
retu... | [
"def",
"overrideable_partial",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"default_kwargs",
")",
":",
"import",
"functools",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"partial_wrapper",
"(",
"*",
"given_args",
",",
"*",
"*",
"given_kwargs... | 42 | 10.555556 |
def losses_by_period(losses, return_periods, num_events=None, eff_time=None):
"""
:param losses: array of simulated losses
:param return_periods: return periods of interest
:param num_events: the number of events (>= to the number of losses)
:param eff_time: investigation_time * ses_per_logic_tree_p... | [
"def",
"losses_by_period",
"(",
"losses",
",",
"return_periods",
",",
"num_events",
"=",
"None",
",",
"eff_time",
"=",
"None",
")",
":",
"if",
"len",
"(",
"losses",
")",
"==",
"0",
":",
"# zero-curve",
"return",
"numpy",
".",
"zeros",
"(",
"len",
"(",
... | 45.4 | 19.3 |
def mouse_press_event(self, x, y, button):
"""Reports left and right mouse button presses + position"""
if button == 1:
print("Left mouse button pressed @", x, y)
if button == 2:
print("Right mouse button pressed @", x, y) | [
"def",
"mouse_press_event",
"(",
"self",
",",
"x",
",",
"y",
",",
"button",
")",
":",
"if",
"button",
"==",
"1",
":",
"print",
"(",
"\"Left mouse button pressed @\"",
",",
"x",
",",
"y",
")",
"if",
"button",
"==",
"2",
":",
"print",
"(",
"\"Right mouse... | 44.166667 | 10.833333 |
def get_weekly_chart_dates(self):
"""Returns a list of From and To tuples for the available charts."""
doc = self._request(self.ws_prefix + ".getWeeklyChartList", True)
seq = []
for node in doc.getElementsByTagName("chart"):
seq.append((node.getAttribute("from"), node.getAt... | [
"def",
"get_weekly_chart_dates",
"(",
"self",
")",
":",
"doc",
"=",
"self",
".",
"_request",
"(",
"self",
".",
"ws_prefix",
"+",
"\".getWeeklyChartList\"",
",",
"True",
")",
"seq",
"=",
"[",
"]",
"for",
"node",
"in",
"doc",
".",
"getElementsByTagName",
"("... | 34.6 | 25.6 |
def set_object(self, obj, properties):
"""Add an object to the definition and set its ``properties``."""
self._objects.add(obj)
properties = set(properties)
self._properties |= properties
pairs = self._pairs
for p in self._properties:
if p in properties:
... | [
"def",
"set_object",
"(",
"self",
",",
"obj",
",",
"properties",
")",
":",
"self",
".",
"_objects",
".",
"add",
"(",
"obj",
")",
"properties",
"=",
"set",
"(",
"properties",
")",
"self",
".",
"_properties",
"|=",
"properties",
"pairs",
"=",
"self",
"."... | 36.181818 | 6.818182 |
def set_ref_b(self, text_ref):
"""
Set the reference values related to the str_b compared string
:param text_info: dict
-- author: str
-- work: str
-- subwork: str
-- text_n: str (a string instead of integer for vari... | [
"def",
"set_ref_b",
"(",
"self",
",",
"text_ref",
")",
":",
"if",
"'author'",
"in",
"text_ref",
":",
"self",
".",
"author_b",
"=",
"text_ref",
"[",
"'author'",
"]",
"if",
"'work'",
"in",
"text_ref",
":",
"self",
".",
"work_b",
"=",
"text_ref",
"[",
"'w... | 35.24 | 13.8 |
def get_session(db_url):
# type: (str) -> Session
"""Gets SQLAlchemy session given url. Your tables must inherit
from Base in hdx.utilities.database.
Args:
db_url (str): SQLAlchemy url
Returns:
sqlalchemy.orm.session.Session: SQLAlchemy session
"... | [
"def",
"get_session",
"(",
"db_url",
")",
":",
"# type: (str) -> Session",
"engine",
"=",
"create_engine",
"(",
"db_url",
",",
"poolclass",
"=",
"NullPool",
",",
"echo",
"=",
"False",
")",
"Session",
"=",
"sessionmaker",
"(",
"bind",
"=",
"engine",
")",
"Bas... | 32.6 | 15.333333 |
def dispatch(self, key):
""" Get a seq of Commandchain objects that match key """
if key in self.strs:
yield self.strs[key]
for r, obj in self.regexs.items():
if re.match(r, key):
yield obj
else:
#print "nomatch",key # dbg
... | [
"def",
"dispatch",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"strs",
":",
"yield",
"self",
".",
"strs",
"[",
"key",
"]",
"for",
"r",
",",
"obj",
"in",
"self",
".",
"regexs",
".",
"items",
"(",
")",
":",
"if",
"re",
".... | 29.727273 | 13.363636 |
def find_args(self):
"""Build self.args using all the fields."""
return self.mpi_cmd + ['-n', str(self.n)] + self.mpi_args + \
self.program + self.program_args | [
"def",
"find_args",
"(",
"self",
")",
":",
"return",
"self",
".",
"mpi_cmd",
"+",
"[",
"'-n'",
",",
"str",
"(",
"self",
".",
"n",
")",
"]",
"+",
"self",
".",
"mpi_args",
"+",
"self",
".",
"program",
"+",
"self",
".",
"program_args"
] | 46.75 | 14 |
def authorize_url(self):
"""
Build the authorization url and save the state. Return the
authorization url
"""
url, self.state = self.oauth.authorization_url(
'%sauthorize' % OAUTH_URL)
return url | [
"def",
"authorize_url",
"(",
"self",
")",
":",
"url",
",",
"self",
".",
"state",
"=",
"self",
".",
"oauth",
".",
"authorization_url",
"(",
"'%sauthorize'",
"%",
"OAUTH_URL",
")",
"return",
"url"
] | 31 | 12 |
def exclude_issues_by_labels(self, issues):
"""
Delete all issues with labels from exclude-labels option.
:param list(dict) issues: All issues for tag.
:rtype: list(dict)
:return: Filtered issues.
"""
if not self.options.exclude_labels:
return copy.de... | [
"def",
"exclude_issues_by_labels",
"(",
"self",
",",
"issues",
")",
":",
"if",
"not",
"self",
".",
"options",
".",
"exclude_labels",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"issues",
")",
"remove_issues",
"=",
"set",
"(",
")",
"exclude_labels",
"=",
"... | 34.130435 | 11.869565 |
def addView(self,view):
"""
Adds the supplied :py:class:`WorldView()` object to the internal registry.
The same restrictions as for cameras apply, e.g. no duplicate names.
Additionally, only instances of :py:class:`WorldView()` may be used, everything else raises a :py:... | [
"def",
"addView",
"(",
"self",
",",
"view",
")",
":",
"if",
"not",
"isinstance",
"(",
"view",
",",
"WorldView",
")",
":",
"raise",
"TypeError",
"(",
"\"view is not of type WorldView!\"",
")",
"self",
".",
"views",
"[",
"view",
".",
"name",
"]",
"=",
"vie... | 43.636364 | 24.727273 |
def compute_photometry(catalog, photmode):
""" Compute magnitudes for sources from catalog based on observations photmode.
Parameters
----------
catalog : `~astropy.table.Table`
Astropy Table with 'source_sum' column for the measured flux for each source.
photmode : str
Specificati... | [
"def",
"compute_photometry",
"(",
"catalog",
",",
"photmode",
")",
":",
"# Determine VEGAMAG zero-point using pysynphot for this photmode",
"photmode",
"=",
"photmode",
".",
"replace",
"(",
"' '",
",",
"', '",
")",
"vega",
"=",
"S",
".",
"FileSpectrum",
"(",
"VEGASP... | 37.090909 | 20.363636 |
def create(self, name, **params):
"""Creates a new role.
This function makes two roundtrips to the server, plus at most
two more if
the ``autologin`` field of :func:`connect` is set to ``True``.
:param name: Name for the role.
:type name: ``string``
:param param... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"ValueError",
"(",
"\"Invalid role name: %s\"",
"%",
"str",
"(",
"name",
")",
")",... | 36.512821 | 17.666667 |
def is_valid(self):
# type: () -> bool
"""
Returns whether the bundle is valid.
"""
if not self._errors:
try:
# We only have to check for a single error to determine
# if the bundle is valid or not.
self._errors.append(n... | [
"def",
"is_valid",
"(",
"self",
")",
":",
"# type: () -> bool",
"if",
"not",
"self",
".",
"_errors",
":",
"try",
":",
"# We only have to check for a single error to determine",
"# if the bundle is valid or not.",
"self",
".",
"_errors",
".",
"append",
"(",
"next",
"("... | 29.714286 | 14.857143 |
def get_readline_tail(self, n=10):
"""Get the last n items in readline history."""
end = self.shell.readline.get_current_history_length() + 1
start = max(end-n, 1)
ghi = self.shell.readline.get_history_item
return [ghi(x) for x in range(start, end)] | [
"def",
"get_readline_tail",
"(",
"self",
",",
"n",
"=",
"10",
")",
":",
"end",
"=",
"self",
".",
"shell",
".",
"readline",
".",
"get_current_history_length",
"(",
")",
"+",
"1",
"start",
"=",
"max",
"(",
"end",
"-",
"n",
",",
"1",
")",
"ghi",
"=",
... | 47.333333 | 10.5 |
def run_in_syspy(f):
"""
Decorator to run a function in the system python
:param f:
:return:
"""
fname = f.__name__
code_lines = inspect.getsource(f).splitlines()
code = dedent("\n".join(code_lines[1:])) # strip this decorator
# add call to the function and print it's result
... | [
"def",
"run_in_syspy",
"(",
"f",
")",
":",
"fname",
"=",
"f",
".",
"__name__",
"code_lines",
"=",
"inspect",
".",
"getsource",
"(",
"f",
")",
".",
"splitlines",
"(",
")",
"code",
"=",
"dedent",
"(",
"\"\\n\"",
".",
"join",
"(",
"code_lines",
"[",
"1"... | 25.322581 | 19.645161 |
def convert(gr, raw_node):
"""
Convert raw node information to a Node or Leaf instance.
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node, so that the tree is build
strictly bottom-up.
"""
type, value, context, children = ... | [
"def",
"convert",
"(",
"gr",
",",
"raw_node",
")",
":",
"type",
",",
"value",
",",
"context",
",",
"children",
"=",
"raw_node",
"if",
"children",
"or",
"type",
"in",
"gr",
".",
"number2symbol",
":",
"# If there's exactly one child, return that child instead of",
... | 37.176471 | 16.588235 |
def isprintable(string):
"""Return if all characters in string are printable.
>>> isprintable('abc')
True
>>> isprintable(b'\01')
False
"""
string = string.strip()
if not string:
return True
if sys.version_info[0] == 3:
try:
return string.isprintable()
... | [
"def",
"isprintable",
"(",
"string",
")",
":",
"string",
"=",
"string",
".",
"strip",
"(",
")",
"if",
"not",
"string",
":",
"return",
"True",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"3",
":",
"try",
":",
"return",
"string",
".",
"isp... | 26.703704 | 20.296296 |
def query(dataset_key, query, query_type='sql', profile='default',
parameters=None, **kwargs):
"""Query an existing dataset
:param dataset_key: Dataset identifier, in the form of owner/id or of a url
:type dataset_key: str
:param query: SQL or SPARQL query
:type query: str
:param quer... | [
"def",
"query",
"(",
"dataset_key",
",",
"query",
",",
"query_type",
"=",
"'sql'",
",",
"profile",
"=",
"'default'",
",",
"parameters",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_get_instance",
"(",
"profile",
",",
"*",
"*",
"kwargs",
... | 44.975 | 21.25 |
def get_environment_details(zone, environment):
""" Issues a request to Composer to get the environment details.
Args:
zone: GCP zone of the composer environment
environment: name of the Composer environment
Returns:
A parsed result object.
Raises:
Exception if there is an error... | [
"def",
"get_environment_details",
"(",
"zone",
",",
"environment",
")",
":",
"default_context",
"=",
"google",
".",
"datalab",
".",
"Context",
".",
"default",
"(",
")",
"url",
"=",
"(",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_ENVIRONMENTS_PATH_FORMA... | 41.0625 | 23.75 |
def cholesky_covariance(x, sample_axis=0, keepdims=False, name=None):
"""Cholesky factor of the covariance matrix of vector-variate random samples.
This function can be use to fit a multivariate normal to data.
```python
tf.enable_eager_execution()
import tensorflow_probability as tfp
tfd = tfp.distributi... | [
"def",
"cholesky_covariance",
"(",
"x",
",",
"sample_axis",
"=",
"0",
",",
"keepdims",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
",",
"'cholesky_covariance'",
",",
"values",
... | 40.185714 | 24.985714 |
def parse_type_system_definition(lexer: Lexer) -> TypeSystemDefinitionNode:
"""TypeSystemDefinition"""
# Many definitions begin with a description and require a lookahead.
keyword_token = lexer.lookahead() if peek_description(lexer) else lexer.token
func = _parse_type_system_definition_functions.get(cas... | [
"def",
"parse_type_system_definition",
"(",
"lexer",
":",
"Lexer",
")",
"->",
"TypeSystemDefinitionNode",
":",
"# Many definitions begin with a description and require a lookahead.",
"keyword_token",
"=",
"lexer",
".",
"lookahead",
"(",
")",
"if",
"peek_description",
"(",
"... | 53 | 24.75 |
def del_by_idx(tree, idxs):
"""
Delete a key entry based on numerical indexes into subtree lists.
"""
if len(idxs) == 0:
tree['item'] = None
tree['subtrees'] = []
else:
hidx, tidxs = idxs[0], idxs[1:]
del_by_idx(tree['subtrees'][hidx][1], tidxs)
if len(tree['s... | [
"def",
"del_by_idx",
"(",
"tree",
",",
"idxs",
")",
":",
"if",
"len",
"(",
"idxs",
")",
"==",
"0",
":",
"tree",
"[",
"'item'",
"]",
"=",
"None",
"tree",
"[",
"'subtrees'",
"]",
"=",
"[",
"]",
"else",
":",
"hidx",
",",
"tidxs",
"=",
"idxs",
"[",... | 32.083333 | 12.416667 |
def predict_proba(self, a, b, idx=0, **kwargs):
""" Use Jarfo to predict the causal direction of a pair of vars.
Args:
a (numpy.ndarray): Variable 1
b (numpy.ndarray): Variable 2
idx (int): (optional) index number for printing purposes
Returns:
f... | [
"def",
"predict_proba",
"(",
"self",
",",
"a",
",",
"b",
",",
"idx",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"predict_dataset",
"(",
"DataFrame",
"(",
"[",
"[",
"a",
",",
"b",
"]",
"]",
",",
"columns",
"=",
"[",
"'A'... | 38.384615 | 18.307692 |
def private_ips_present(name, network_interface_name=None, network_interface_id=None,
private_ip_addresses=None, allow_reassignment=False, region=None, key=None,
keyid=None, profile=None):
'''
Ensure an ENI has secondary private ip addresses associated with it
... | [
"def",
"private_ips_present",
"(",
"name",
",",
"network_interface_name",
"=",
"None",
",",
"network_interface_id",
"=",
"None",
",",
"private_ip_addresses",
"=",
"None",
",",
"allow_reassignment",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None... | 39.422764 | 24.837398 |
def resize(self, size):
"""
Resizes this Volume
"""
result = self._client.post('{}/resize'.format(Volume.api_endpoint, model=self,
data={ "size": size }))
self._populate(result.json)
return True | [
"def",
"resize",
"(",
"self",
",",
"size",
")",
":",
"result",
"=",
"self",
".",
"_client",
".",
"post",
"(",
"'{}/resize'",
".",
"format",
"(",
"Volume",
".",
"api_endpoint",
",",
"model",
"=",
"self",
",",
"data",
"=",
"{",
"\"size\"",
":",
"size",... | 24.7 | 18.7 |
def handle_block(self, match, block_start=None):
"""Handle a block. The current state of the parser should be after the
open block is completed:
{% blk foo %}my data {% endblk %}
^ right here
"""
# we have to handle comments inside blocks because you ... | [
"def",
"handle_block",
"(",
"self",
",",
"match",
",",
"block_start",
"=",
"None",
")",
":",
"# we have to handle comments inside blocks because you could do this:",
"# {% blk foo %}asdf {# {% endblk %} #} {%endblk%}",
"# they still end up in the data/raw_data of the block itself, but we... | 40.425926 | 16.296296 |
def _generate_struct_class_slots(self, data_type):
"""Creates a slots declaration for struct classes.
Slots are an optimization in Python. They reduce the memory footprint
of instances since attributes cannot be added after declaration.
"""
with self.block('__slots__ =', delim=(... | [
"def",
"_generate_struct_class_slots",
"(",
"self",
",",
"data_type",
")",
":",
"with",
"self",
".",
"block",
"(",
"'__slots__ ='",
",",
"delim",
"=",
"(",
"'['",
",",
"']'",
")",
")",
":",
"for",
"field",
"in",
"data_type",
".",
"fields",
":",
"field_na... | 45.333333 | 16.416667 |
def set_config(self, key, value):
'''set {key:value} paris to self.config'''
self.config = self.read_file()
self.config[key] = value
self.write_file() | [
"def",
"set_config",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"config",
"=",
"self",
".",
"read_file",
"(",
")",
"self",
".",
"config",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"write_file",
"(",
")"
] | 35.6 | 8.4 |
def setGridColor(self, color):
"""
Sets the color for the grid for this instance to the given color.
:param color | <QColor>
"""
palette = self.palette()
palette.setColor(palette.GridForeground, QColor(color)) | [
"def",
"setGridColor",
"(",
"self",
",",
"color",
")",
":",
"palette",
"=",
"self",
".",
"palette",
"(",
")",
"palette",
".",
"setColor",
"(",
"palette",
".",
"GridForeground",
",",
"QColor",
"(",
"color",
")",
")"
] | 33 | 13.75 |
def from_keyed_iterable(iterable, key, filter_func=None):
"""Construct a dictionary out of an iterable, using an attribute name as
the key. Optionally provide a filter function, to determine what should be
kept in the dictionary."""
generated = {}
for element in iterable:
try:
... | [
"def",
"from_keyed_iterable",
"(",
"iterable",
",",
"key",
",",
"filter_func",
"=",
"None",
")",
":",
"generated",
"=",
"{",
"}",
"for",
"element",
"in",
"iterable",
":",
"try",
":",
"k",
"=",
"getattr",
"(",
"element",
",",
"key",
")",
"except",
"Attr... | 31.454545 | 19.909091 |
def _pollCallStatus(self, expectedState, callId=None, timeout=None):
""" Poll the status of outgoing calls.
This is used for modems that do not have a known set of call status update notifications.
:param expectedState: The internal state we are waiting for. 0 == initiated, 1 == ans... | [
"def",
"_pollCallStatus",
"(",
"self",
",",
"expectedState",
",",
"callId",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"callDone",
"=",
"False",
"timeLeft",
"=",
"timeout",
"or",
"999999",
"while",
"self",
".",
"alive",
"and",
"not",
"callDone",
... | 54.26087 | 23.934783 |
def _init_client(self, from_archive=False):
"""Init client"""
return LaunchpadClient(self.distribution, self.package, self.items_per_page,
self.sleep_time, self.archive, from_archive) | [
"def",
"_init_client",
"(",
"self",
",",
"from_archive",
"=",
"False",
")",
":",
"return",
"LaunchpadClient",
"(",
"self",
".",
"distribution",
",",
"self",
".",
"package",
",",
"self",
".",
"items_per_page",
",",
"self",
".",
"sleep_time",
",",
"self",
".... | 45.4 | 24.4 |
def fetch(self, year: int, month: int):
"""Fetch year month data"""
self.raw_data = [self.fetcher.fetch(year, month, self.sid)]
self.data = self.raw_data[0]['data']
return self.data | [
"def",
"fetch",
"(",
"self",
",",
"year",
":",
"int",
",",
"month",
":",
"int",
")",
":",
"self",
".",
"raw_data",
"=",
"[",
"self",
".",
"fetcher",
".",
"fetch",
"(",
"year",
",",
"month",
",",
"self",
".",
"sid",
")",
"]",
"self",
".",
"data"... | 41.8 | 9.6 |
def clear_results_db(session):
'''Used to clear the result tables in the OEDB. Caution!
This deletes EVERY RESULT SET!'''
from egoio.db_tables.model_draft import EgoGridPfHvResultBus as BusResult,\
EgoGridPfHvResultBusT as BusTResult,\
EgoGridPfHvResultStorage as StorageResult,\
... | [
"def",
"clear_results_db",
"(",
"session",
")",
":",
"from",
"egoio",
".",
"db_tables",
".",
"model_draft",
"import",
"EgoGridPfHvResultBus",
"as",
"BusResult",
",",
"EgoGridPfHvResultBusT",
"as",
"BusTResult",
",",
"EgoGridPfHvResultStorage",
"as",
"StorageResult",
"... | 42.326087 | 12.326087 |
def focusInEvent(self, event):
"""Reimplement Qt method to send focus change notification"""
self.focus_changed.emit()
return super(ControlWidget, self).focusInEvent(event) | [
"def",
"focusInEvent",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"focus_changed",
".",
"emit",
"(",
")",
"return",
"super",
"(",
"ControlWidget",
",",
"self",
")",
".",
"focusInEvent",
"(",
"event",
")"
] | 48.25 | 9.5 |
def dispatch(self, request, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Check if this is a REST query to pusth the answer to responde in JSON
if bool(self.request.META.get('HTTP_X_REST', False)):
self.json = True
# Check if th... | [
"def",
"dispatch",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check if this is a REST query to pusth the answer to responde in JSON",
"if",
"bool",
"(",
"self",
".",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_X_REST'",
",",
"False",
... | 34.585366 | 22.634146 |
def get_environments():
"""
Return defined environments from config file for default
environment values.
"""
config = ConfigParser.SafeConfigParser()
config = _config_file()
juicer.utils.Log.log_debug("Reading environment sections:")
environments = config.sections()
juicer.utils.L... | [
"def",
"get_environments",
"(",
")",
":",
"config",
"=",
"ConfigParser",
".",
"SafeConfigParser",
"(",
")",
"config",
"=",
"_config_file",
"(",
")",
"juicer",
".",
"utils",
".",
"Log",
".",
"log_debug",
"(",
"\"Reading environment sections:\"",
")",
"environment... | 28.642857 | 20.214286 |
def retrieve_object_query(self, view_kwargs, filter_field, filter_value):
"""Build query to retrieve object
:param dict view_kwargs: kwargs from the resource view
:params sqlalchemy_field filter_field: the field to filter on
:params filter_value: the value to filter with
:return... | [
"def",
"retrieve_object_query",
"(",
"self",
",",
"view_kwargs",
",",
"filter_field",
",",
"filter_value",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"model",
")",
".",
"filter",
"(",
"filter_field",
"==",
"filter_value",
")"... | 49.888889 | 21.888889 |
def from_nds2(cls, nds2channel):
"""Generate a new channel using an existing nds2.channel object
"""
# extract metadata
name = nds2channel.name
sample_rate = nds2channel.sample_rate
unit = nds2channel.signal_units
if not unit:
unit = None
ctype... | [
"def",
"from_nds2",
"(",
"cls",
",",
"nds2channel",
")",
":",
"# extract metadata",
"name",
"=",
"nds2channel",
".",
"name",
"sample_rate",
"=",
"nds2channel",
".",
"sample_rate",
"unit",
"=",
"nds2channel",
".",
"signal_units",
"if",
"not",
"unit",
":",
"unit... | 43.47619 | 13.285714 |
def filenames(self) -> Tuple[str, ...]:
"""A |tuple| of names of all handled |NetCDFFile| objects."""
return tuple(sorted(set(itertools.chain(
*(_.keys() for _ in self.folders.values()))))) | [
"def",
"filenames",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"set",
"(",
"itertools",
".",
"chain",
"(",
"*",
"(",
"_",
".",
"keys",
"(",
")",
"for",
"_",
"in",
"self",
".",
"fold... | 53.5 | 6.75 |
def put_many(self, items: Iterable[T], context: PipelineContext = None) -> None:
"""Puts multiple objects of the same type into the data sink. The objects may be transformed into a new type for insertion if necessary.
Args:
items: An iterable (e.g. list) of objects to be inserted into the d... | [
"def",
"put_many",
"(",
"self",
",",
"items",
":",
"Iterable",
"[",
"T",
"]",
",",
"context",
":",
"PipelineContext",
"=",
"None",
")",
"->",
"None",
":",
"LOGGER",
".",
"info",
"(",
"\"Creating transform generator for items \\\"{items}\\\" for sink \\\"{sink}\\\"\"... | 75 | 40.363636 |
def get_table_column_statistics(self, db_name, tbl_name, col_name):
"""
Parameters:
- db_name
- tbl_name
- col_name
"""
self.send_get_table_column_statistics(db_name, tbl_name, col_name)
return self.recv_get_table_column_statistics() | [
"def",
"get_table_column_statistics",
"(",
"self",
",",
"db_name",
",",
"tbl_name",
",",
"col_name",
")",
":",
"self",
".",
"send_get_table_column_statistics",
"(",
"db_name",
",",
"tbl_name",
",",
"col_name",
")",
"return",
"self",
".",
"recv_get_table_column_stati... | 28.888889 | 18.666667 |
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
... | [
"def",
"clean_old_jobs",
"(",
")",
":",
"if",
"__opts__",
".",
"get",
"(",
"'keep_jobs'",
",",
"False",
")",
"and",
"int",
"(",
"__opts__",
".",
"get",
"(",
"'keep_jobs'",
",",
"0",
")",
")",
">",
"0",
":",
"try",
":",
"with",
"_get_serv",
"(",
")"... | 40.363636 | 22.363636 |
def dynamic_instantiate_middleware(name, args, expand=None):
"""Import a class and instantiate with custom args.
Example:
name = "my.module.Foo"
args_dict = {
"bar": 42,
"baz": "qux"
}
=>
from my.module import Foo
return Foo(bar=42, ba... | [
"def",
"dynamic_instantiate_middleware",
"(",
"name",
",",
"args",
",",
"expand",
"=",
"None",
")",
":",
"def",
"_expand",
"(",
"v",
")",
":",
"\"\"\"Replace some string templates with defined values.\"\"\"",
"if",
"expand",
"and",
"compat",
".",
"is_basestring",
"(... | 29.222222 | 19.722222 |
def keywords(self):
"""
Get the plot keywords for a specific movie id.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('keywords')
response = self._GET(path)
self._set_attrs_to_values(response)
r... | [
"def",
"keywords",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"_get_id_path",
"(",
"'keywords'",
")",
"response",
"=",
"self",
".",
"_GET",
"(",
"path",
")",
"self",
".",
"_set_attrs_to_values",
"(",
"response",
")",
"return",
"response"
] | 26.916667 | 16.416667 |
def tasks(self):
"""Get the list of tasks"""
self._rwlock.reader_acquire()
tl = [v for v in self._tasks.values()]
tl.sort(key=lambda x: x.task_id)
self._rwlock.reader_release()
return tl | [
"def",
"tasks",
"(",
"self",
")",
":",
"self",
".",
"_rwlock",
".",
"reader_acquire",
"(",
")",
"tl",
"=",
"[",
"v",
"for",
"v",
"in",
"self",
".",
"_tasks",
".",
"values",
"(",
")",
"]",
"tl",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
... | 25.333333 | 15.444444 |
def htmlsafe(unsafe):
"""
Escapes all x(ht)ml control characters.
"""
unsafe = unsafe.replace('&', '&')
unsafe = unsafe.replace('<', '<')
unsafe = unsafe.replace('>', '>')
return unsafe | [
"def",
"htmlsafe",
"(",
"unsafe",
")",
":",
"unsafe",
"=",
"unsafe",
".",
"replace",
"(",
"'&'",
",",
"'&'",
")",
"unsafe",
"=",
"unsafe",
".",
"replace",
"(",
"'<'",
",",
"'<'",
")",
"unsafe",
"=",
"unsafe",
".",
"replace",
"(",
"'>'",
",",
... | 27 | 5.75 |
def topological_sort(source):
"""perform topo sort on elements.
:arg source: list of ``(name, [list of dependancies])`` pairs
:returns: list of names, with dependancies listed first
"""
if isinstance(source, dict):
source = source.items()
pending = sorted([(name, set(deps)) for name, de... | [
"def",
"topological_sort",
"(",
"source",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"dict",
")",
":",
"source",
"=",
"source",
".",
"items",
"(",
")",
"pending",
"=",
"sorted",
"(",
"[",
"(",
"name",
",",
"set",
"(",
"deps",
")",
")",
"for"... | 46.307692 | 23 |
def get_table_acl(self, table_name, timeout=None):
'''
Returns details about any stored access policies specified on the
table that may be used with Shared Access Signatures.
:param str table_name:
The name of an existing table.
:param int timeout:
The se... | [
"def",
"get_table_acl",
"(",
"self",
",",
"table_name",
",",
"timeout",
"=",
"None",
")",
":",
"_validate_not_none",
"(",
"'table_name'",
",",
"table_name",
")",
"request",
"=",
"HTTPRequest",
"(",
")",
"request",
".",
"method",
"=",
"'GET'",
"request",
".",... | 40.391304 | 21.26087 |
def set_shutdown(self, state):
"""
Set the shutdown state of the Connection.
:param state: bitvector of SENT_SHUTDOWN, RECEIVED_SHUTDOWN.
:return: None
"""
if not isinstance(state, integer_types):
raise TypeError("state must be an integer")
_lib.SSL_... | [
"def",
"set_shutdown",
"(",
"self",
",",
"state",
")",
":",
"if",
"not",
"isinstance",
"(",
"state",
",",
"integer_types",
")",
":",
"raise",
"TypeError",
"(",
"\"state must be an integer\"",
")",
"_lib",
".",
"SSL_set_shutdown",
"(",
"self",
".",
"_ssl",
",... | 30.909091 | 16 |
def encrypt_password(**kwargs):
""" Crypt :new_value: if it's not crypted yet. """
new_value = kwargs['new_value']
field = kwargs['field']
min_length = field.params['min_length']
if len(new_value) < min_length:
raise ValueError(
'`{}`: Value length must be more than {}'.format(
... | [
"def",
"encrypt_password",
"(",
"*",
"*",
"kwargs",
")",
":",
"new_value",
"=",
"kwargs",
"[",
"'new_value'",
"]",
"field",
"=",
"kwargs",
"[",
"'field'",
"]",
"min_length",
"=",
"field",
".",
"params",
"[",
"'min_length'",
"]",
"if",
"len",
"(",
"new_va... | 37.153846 | 12.538462 |
async def _check_resolver_ans(
self, dns_answer_list, record_name,
record_data_list, record_ttl, record_type_code):
"""Check if resolver answer is equal to record data.
Args:
dns_answer_list (list): DNS answer list contains record objects.
record_name (st... | [
"async",
"def",
"_check_resolver_ans",
"(",
"self",
",",
"dns_answer_list",
",",
"record_name",
",",
"record_data_list",
",",
"record_ttl",
",",
"record_type_code",
")",
":",
"type_filtered_list",
"=",
"[",
"ans",
"for",
"ans",
"in",
"dns_answer_list",
"if",
"ans"... | 37.055556 | 19.416667 |
def cli(env, identifier, postinstall, key, image):
"""Reload operating system on a virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
keys = []
if key:
for single_key in key:
resolver = SoftLayer.SshKeyManager(e... | [
"def",
"cli",
"(",
"env",
",",
"identifier",
",",
"postinstall",
",",
"key",
",",
"image",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
... | 39.055556 | 16.944444 |
def render_q(q, qn, connection):
"""
Renders the Q object into SQL for the WHEN clause.
Uses as much as possible the Django ORM machinery for SQL generation,
handling table aliases, field quoting, parameter escaping etc.
:param q: Q object representing the filter condition
:param qn: db specif... | [
"def",
"render_q",
"(",
"q",
",",
"qn",
",",
"connection",
")",
":",
"joinstr",
"=",
"u' {} '",
".",
"format",
"(",
"q",
".",
"connector",
")",
"conditions",
"=",
"[",
"]",
"params",
"=",
"[",
"]",
"if",
"DJANGO_MAJOR",
"==",
"1",
"and",
"DJANGO_MINO... | 36.285714 | 18.489796 |
def GetSOAPHeaders(self, create_method):
"""Returns the SOAP headers required for request authorization.
Args:
create_method: The SOAP library specific method used to instantiate SOAP
objects.
Returns:
A SOAP object containing the headers.
"""
header = create_method(self._SOAP_HE... | [
"def",
"GetSOAPHeaders",
"(",
"self",
",",
"create_method",
")",
":",
"header",
"=",
"create_method",
"(",
"self",
".",
"_SOAP_HEADER_CLASS",
"%",
"self",
".",
"_version",
")",
"header",
".",
"clientCustomerId",
"=",
"self",
".",
"_adwords_client",
".",
"clien... | 39.105263 | 20.052632 |
def show_extent_selector(self):
"""Show the extent selector widget for defining analysis extents."""
# import here only so that it is AFTER i18n set up
from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog
widget = ExtentSelectorDialog(
self.iface,
... | [
"def",
"show_extent_selector",
"(",
"self",
")",
":",
"# import here only so that it is AFTER i18n set up",
"from",
"safe",
".",
"gui",
".",
"tools",
".",
"extent_selector_dialog",
"import",
"ExtentSelectorDialog",
"widget",
"=",
"ExtentSelectorDialog",
"(",
"self",
".",
... | 50.055556 | 14.388889 |
def value_iteration(self, v_init=None, epsilon=None, max_iter=None):
"""
Solve the optimization problem by value iteration. See the
`solve` method.
"""
if self.beta == 1:
raise NotImplementedError(self._error_msg_no_discounting)
if max_iter is None:
... | [
"def",
"value_iteration",
"(",
"self",
",",
"v_init",
"=",
"None",
",",
"epsilon",
"=",
"None",
",",
"max_iter",
"=",
"None",
")",
":",
"if",
"self",
".",
"beta",
"==",
"1",
":",
"raise",
"NotImplementedError",
"(",
"self",
".",
"_error_msg_no_discounting"... | 31.952381 | 18.238095 |
def _populate_cache(platform, pkg_cache, mount_dir):
'''
If a ``pkg_cache`` directory is specified, then use it to populate the
disk image.
'''
if not pkg_cache:
return
if not os.path.isdir(pkg_cache):
return
if platform == 'pacman':
cache_dir = '{0}/var/cache/pacman... | [
"def",
"_populate_cache",
"(",
"platform",
",",
"pkg_cache",
",",
"mount_dir",
")",
":",
"if",
"not",
"pkg_cache",
":",
"return",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"pkg_cache",
")",
":",
"return",
"if",
"platform",
"==",
"'pacman'",
":",... | 31.666667 | 26.066667 |
def fill_polygon(self, polygons, colour=7, bg=0):
"""
Draw a filled polygon.
This function uses the scan line algorithm to create the polygon. See
https://www.cs.uic.edu/~jbell/CourseNotes/ComputerGraphics/PolygonFilling.html for details.
:param polygons: A list of polygons (w... | [
"def",
"fill_polygon",
"(",
"self",
",",
"polygons",
",",
"colour",
"=",
"7",
",",
"bg",
"=",
"0",
")",
":",
"def",
"_add_edge",
"(",
"a",
",",
"b",
")",
":",
"# Ignore horizontal lines - they are redundant",
"if",
"a",
"[",
"1",
"]",
"==",
"b",
"[",
... | 40.034483 | 19.62069 |
def parse_gptl(file_path, var_list):
"""
Read a GPTL timing file and extract some data.
Args:
file_path: the path to the GPTL timing file
var_list: a list of strings to look for in the file
Returns:
A dict containing key-value pairs of the livvkit
and the times associat... | [
"def",
"parse_gptl",
"(",
"file_path",
",",
"var_list",
")",
":",
"timing_result",
"=",
"dict",
"(",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"'r'",
")",
"as",
"f",
":",
"for",
... | 31.666667 | 15.285714 |
def convert_general(value):
"""Take a python object and convert it to the format Imgur expects."""
if isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, list):
value = [convert_general(item) for item in value]
value = convert_to_imgur_list(value)
... | [
"def",
"convert_general",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"\"true\"",
"if",
"value",
"else",
"\"false\"",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"convert_ge... | 39.416667 | 8.583333 |
def parse_sequencetableline(self, line):
""" Parses sequence table lines
Sequence Table example:
Sequence Table,,,,,,,,,,,,,,,,,
Data File,Sample Name,Position,Inj Vol,Level,Sample Type,Acq Method File,,,,,,,,,,,
prerunrespchk.d,prerunrespchk,Vial 3,-1.00,,Sample... | [
"def",
"parse_sequencetableline",
"(",
"self",
",",
"line",
")",
":",
"# Sequence Table,,,,,,,,,,,,,,,,,",
"# prerunrespchk.d,prerunrespchk,Vial 3,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.m,,,,,,,,,,,",
"# mid_respchk.d,mid_respchk,Vial 3,-1.00,,Sample,120824_VitD_MAPTAD_1D_MRM_practice.... | 56.470588 | 29.411765 |
def select(self, *columns):
"""
Set the columns to be selected
:param columns: The columns to be selected
:type columns: tuple
:return: The current QueryBuilder instance
:rtype: QueryBuilder
"""
if not columns:
columns = ["*"]
self.c... | [
"def",
"select",
"(",
"self",
",",
"*",
"columns",
")",
":",
"if",
"not",
"columns",
":",
"columns",
"=",
"[",
"\"*\"",
"]",
"self",
".",
"columns",
"=",
"list",
"(",
"columns",
")",
"return",
"self"
] | 21.75 | 17.125 |
def read(self, entity=None, attrs=None, ignore=None, params=None):
"""Fetch as many attributes as possible for this entity.
Do not read the ``facts``, ``organization`` or ``type`` attributes.
For more information, see `Bugzilla #1202917
<https://bugzilla.redhat.com/show_bug.cgi?id=12029... | [
"def",
"read",
"(",
"self",
",",
"entity",
"=",
"None",
",",
"attrs",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"attrs",
"is",
"None",
":",
"attrs",
"=",
"self",
".",
"read_json",
"(",
")",
"attrs",
"[",... | 44.705882 | 19.941176 |
def consumed_in_month(self):
""" How many resources were (or will be) consumed until end of the month """
month_end = core_utils.month_end(datetime.date(self.price_estimate.year, self.price_estimate.month, 1))
return self._get_consumed(month_end) | [
"def",
"consumed_in_month",
"(",
"self",
")",
":",
"month_end",
"=",
"core_utils",
".",
"month_end",
"(",
"datetime",
".",
"date",
"(",
"self",
".",
"price_estimate",
".",
"year",
",",
"self",
".",
"price_estimate",
".",
"month",
",",
"1",
")",
")",
"ret... | 66.75 | 21.75 |
def generate_contour_data(pid):
"""
Main function for this program.
This will read in sensitivity_curves and binary parameters; calculate snrs
with a matched filtering approach; and then read the contour data out to a file.
Args:
pid (obj or dict): GenInput class or dictionary containing a... | [
"def",
"generate_contour_data",
"(",
"pid",
")",
":",
"# check if pid is dicionary or GenInput class",
"# if GenInput, change to dictionary",
"if",
"isinstance",
"(",
"pid",
",",
"GenInput",
")",
":",
"pid",
"=",
"pid",
".",
"return_dict",
"(",
")",
"begin_time",
"="... | 35.3 | 24.45 |
def close(self, **kw):
"""
This asks Tor to close the underlying stream object. See
:meth:`txtorcon.interface.ITorControlProtocol.close_stream`
for details.
Although Tor currently takes no flags, it allows you to; any
keyword arguments are passed through as flags.
... | [
"def",
"close",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_closing_deferred",
"=",
"defer",
".",
"Deferred",
"(",
")",
"def",
"close_command_is_queued",
"(",
"*",
"args",
")",
":",
"return",
"self",
".",
"_closing_deferred",
"d",
"=",
"... | 36.5 | 19.318182 |
def covar(self):
"""
The covariance matrix for the result :math:`\\beta`
"""
if self._covar is None:
self._covar = _np.linalg.inv(_np.dot(_np.transpose(self.X), self.X))
return self._covar | [
"def",
"covar",
"(",
"self",
")",
":",
"if",
"self",
".",
"_covar",
"is",
"None",
":",
"self",
".",
"_covar",
"=",
"_np",
".",
"linalg",
".",
"inv",
"(",
"_np",
".",
"dot",
"(",
"_np",
".",
"transpose",
"(",
"self",
".",
"X",
")",
",",
"self",
... | 33.428571 | 15.142857 |
def file_list( blockchain_id, config_path=CONFIG_PATH, wallet_keys=None ):
"""
List all files uploaded to a particular blockchain ID
Return {'status': True, 'listing': list} on success
Return {'error': ...} on error
"""
config_dir = os.path.dirname(config_path)
client_config_path = os.path.... | [
"def",
"file_list",
"(",
"blockchain_id",
",",
"config_path",
"=",
"CONFIG_PATH",
",",
"wallet_keys",
"=",
"None",
")",
":",
"config_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"config_path",
")",
"client_config_path",
"=",
"os",
".",
"path",
".",
"... | 35.115385 | 22.346154 |
def set_max_position_size(self,
asset=None,
max_shares=None,
max_notional=None,
on_error='fail'):
"""Set a limit on the number of shares and/or dollar value held for the
given sid. Lim... | [
"def",
"set_max_position_size",
"(",
"self",
",",
"asset",
"=",
"None",
",",
"max_shares",
"=",
"None",
",",
"max_notional",
"=",
"None",
",",
"on_error",
"=",
"'fail'",
")",
":",
"control",
"=",
"MaxPositionSize",
"(",
"asset",
"=",
"asset",
",",
"max_sha... | 46.290323 | 18.354839 |
def rustcall(func, *args):
"""Calls rust method and does some error handling."""
lib.semaphore_err_clear()
rv = func(*args)
err = lib.semaphore_err_get_last_code()
if not err:
return rv
msg = lib.semaphore_err_get_last_message()
cls = exceptions_by_code.get(err, SemaphoreError)
e... | [
"def",
"rustcall",
"(",
"func",
",",
"*",
"args",
")",
":",
"lib",
".",
"semaphore_err_clear",
"(",
")",
"rv",
"=",
"func",
"(",
"*",
"args",
")",
"err",
"=",
"lib",
".",
"semaphore_err_get_last_code",
"(",
")",
"if",
"not",
"err",
":",
"return",
"rv... | 32.857143 | 14.5 |
def change_vlan_id(self, original, new):
"""
Change VLAN ID for a single VLAN, cluster VLAN or inline
interface. When changing a single or cluster FW vlan, you
can specify the original VLAN and new VLAN as either single
int or str value. If modifying an inline interface VLAN when... | [
"def",
"change_vlan_id",
"(",
"self",
",",
"original",
",",
"new",
")",
":",
"vlan",
"=",
"self",
".",
"vlan_interface",
".",
"get_vlan",
"(",
"original",
")",
"newvlan",
"=",
"str",
"(",
"new",
")",
".",
"split",
"(",
"'-'",
")",
"splitted",
"=",
"v... | 42.711111 | 16 |
def confirm(*args, **kwargs):
"""Prompt for confirmation (yes/no) and handle any abort exceptions."""
try:
return click.confirm(*args, **kwargs)
except click.Abort:
return False | [
"def",
"confirm",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"click",
".",
"confirm",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"click",
".",
"Abort",
":",
"return",
"False"
] | 33.333333 | 14.166667 |
def _format_param_val(self, param_val):
"""
Internal method to format values in the packmol parameter dictionaries
Args:
param_val:
Some object to turn into String
Returns:
string representation of the object
"""
if isinst... | [
"def",
"_format_param_val",
"(",
"self",
",",
"param_val",
")",
":",
"if",
"isinstance",
"(",
"param_val",
",",
"list",
")",
":",
"return",
"' '",
".",
"join",
"(",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"param_val",
")",
"else",
":",
"return",
"str... | 28.733333 | 17 |
def replace_u(matchobj):
"""Break the interval into parts, and replace 'u's.
pieces - [pos/neg, start_year, start_month, start_day,
pos/neg, end_year, end_month, end_day]
"""
pieces = list(matchobj.groups(''))
# Replace "u"s in start and end years.
if 'u' in pieces[1]:
pie... | [
"def",
"replace_u",
"(",
"matchobj",
")",
":",
"pieces",
"=",
"list",
"(",
"matchobj",
".",
"groups",
"(",
"''",
")",
")",
"# Replace \"u\"s in start and end years.",
"if",
"'u'",
"in",
"pieces",
"[",
"1",
"]",
":",
"pieces",
"[",
"1",
"]",
"=",
"pieces"... | 38.807692 | 13.807692 |
def gameloop(self):
"""
A game loop that circles through the methods.
"""
try:
while True:
self.handle_events()
self.update()
self.render()
except KeyboardInterrupt:
pass | [
"def",
"gameloop",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"self",
".",
"handle_events",
"(",
")",
"self",
".",
"update",
"(",
")",
"self",
".",
"render",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
] | 24.727273 | 12.363636 |
def select_action(self, pos1, pos2, ctrl, shift):
"""Return a `sc_pb.Action` with the selection filled."""
assert pos1.surf.surf_type == pos2.surf.surf_type
assert pos1.surf.world_to_obs == pos2.surf.world_to_obs
action = sc_pb.Action()
action_spatial = pos1.action_spatial(action)
if pos1.worl... | [
"def",
"select_action",
"(",
"self",
",",
"pos1",
",",
"pos2",
",",
"ctrl",
",",
"shift",
")",
":",
"assert",
"pos1",
".",
"surf",
".",
"surf_type",
"==",
"pos2",
".",
"surf",
".",
"surf_type",
"assert",
"pos1",
".",
"surf",
".",
"world_to_obs",
"==",
... | 38.633333 | 19.9 |
def setup_packages():
'''
Custom setup for Corrfunc package.
Optional: Set compiler via 'CC=/path/to/compiler' or
'CC /path/to/compiler' or 'CC = /path/to/compiler'
All the CC options are removed from sys.argv after
being parsed.
'''
# protect the user in ... | [
"def",
"setup_packages",
"(",
")",
":",
"# protect the user in case they run python setup.py not from root directory",
"src_path",
"=",
"dirname",
"(",
"abspath",
"(",
"sys",
".",
"argv",
"[",
"0",
"]",
")",
")",
"old_path",
"=",
"os",
".",
"getcwd",
"(",
")",
"... | 40.160584 | 17.635036 |
def copy_ecu(ecu_or_glob, source_db, target_db):
# type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None
"""
Copy ECU(s) identified by Name or as Object from source CAN matrix to target CAN matrix.
This function additionally copy all relevant Defines.
:param ecu_or_glob: Ecu instanc... | [
"def",
"copy_ecu",
"(",
"ecu_or_glob",
",",
"source_db",
",",
"target_db",
")",
":",
"# type: (typing.Union[cm.Ecu, str], cm.CanMatrix, cm.CanMatrix) -> None",
"# check whether ecu_or_glob is object or symbolic name",
"if",
"isinstance",
"(",
"ecu_or_glob",
",",
"cm",
".",
"Ecu... | 47.5 | 21.25 |
def reserve(self, max=None, timeout=None, wait=None, delete=None):
"""Retrieves Messages from the queue and reserves it.
Arguments:
max -- The maximum number of messages to reserve. Defaults to 1.
timeout -- Timeout in seconds.
wait -- Time to long poll for messages, in seconds.... | [
"def",
"reserve",
"(",
"self",
",",
"max",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"wait",
"=",
"None",
",",
"delete",
"=",
"None",
")",
":",
"url",
"=",
"\"queues/%s/reservations\"",
"%",
"self",
".",
"name",
"qitems",
"=",
"{",
"}",
"if",
... | 39.08 | 19.16 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.