text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _open(file_or_str, **kwargs):
'''Either open a file handle, or use an existing file-like object.
This will behave as the `open` function if `file_or_str` is a string.
If `file_or_str` has the `read` attribute, it will return `file_or_str`.
Otherwise, an `IOError` is raised.
'''
if hasattr... | [
"def",
"_open",
"(",
"file_or_str",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"file_or_str",
",",
"'read'",
")",
":",
"yield",
"file_or_str",
"elif",
"isinstance",
"(",
"file_or_str",
",",
"six",
".",
"string_types",
")",
":",
"with",
"ope... | 35.875 | 0.001698 |
def __random_density_hs(N, rank=None, seed=None):
"""
Generate a random density matrix from the Hilbert-Schmidt metric.
Args:
N (int): the length of the density matrix.
rank (int or None): the rank of the density matrix. The default
value is full-rank.
seed (int): Option... | [
"def",
"__random_density_hs",
"(",
"N",
",",
"rank",
"=",
"None",
",",
"seed",
"=",
"None",
")",
":",
"G",
"=",
"__ginibre_matrix",
"(",
"N",
",",
"rank",
",",
"seed",
")",
"G",
"=",
"G",
".",
"dot",
"(",
"G",
".",
"conj",
"(",
")",
".",
"T",
... | 32.666667 | 0.001984 |
def create_style(self,title=None,defaults=None,mappings=None,verbose=VERBOSE):
"""
Creates a new visual style
:param title: title of the visual style
:param defaults: a list of dictionaries for each visualProperty
:param mappings: a list of dictionaries for each visualProperty
... | [
"def",
"create_style",
"(",
"self",
",",
"title",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"mappings",
"=",
"None",
",",
"verbose",
"=",
"VERBOSE",
")",
":",
"u",
"=",
"self",
".",
"__url",
"host",
"=",
"u",
".",
"split",
"(",
"\"//\"",
")",... | 33.25 | 0.021912 |
def steam64_from_url(url, http_timeout=30):
"""
Takes a Steam Community url and returns steam64 or None
.. note::
Each call makes a http request to ``steamcommunity.com``
.. note::
For a reliable resolving of vanity urls use ``ISteamUser.ResolveVanityURL`` web api
:param url: stea... | [
"def",
"steam64_from_url",
"(",
"url",
",",
"http_timeout",
"=",
"30",
")",
":",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(?P<clean_url>https?://steamcommunity.com/'",
"r'(?P<type>profiles|id|gid|groups)/(?P<value>.*?))(?:/(?:.*)?)?$'",
",",
"url",
")",
"if",
"not",
"... | 35.207547 | 0.00365 |
def nonblock_read(stream, limit=None, forceMode=None):
'''
nonblock_read - Read any data available on the given stream (file, socket, etc) without blocking and regardless of newlines.
@param stream <object> - A stream (like a file object or a socket)
@param limit <None/int> - Max nu... | [
"def",
"nonblock_read",
"(",
"stream",
",",
"limit",
"=",
"None",
",",
"forceMode",
"=",
"None",
")",
":",
"bytesRead",
"=",
"0",
"ret",
"=",
"[",
"]",
"if",
"forceMode",
":",
"if",
"'b'",
"in",
"forceMode",
":",
"streamMode",
"=",
"bytes",
"elif",
"... | 36.839286 | 0.005666 |
def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
Inherited method should take all specified arguments.
:param variable_p... | [
"def",
"get",
"(",
"self",
",",
"variable_path",
":",
"str",
",",
"default",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Any",
"]",
"=",
"None",
",",
"coerce_type",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Type",
"]",
"=",
"None",
",",
"coercer"... | 42.411765 | 0.009498 |
def initialize_db_args(self, settings, db_key):
""" Initialize connection arguments for postgres commands. """
self.print_message("Initializing database settings for %s" % db_key, verbosity_needed=2)
db_member = self.databases[db_key]
db_name = settings.get('NAME')
if db_name a... | [
"def",
"initialize_db_args",
"(",
"self",
",",
"settings",
",",
"db_key",
")",
":",
"self",
".",
"print_message",
"(",
"\"Initializing database settings for %s\"",
"%",
"db_key",
",",
"verbosity_needed",
"=",
"2",
")",
"db_member",
"=",
"self",
".",
"databases",
... | 36.7 | 0.005312 |
def cmd_jshell(ip, port, verbose):
"""Control a web browser through Websockets.
Bind a port (default: 3333) and listen for HTTP connections.
On connection, send a JavaScript code that opens a WebSocket that
can be used to send commands to the connected browser.
You can write the commands directly... | [
"def",
"cmd_jshell",
"(",
"ip",
",",
"port",
",",
"verbose",
")",
":",
"global",
"hook_js",
"hook_js",
"=",
"hook_js",
".",
"format",
"(",
"ip",
"=",
"ip",
",",
"port",
"=",
"port",
")",
"print",
"(",
"'>>> Listening on {}:{}. Waiting for a victim connection.'... | 33.268657 | 0.00305 |
def ilen(iterable):
"""Return the number of items in *iterable*.
>>> ilen(x for x in range(1000000) if x % 3 == 0)
333334
This consumes the iterable, so handle with care.
"""
# This approach was selected because benchmarks showed it's likely the
# fastest of the known implementati... | [
"def",
"ilen",
"(",
"iterable",
")",
":",
"# This approach was selected because benchmarks showed it's likely the",
"# fastest of the known implementations at the time of writing.",
"# See GitHub tracker: #236, #230.",
"counter",
"=",
"count",
"(",
")",
"deque",
"(",
"zip",
"(",
... | 30.8 | 0.002101 |
def list_backups_dir(path, limit=None):
'''
Lists the previous versions of a directory backed up using Salt's :ref:`file
state backup <file-state-backups>` system.
path
The directory on the minion to check for backups
limit
Limit the number of results to the most recent N backups
... | [
"def",
"list_backups_dir",
"(",
"path",
",",
"limit",
"=",
"None",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"try",
":",
"limit",
"=",
"int",
"(",
"limit",
")",
"except",
"TypeError",
":",
"pass",
"except",
"Value... | 34.423729 | 0.002393 |
def notify_scale_factor_change(self, screen_id, u32_scale_factor_w_multiplied, u32_scale_factor_h_multiplied):
"""Notify OpenGL HGCM host service about graphics content scaling factor change.
in screen_id of type int
in u32_scale_factor_w_multiplied of type int
in u32_scale_factor_h_m... | [
"def",
"notify_scale_factor_change",
"(",
"self",
",",
"screen_id",
",",
"u32_scale_factor_w_multiplied",
",",
"u32_scale_factor_h_multiplied",
")",
":",
"if",
"not",
"isinstance",
"(",
"screen_id",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"screen_id... | 54 | 0.0091 |
def _db_remove_prefix(self, spec, recursive = False):
""" Do the underlying database operations to delete a prefix
"""
if recursive:
prefix = spec['prefix']
del spec['prefix']
where, params = self._expand_prefix_spec(spec)
spec['prefix'] = prefix
... | [
"def",
"_db_remove_prefix",
"(",
"self",
",",
"spec",
",",
"recursive",
"=",
"False",
")",
":",
"if",
"recursive",
":",
"prefix",
"=",
"spec",
"[",
"'prefix'",
"]",
"del",
"spec",
"[",
"'prefix'",
"]",
"where",
",",
"params",
"=",
"self",
".",
"_expand... | 38 | 0.006849 |
def main(argv=None):
"""Entry point for the `simpl` command."""
#
# `simpl server`
#
logging.basicConfig(level=logging.INFO)
server_func = functools.partial(server.main, argv=argv)
server_parser = server.attach_parser(default_subparser())
server_parser.set_defaults(_func=server_func)
... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"#",
"# `simpl server`",
"#",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
")",
"server_func",
"=",
"functools",
".",
"partial",
"(",
"server",
".",
"main",
",",
"argv",
"=... | 32.285714 | 0.002151 |
def morlet(freq, s_freq, ratio=5, sigma_f=None, dur_in_sd=4, dur_in_s=None,
normalization='peak', zero_mean=False):
"""Create a Morlet wavelet.
Parameters
----------
freq : float
central frequency of the wavelet
s_freq : int
sampling frequency
ratio : float
ra... | [
"def",
"morlet",
"(",
"freq",
",",
"s_freq",
",",
"ratio",
"=",
"5",
",",
"sigma_f",
"=",
"None",
",",
"dur_in_sd",
"=",
"4",
",",
"dur_in_s",
"=",
"None",
",",
"normalization",
"=",
"'peak'",
",",
"zero_mean",
"=",
"False",
")",
":",
"if",
"sigma_f"... | 35.564103 | 0.000351 |
def download_file(self, owner, id, file, **kwargs):
"""
Download file
This endpoint will return a file within the dataset as originally uploaded. If you are interested retrieving clean data extracted from those files by data.world, check out `GET:/sql` and `GET:/sparql`.
This method ma... | [
"def",
"download_file",
"(",
"self",
",",
"owner",
",",
"id",
",",
"file",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
... | 66.185185 | 0.003861 |
def getParam(xmlelement):
"""Converts an mzML xml element to a param tuple.
:param xmlelement: #TODO docstring
:returns: a param tuple or False if the xmlelement is not a parameter
('userParam', 'cvParam' or 'referenceableParamGroupRef')
"""
elementTag = clearTag(xmlelement.tag)
if ele... | [
"def",
"getParam",
"(",
"xmlelement",
")",
":",
"elementTag",
"=",
"clearTag",
"(",
"xmlelement",
".",
"tag",
")",
"if",
"elementTag",
"in",
"[",
"'userParam'",
",",
"'cvParam'",
",",
"'referenceableParamGroupRef'",
"]",
":",
"if",
"elementTag",
"==",
"'cvPara... | 35.789474 | 0.001433 |
def get(self, request, enterprise_customer_uuid):
"""
Handle GET request - render "Transmit courses metadata" form.
Arguments:
request (django.http.request.HttpRequest): Request instance
enterprise_customer_uuid (str): Enterprise Customer UUID
Returns:
... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"enterprise_customer_uuid",
")",
":",
"context",
"=",
"self",
".",
"_build_context",
"(",
"request",
",",
"enterprise_customer_uuid",
")",
"transmit_courses_metadata_form",
"=",
"TransmitEnterpriseCoursesForm",
"(",
")",... | 42.5625 | 0.00431 |
def _get_options_for_model(self, model, opts_class=None, **options):
"""
Returns an instance of translation options with translated fields
defined for the ``model`` and inherited from superclasses.
"""
if model not in self._registry:
# Create a new type for backwards ... | [
"def",
"_get_options_for_model",
"(",
"self",
",",
"model",
",",
"opts_class",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"if",
"model",
"not",
"in",
"self",
".",
"_registry",
":",
"# Create a new type for backwards compatibility.",
"opts",
"=",
"type",
... | 46.25 | 0.001765 |
def __info_yenczlib_gen(self):
"""Generator for the lines of a compressed info (textual) response.
Compressed responses are an extension to the NNTP protocol supported by
some usenet servers to reduce the bandwidth of heavily used range style
commands that can return large amounts of te... | [
"def",
"__info_yenczlib_gen",
"(",
"self",
")",
":",
"escape",
"=",
"0",
"dcrc32",
"=",
"0",
"inflate",
"=",
"zlib",
".",
"decompressobj",
"(",
"-",
"15",
")",
"# header",
"header",
"=",
"next",
"(",
"self",
".",
"__info_plain_gen",
"(",
")",
")",
"if"... | 34.65 | 0.001871 |
def on_click_dispatcher(self, module_name, event, command):
"""
Dispatch on_click config parameters to either:
- Our own methods for special py3status commands (listed below)
- The i3-msg program which is part of i3wm
"""
if command is None:
return
... | [
"def",
"on_click_dispatcher",
"(",
"self",
",",
"module_name",
",",
"event",
",",
"command",
")",
":",
"if",
"command",
"is",
"None",
":",
"return",
"elif",
"command",
"==",
"\"refresh_all\"",
":",
"self",
".",
"py3_wrapper",
".",
"refresh_modules",
"(",
")"... | 47.72 | 0.003287 |
def init_widget(self):
""" Initialize the underlying widget.
"""
super(AndroidViewAnimator, self).init_widget()
d = self.declaration
if d.animate_first_view:
self.set_animate_first_view(d.animate_first_view)
if d.displayed_child:
self.set_displaye... | [
"def",
"init_widget",
"(",
"self",
")",
":",
"super",
"(",
"AndroidViewAnimator",
",",
"self",
")",
".",
"init_widget",
"(",
")",
"d",
"=",
"self",
".",
"declaration",
"if",
"d",
".",
"animate_first_view",
":",
"self",
".",
"set_animate_first_view",
"(",
"... | 33.7 | 0.00578 |
def add_protocols(session, verbose):
"""Adds protocols"""
# 1. DEFINITIONS
enroll_session = [1]
client_probe_session = [2]
impostor_probe_session = [3]
protocols = ['A']
# 2. ADDITIONS TO THE SQL DATABASE
protocolPurpose_list = [('eval', 'enrol'), ('eval', 'probe')]
for proto in protocols:
p = P... | [
"def",
"add_protocols",
"(",
"session",
",",
"verbose",
")",
":",
"# 1. DEFINITIONS",
"enroll_session",
"=",
"[",
"1",
"]",
"client_probe_session",
"=",
"[",
"2",
"]",
"impostor_probe_session",
"=",
"[",
"3",
"]",
"protocols",
"=",
"[",
"'A'",
"]",
"# 2. ADD... | 37.711111 | 0.024698 |
def search(cls, term=None, page=0, **criteria):
"""
Search a list of the model
If you use "term":
- Returns a collection of people that have a name matching the term passed in through the URL.
If you use "criteria":
- returns people who match your search criteria.
... | [
"def",
"search",
"(",
"cls",
",",
"term",
"=",
"None",
",",
"page",
"=",
"0",
",",
"*",
"*",
"criteria",
")",
":",
"assert",
"(",
"term",
"or",
"criteria",
"and",
"not",
"(",
"term",
"and",
"criteria",
")",
")",
"params",
"=",
"{",
"'n'",
":",
... | 31.195122 | 0.003033 |
def tf_initialize(self, x_init, base_value, target_value, estimated_improvement):
"""
Initialization step preparing the arguments for the first iteration of the loop body.
Args:
x_init: Initial solution guess $x_0$.
base_value: Value $f(x')$ at $x = x'$.
targ... | [
"def",
"tf_initialize",
"(",
"self",
",",
"x_init",
",",
"base_value",
",",
"target_value",
",",
"estimated_improvement",
")",
":",
"self",
".",
"base_value",
"=",
"base_value",
"if",
"estimated_improvement",
"is",
"None",
":",
"# TODO: Is this a good alternative?",
... | 36.742857 | 0.004545 |
def get_root_path(import_name):
"""Returns the path to a package or cwd if that cannot be found. This
returns the path of a package or the folder that contains a module.
Not to be confused with the package path returned by :func:`find_package`.
"""
# Module already imported and has a file attribut... | [
"def",
"get_root_path",
"(",
"import_name",
")",
":",
"# Module already imported and has a file attribute. Use that first.",
"mod",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"import_name",
")",
"if",
"mod",
"is",
"not",
"None",
"and",
"hasattr",
"(",
"mod",
",... | 41.580645 | 0.000758 |
def find_missing_items(self, dtype):
"""
Find any items that are referenced in a child table
but are missing in their own table.
For example, a site that is listed in the samples table,
but has no entry in the sites table.
Parameters
----------
dtype : st... | [
"def",
"find_missing_items",
"(",
"self",
",",
"dtype",
")",
":",
"parent_dtype",
",",
"child_dtype",
"=",
"self",
".",
"get_parent_and_child",
"(",
"dtype",
")",
"if",
"not",
"child_dtype",
"in",
"self",
".",
"tables",
":",
"return",
"set",
"(",
")",
"ite... | 35.090909 | 0.005044 |
def regions(self):
""" Get a list of all regions
"""
regions = []
elem = self.dimensions["region"].elem
for option_elem in elem.find_all("option"):
region = option_elem.text.strip()
regions.append(region)
return regions | [
"def",
"regions",
"(",
"self",
")",
":",
"regions",
"=",
"[",
"]",
"elem",
"=",
"self",
".",
"dimensions",
"[",
"\"region\"",
"]",
".",
"elem",
"for",
"option_elem",
"in",
"elem",
".",
"find_all",
"(",
"\"option\"",
")",
":",
"region",
"=",
"option_ele... | 28.3 | 0.006849 |
def create_pipeline_field(self, pipeline_key, name, field_type, **kwargs):
'''Creates a pipeline field with the provided attributes.
Args:
pipeline_key specifying the pipeline to add the field to
name required name string
field_type required type string [TEXT_INPUT, DATE or PERSON]
kwargs {}
ret... | [
"def",
"create_pipeline_field",
"(",
"self",
",",
"pipeline_key",
",",
"name",
",",
"field_type",
",",
"*",
"*",
"kwargs",
")",
":",
"uri",
"=",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"api_uri",
",",
"self",
".",
"pipelines_suffix",
",",
"pipeline_ke... | 28.842105 | 0.04417 |
def recruit_participants(self, n=1):
"""Recruit n participants."""
auto_recruit = os.environ['auto_recruit'] == 'true'
if auto_recruit:
print "Starting Wallace's recruit_participants."
hit_id = str(
Participant.query.
with_entities(Parti... | [
"def",
"recruit_participants",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"auto_recruit",
"=",
"os",
".",
"environ",
"[",
"'auto_recruit'",
"]",
"==",
"'true'",
"if",
"auto_recruit",
":",
"print",
"\"Starting Wallace's recruit_participants.\"",
"hit_id",
"=",
"s... | 32.627907 | 0.001384 |
def run_nested_error_groups():
"""Run nested groups example where an error occurs in nested main phase.
In this example, the first main phase in the nested PhaseGroup errors out.
The other inner main phase is skipped, as is the outer main phase. Both
PhaseGroups were entered, so both teardown phases are run.
... | [
"def",
"run_nested_error_groups",
"(",
")",
":",
"test",
"=",
"htf",
".",
"Test",
"(",
"htf",
".",
"PhaseGroup",
"(",
"main",
"=",
"[",
"htf",
".",
"PhaseGroup",
".",
"with_teardown",
"(",
"inner_teardown_phase",
")",
"(",
"error_main_phase",
",",
"main_phas... | 32.555556 | 0.006633 |
def calc_checksum(self, expanded=False):
"""
Calculate the checksum(s) of the d_signal (expanded=False)
or e_d_signal field (expanded=True)
"""
if expanded:
cs = [int(np.sum(self.e_d_signal[ch]) % 65536) for ch in range(self.n_sig)]
else:
cs = np.s... | [
"def",
"calc_checksum",
"(",
"self",
",",
"expanded",
"=",
"False",
")",
":",
"if",
"expanded",
":",
"cs",
"=",
"[",
"int",
"(",
"np",
".",
"sum",
"(",
"self",
".",
"e_d_signal",
"[",
"ch",
"]",
")",
"%",
"65536",
")",
"for",
"ch",
"in",
"range",... | 35.818182 | 0.007426 |
def get_culprit(omit_top_frames=1):
"""get the filename and line number calling this.
Parameters
----------
omit_top_frames: int, default=1
omit n frames from top of stack stack. Purpose is to get the real
culprit and not intermediate functions on the stack.
Returns
-------
... | [
"def",
"get_culprit",
"(",
"omit_top_frames",
"=",
"1",
")",
":",
"try",
":",
"caller_stack",
"=",
"stack",
"(",
")",
"[",
"omit_top_frames",
":",
"]",
"while",
"len",
"(",
"caller_stack",
")",
">",
"0",
":",
"frame",
"=",
"caller_stack",
".",
"pop",
"... | 33.466667 | 0.002904 |
def delete(self, key: bytes) -> Tuple[Hash32]:
"""
Equals to setting the value to None
Returns all updated hashes in root->leaf order
"""
validate_is_bytes(key)
validate_length(key, self._key_size)
return self.set(key, self._default) | [
"def",
"delete",
"(",
"self",
",",
"key",
":",
"bytes",
")",
"->",
"Tuple",
"[",
"Hash32",
"]",
":",
"validate_is_bytes",
"(",
"key",
")",
"validate_length",
"(",
"key",
",",
"self",
".",
"_key_size",
")",
"return",
"self",
".",
"set",
"(",
"key",
",... | 31.333333 | 0.006897 |
def battery_voltage(self):
""" Returns voltage in mV """
msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG)
lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG)
voltage_bin = msb << 4 | lsb & 0x0f
return voltage_bin * 1.1 | [
"def",
"battery_voltage",
"(",
"self",
")",
":",
"msb",
"=",
"self",
".",
"bus",
".",
"read_byte_data",
"(",
"AXP209_ADDRESS",
",",
"BATTERY_VOLTAGE_MSB_REG",
")",
"lsb",
"=",
"self",
".",
"bus",
".",
"read_byte_data",
"(",
"AXP209_ADDRESS",
",",
"BATTERY_VOLT... | 49 | 0.006689 |
def ketbra(i, j, Ne):
"""This function returns the outer product :math:`|i><j|` where\
:math:`|i>` and :math:`|j>` are elements of the canonical basis of an\
Ne-dimensional Hilbert space (in matrix form).
>>> ketbra(2, 3, 3)
Matrix([
[0, 0, 0],
[0, 0, 1],
[0, 0, 0]])
"""
return ket(i... | [
"def",
"ketbra",
"(",
"i",
",",
"j",
",",
"Ne",
")",
":",
"return",
"ket",
"(",
"i",
",",
"Ne",
")",
"*",
"bra",
"(",
"j",
",",
"Ne",
")"
] | 24.923077 | 0.002976 |
def physical_conversion(quantity,pop=False):
"""Decorator to convert to physical coordinates:
quantity = [position,velocity,time]"""
def wrapper(method):
@wraps(method)
def wrapped(*args,**kwargs):
use_physical= kwargs.get('use_physical',True) and \
not kwargs.ge... | [
"def",
"physical_conversion",
"(",
"quantity",
",",
"pop",
"=",
"False",
")",
":",
"def",
"wrapper",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"use_physical",
"="... | 46.281437 | 0.014946 |
def GetMethodConfig(self, method):
"""Returns service cached method config for given method."""
method_config = self._method_configs.get(method)
if method_config:
return method_config
func = getattr(self, method, None)
if func is None:
raise KeyError(metho... | [
"def",
"GetMethodConfig",
"(",
"self",
",",
"method",
")",
":",
"method_config",
"=",
"self",
".",
"_method_configs",
".",
"get",
"(",
"method",
")",
"if",
"method_config",
":",
"return",
"method_config",
"func",
"=",
"getattr",
"(",
"self",
",",
"method",
... | 40.461538 | 0.003717 |
def set_sim_data(inj, field, data):
"""Sets data of a SimInspiral instance."""
try:
sim_field = sim_inspiral_map[field]
except KeyError:
sim_field = field
# for tc, map to geocentric times
if sim_field == 'tc':
inj.geocent_end_time = int(data)
inj.geocent_end_time_ns ... | [
"def",
"set_sim_data",
"(",
"inj",
",",
"field",
",",
"data",
")",
":",
"try",
":",
"sim_field",
"=",
"sim_inspiral_map",
"[",
"field",
"]",
"except",
"KeyError",
":",
"sim_field",
"=",
"field",
"# for tc, map to geocentric times",
"if",
"sim_field",
"==",
"'t... | 31.5 | 0.002571 |
def get_phonetic_feature_vector(self, c, lang):
"""For a given character in a language, it gathers all the information related to it
(eg: whether fricative, plosive,etc)"""
offset = self.get_offset(c, lang)
if not self.in_coordinated_range_offset(offset):
return self.inval... | [
"def",
"get_phonetic_feature_vector",
"(",
"self",
",",
"c",
",",
"lang",
")",
":",
"offset",
"=",
"self",
".",
"get_offset",
"(",
"c",
",",
"lang",
")",
"if",
"not",
"self",
".",
"in_coordinated_range_offset",
"(",
"offset",
")",
":",
"return",
"self",
... | 38.133333 | 0.005119 |
def write(self, filename):
"""Write the XML job description to a file."""
txt = self.tostring()
with open(filename, 'w') as f:
f.write(txt) | [
"def",
"write",
"(",
"self",
",",
"filename",
")",
":",
"txt",
"=",
"self",
".",
"tostring",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"txt",
")"
] | 34.2 | 0.011429 |
def detect_images_and_galleries(generators):
"""Runs generator on both pages and articles."""
for generator in generators:
if isinstance(generator, ArticlesGenerator):
for article in itertools.chain(generator.articles, generator.translations, generator.drafts):
detect_image(g... | [
"def",
"detect_images_and_galleries",
"(",
"generators",
")",
":",
"for",
"generator",
"in",
"generators",
":",
"if",
"isinstance",
"(",
"generator",
",",
"ArticlesGenerator",
")",
":",
"for",
"article",
"in",
"itertools",
".",
"chain",
"(",
"generator",
".",
... | 57.363636 | 0.00468 |
def bio_read(self, bufsiz):
"""
If the Connection was created with a memory BIO, this method can be
used to read bytes from the write end of that memory BIO. Many
Connection methods will add bytes which must be read in this manner or
the buffer will eventually fill up and the Co... | [
"def",
"bio_read",
"(",
"self",
",",
"bufsiz",
")",
":",
"if",
"self",
".",
"_from_ssl",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"\"Connection sock was not None\"",
")",
"if",
"not",
"isinstance",
"(",
"bufsiz",
",",
"integer_types",
")",
":",
"raise",... | 39.304348 | 0.00216 |
def authorize_get(self, session, fields=[]):
'''taobao.itemcats.authorize.get 查询B商家被授权品牌列表和类目列表'''
sellerAuthorize = SellerAuthorize()
request = TOPRequest('taobao.authorize.get')
if not fields:
fields = sellerAuthorize.fields
request['fields'] = ','.join(fields)
... | [
"def",
"authorize_get",
"(",
"self",
",",
"session",
",",
"fields",
"=",
"[",
"]",
")",
":",
"sellerAuthorize",
"=",
"SellerAuthorize",
"(",
")",
"request",
"=",
"TOPRequest",
"(",
"'taobao.authorize.get'",
")",
"if",
"not",
"fields",
":",
"fields",
"=",
"... | 44 | 0.00495 |
def get_project_items(pronac):
"""
Returns all items from a project.
"""
df = data.all_items
return (
df[df['PRONAC'] == pronac]
.drop(columns=['PRONAC', 'idSegmento'])
) | [
"def",
"get_project_items",
"(",
"pronac",
")",
":",
"df",
"=",
"data",
".",
"all_items",
"return",
"(",
"df",
"[",
"df",
"[",
"'PRONAC'",
"]",
"==",
"pronac",
"]",
".",
"drop",
"(",
"columns",
"=",
"[",
"'PRONAC'",
",",
"'idSegmento'",
"]",
")",
")"... | 22.444444 | 0.004762 |
def polarization_vector(phi, theta, alpha, beta, p,
numeric=False, abstract=False):
"""This function returns a unitary vector describing the polarization
of plane waves.:
INPUT:
- ``phi`` - The spherical coordinates azimuthal angle of the wave vector\
k.
- ``theta`` - Th... | [
"def",
"polarization_vector",
"(",
"phi",
",",
"theta",
",",
"alpha",
",",
"beta",
",",
"p",
",",
"numeric",
"=",
"False",
",",
"abstract",
"=",
"False",
")",
":",
"if",
"abstract",
":",
"Nl",
"=",
"symbols",
"(",
"\"N_l\"",
",",
"integer",
"=",
"Tru... | 30.3 | 0.000355 |
def list_create(self, title):
"""
Create a new list with the given `title`.
Returns the `list dict`_ of the created list.
"""
params = self.__generate_params(locals())
return self.__api_request('POST', '/api/v1/lists', params) | [
"def",
"list_create",
"(",
"self",
",",
"title",
")",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"'/api/v1/lists'",
",",
"params",
")"
] | 34.5 | 0.010601 |
def device_mapping(cuda_device: int):
"""
In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),
you have to supply a `map_location` function. Call this with
the desired `cuda_device` to get the function that `torch.load()` needs.
"""
def inner_device_mapping(storage: torc... | [
"def",
"device_mapping",
"(",
"cuda_device",
":",
"int",
")",
":",
"def",
"inner_device_mapping",
"(",
"storage",
":",
"torch",
".",
"Storage",
",",
"location",
")",
"->",
"torch",
".",
"Storage",
":",
"# pylint: disable=unused-argument",
"if",
"cuda_device",
">... | 37.714286 | 0.005545 |
def field(self, well_x=1, well_y=1, field_x=1, field_y=1):
"""ScanFieldData of specified field.
Parameters
----------
well_x : int
well_y : int
field_x : int
field_y : int
Returns
-------
lxml.objectify.ObjectifiedElement
Scan... | [
"def",
"field",
"(",
"self",
",",
"well_x",
"=",
"1",
",",
"well_y",
"=",
"1",
",",
"field_x",
"=",
"1",
",",
"field_y",
"=",
"1",
")",
":",
"xpath",
"=",
"'./ScanFieldArray/ScanFieldData'",
"xpath",
"+=",
"_xpath_attrib",
"(",
"'WellX'",
",",
"well_x",
... | 30 | 0.002937 |
def create_executable_script(filepath, body, program=None):
"""Create an executable script.
Args:
filepath (str): File to create.
body (str or callable): Contents of the script. If a callable, its code
is used as the script body.
program (str): Name of program to launch the ... | [
"def",
"create_executable_script",
"(",
"filepath",
",",
"body",
",",
"program",
"=",
"None",
")",
":",
"program",
"=",
"program",
"or",
"\"python\"",
"if",
"callable",
"(",
"body",
")",
":",
"from",
"rez",
".",
"utils",
".",
"sourcecode",
"import",
"Sourc... | 37.9 | 0.003431 |
def get_mesh_name(mesh_id, offline=False):
"""Get the MESH label for the given MESH ID.
Uses the mappings table in `indra/resources`; if the MESH ID is not listed
there, falls back on the NLM REST API.
Parameters
----------
mesh_id : str
MESH Identifier, e.g. 'D003094'.
offline : b... | [
"def",
"get_mesh_name",
"(",
"mesh_id",
",",
"offline",
"=",
"False",
")",
":",
"indra_mesh_mapping",
"=",
"mesh_id_to_name",
".",
"get",
"(",
"mesh_id",
")",
"if",
"offline",
"or",
"indra_mesh_mapping",
"is",
"not",
"None",
":",
"return",
"indra_mesh_mapping",
... | 33.423077 | 0.002237 |
def compile(self, session=None):
"""
Compile is two phase operation: at first it calls `build` method and then
intializes the node for passed session. The policy around `session` is defined
inside the `initialize` method.
:param session: TensorFlow session used for initializing.... | [
"def",
"compile",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"session",
"=",
"self",
".",
"enquire_session",
"(",
"session",
")",
"if",
"self",
".",
"is_built_coherence",
"(",
"session",
".",
"graph",
")",
"is",
"Build",
".",
"NO",
":",
"with"... | 45.176471 | 0.007653 |
def find_value_in_object(attr, obj):
"""Return values for any key coincidence with attr in obj or any other
nested dict.
"""
# Carry on inspecting inside the list or tuple
if isinstance(obj, (collections.Iterator, list)):
for item in obj:
yield from find_value_in_object(attr, it... | [
"def",
"find_value_in_object",
"(",
"attr",
",",
"obj",
")",
":",
"# Carry on inspecting inside the list or tuple",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"collections",
".",
"Iterator",
",",
"list",
")",
")",
":",
"for",
"item",
"in",
"obj",
":",
"yield",
... | 32.9 | 0.000984 |
def _select_tts_engine(self):
"""
Select the TTS engine to be used by looking at the rconf object.
"""
self.log(u"Selecting TTS engine...")
requested_tts_engine = self.rconf[RuntimeConfiguration.TTS]
if requested_tts_engine == self.CUSTOM:
self.log(u"TTS engin... | [
"def",
"_select_tts_engine",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Selecting TTS engine...\"",
")",
"requested_tts_engine",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TTS",
"]",
"if",
"requested_tts_engine",
"==",
"self",
".",
"C... | 55.339623 | 0.005025 |
def shift(self, delta):
"""Shift this `Series` forward on the X-axis by ``delta``
This modifies the series in-place.
Parameters
----------
delta : `float`, `~astropy.units.Quantity`, `str`
The amount by which to shift (in x-axis units if `float`), give
a... | [
"def",
"shift",
"(",
"self",
",",
"delta",
")",
":",
"self",
".",
"x0",
"=",
"self",
".",
"x0",
"+",
"Quantity",
"(",
"delta",
",",
"self",
".",
"xunit",
")"
] | 28.833333 | 0.002797 |
def get_manifest_and_response(self, alias):
"""
Request the manifest for an alias and return the manifest and the
response.
:param alias: Alias name.
:type alias: str
:rtype: tuple
:returns: Tuple containing the manifest as a string (JSON) and the `requests.Resp... | [
"def",
"get_manifest_and_response",
"(",
"self",
",",
"alias",
")",
":",
"r",
"=",
"self",
".",
"_request",
"(",
"'get'",
",",
"'manifests/'",
"+",
"alias",
",",
"headers",
"=",
"{",
"'Accept'",
":",
"_schema2_mimetype",
"+",
"', '",
"+",
"_schema1_mimetype"... | 40.75 | 0.005997 |
def with_start_after(self, after_namespace):
"""Returns a copy of this NamespaceName with a new namespace_start.
Args:
after_namespace: A namespace string.
Returns:
A NamespaceRange object whose namespace_start is the lexographically next
namespace after the given namespace string.
... | [
"def",
"with_start_after",
"(",
"self",
",",
"after_namespace",
")",
":",
"namespace_start",
"=",
"_ord_to_namespace",
"(",
"_namespace_to_ord",
"(",
"after_namespace",
")",
"+",
"1",
")",
"return",
"NamespaceRange",
"(",
"namespace_start",
",",
"self",
".",
"name... | 36.866667 | 0.001764 |
def update_forum_votes(sender, **kwargs):
"""
When a Vote is added, re-saves the topic or post to update vote count.
Since Votes can be assigned
to any content type, first makes sure we are dealing with a forum post or topic.
Deprecated 1-6-14 by storing score as cached property
"""
... | [
"def",
"update_forum_votes",
"(",
"sender",
",",
"*",
"*",
"kwargs",
")",
":",
"vote",
"=",
"kwargs",
"[",
"'instance'",
"]",
"if",
"vote",
".",
"content_type",
".",
"app_label",
"!=",
"\"fretboard\"",
":",
"return",
"if",
"vote",
".",
"content_type",
".",... | 40.842105 | 0.002519 |
def recombine(self, other, d=0.7):
"""
Genetic recombination of two themes using cut and splice technique.
"""
a, b = self, other
d1 = max(0, min(d, 1))
d2 = d1
c = ColorTheme(
name=a.name[:int(len(a.name) * d1)] +
b.name[int(len(b.na... | [
"def",
"recombine",
"(",
"self",
",",
"other",
",",
"d",
"=",
"0.7",
")",
":",
"a",
",",
"b",
"=",
"self",
",",
"other",
"d1",
"=",
"max",
"(",
"0",
",",
"min",
"(",
"d",
",",
"1",
")",
")",
"d2",
"=",
"d1",
"c",
"=",
"ColorTheme",
"(",
"... | 33.571429 | 0.005517 |
def _make_info(shape_list, num_classes):
"""Create an info-like tuple for feature given some shapes and vocab size."""
feature_info = collections.namedtuple("FeatureInfo", ["shape", "num_classes"])
cur_shape = list(shape_list[0])
# We need to merge the provided shapes, put None where they disagree.
for shape ... | [
"def",
"_make_info",
"(",
"shape_list",
",",
"num_classes",
")",
":",
"feature_info",
"=",
"collections",
".",
"namedtuple",
"(",
"\"FeatureInfo\"",
",",
"[",
"\"shape\"",
",",
"\"num_classes\"",
"]",
")",
"cur_shape",
"=",
"list",
"(",
"shape_list",
"[",
"0",... | 47.384615 | 0.017516 |
def set(self, value):
'''
Atomically sets the value to `value`.
:param value: The value to set.
'''
with self._lock.exclusive:
self._value = value
return value | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"with",
"self",
".",
"_lock",
".",
"exclusive",
":",
"self",
".",
"_value",
"=",
"value",
"return",
"value"
] | 24 | 0.008929 |
def _get_pypirc_command(self):
"""
Get the distutils command for interacting with PyPI configurations.
:return: the command.
"""
from distutils.core import Distribution
from distutils.config import PyPIRCCommand
d = Distribution()
return PyPIRCCommand(d) | [
"def",
"_get_pypirc_command",
"(",
"self",
")",
":",
"from",
"distutils",
".",
"core",
"import",
"Distribution",
"from",
"distutils",
".",
"config",
"import",
"PyPIRCCommand",
"d",
"=",
"Distribution",
"(",
")",
"return",
"PyPIRCCommand",
"(",
"d",
")"
] | 34.444444 | 0.006289 |
def fit_mle(self, data, fix_mean=False):
"""%(super)s
Additional Parameters
----------------------
fix_mean : bool
Default False. If True, fixes mean before optimizing sigma
"""
if not fix_mean:
sigma, _, scale = stats.lognorm.fit(data, floc=0)... | [
"def",
"fit_mle",
"(",
"self",
",",
"data",
",",
"fix_mean",
"=",
"False",
")",
":",
"if",
"not",
"fix_mean",
":",
"sigma",
",",
"_",
",",
"scale",
"=",
"stats",
".",
"lognorm",
".",
"fit",
"(",
"data",
",",
"floc",
"=",
"0",
")",
"return",
"np",... | 30.16 | 0.006427 |
def open_only(f):
"decorator"
@functools.wraps(f)
def f2(self, *args, **kwargs):
if self.closed: raise NotSupportedError('connection is closed')
return f(self, *args, **kwargs)
return f2 | [
"def",
"open_only",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"f2",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"NotSupportedError",
"(",
"'connection ... | 28 | 0.029703 |
def reset(self):
"""
Empties all internal storage containers
"""
self.X = []
self.Y = []
self.w = []
self.Xnorm = []
self.graph_rep = None | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"X",
"=",
"[",
"]",
"self",
".",
"Y",
"=",
"[",
"]",
"self",
".",
"w",
"=",
"[",
"]",
"self",
".",
"Xnorm",
"=",
"[",
"]",
"self",
".",
"graph_rep",
"=",
"None"
] | 18 | 0.009615 |
def splunk_version(self):
"""Returns the version of the splunkd instance this object is attached
to.
The version is returned as a tuple of the version components as
integers (for example, `(4,3,3)` or `(5,)`).
:return: A ``tuple`` of ``integers``.
"""
if self._s... | [
"def",
"splunk_version",
"(",
"self",
")",
":",
"if",
"self",
".",
"_splunk_version",
"is",
"None",
":",
"self",
".",
"_splunk_version",
"=",
"tuple",
"(",
"[",
"int",
"(",
"p",
")",
"for",
"p",
"in",
"self",
".",
"info",
"[",
"'version'",
"]",
".",
... | 38.25 | 0.006383 |
def copy(self, **attributes):
"""Create a copy of this message.
"""
updated_options = attributes.pop("options", {})
options = self.options.copy()
options.update(updated_options)
return self._replace(**attributes, options=options) | [
"def",
"copy",
"(",
"self",
",",
"*",
"*",
"attributes",
")",
":",
"updated_options",
"=",
"attributes",
".",
"pop",
"(",
"\"options\"",
",",
"{",
"}",
")",
"options",
"=",
"self",
".",
"options",
".",
"copy",
"(",
")",
"options",
".",
"update",
"(",... | 38.714286 | 0.00722 |
def group_encrypt(self, groupid, message):
"""
:param groupid:
:type groupid: str
:param message:
:type message: bytes
:return:
:rtype:
"""
logger.debug("group_encrypt(groupid=%s, message=%s)" % (groupid, message))
group_cipher = self._get_... | [
"def",
"group_encrypt",
"(",
"self",
",",
"groupid",
",",
"message",
")",
":",
"logger",
".",
"debug",
"(",
"\"group_encrypt(groupid=%s, message=%s)\"",
"%",
"(",
"groupid",
",",
"message",
")",
")",
"group_cipher",
"=",
"self",
".",
"_get_group_cipher",
"(",
... | 35.416667 | 0.006881 |
def _parse_template_vars(self):
""" find all template variables in self._code, excluding the
function name.
"""
template_vars = set()
for var in parsing.find_template_variables(self._code):
var = var.lstrip('$')
if var == self.name:
contin... | [
"def",
"_parse_template_vars",
"(",
"self",
")",
":",
"template_vars",
"=",
"set",
"(",
")",
"for",
"var",
"in",
"parsing",
".",
"find_template_variables",
"(",
"self",
".",
"_code",
")",
":",
"var",
"=",
"var",
".",
"lstrip",
"(",
"'$'",
")",
"if",
"v... | 37.785714 | 0.00738 |
def coerce(cls, arg):
"""Given an arg, return the appropriate value given the class."""
try:
return cls(arg).value
except (ValueError, TypeError):
raise InvalidParameterDatatype("%s coerce error" % (cls.__name__,)) | [
"def",
"coerce",
"(",
"cls",
",",
"arg",
")",
":",
"try",
":",
"return",
"cls",
"(",
"arg",
")",
".",
"value",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"raise",
"InvalidParameterDatatype",
"(",
"\"%s coerce error\"",
"%",
"(",
"cls",
".",... | 42.833333 | 0.007634 |
def p_chr(p):
""" string : CHR arg_list
"""
if len(p[2]) < 1:
syntax_error(p.lineno(1), "CHR$ function need at less 1 parameter")
p[0] = None
return
for i in range(len(p[2])): # Convert every argument to 8bit unsigned
p[2][i].value = make_typecast(TYPE.ubyte, p[2][i].va... | [
"def",
"p_chr",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
"[",
"2",
"]",
")",
"<",
"1",
":",
"syntax_error",
"(",
"p",
".",
"lineno",
"(",
"1",
")",
",",
"\"CHR$ function need at less 1 parameter\"",
")",
"p",
"[",
"0",
"]",
"=",
"None",
"return",... | 33 | 0.002457 |
def reset (self):
"""Reset all log statistics to default values."""
# number of logged URLs
self.number = 0
# number of encountered URL errors
self.errors = 0
# number of URL errors that were printed
self.errors_printed = 0
# number of URL warnings
... | [
"def",
"reset",
"(",
"self",
")",
":",
"# number of logged URLs",
"self",
".",
"number",
"=",
"0",
"# number of encountered URL errors",
"self",
".",
"errors",
"=",
"0",
"# number of URL errors that were printed",
"self",
".",
"errors_printed",
"=",
"0",
"# number of ... | 33.347826 | 0.003802 |
def run(uri,
user_entry_point,
args,
env_vars=None,
wait=True,
capture_error=False,
runner=_runner.ProcessRunnerType,
extra_opts=None):
# type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None
"""Download, prepa... | [
"def",
"run",
"(",
"uri",
",",
"user_entry_point",
",",
"args",
",",
"env_vars",
"=",
"None",
",",
"wait",
"=",
"True",
",",
"capture_error",
"=",
"False",
",",
"runner",
"=",
"_runner",
".",
"ProcessRunnerType",
",",
"extra_opts",
"=",
"None",
")",
":",... | 46.044118 | 0.006254 |
def rest(url, req="GET", data=None):
"""Main function to be called from this module.
send a request using method 'req' and to the url. the _rest() function
will add the base_url to this, so 'url' should be something like '/ips'.
"""
load_variables()
return _rest(base_url + url, req, data) | [
"def",
"rest",
"(",
"url",
",",
"req",
"=",
"\"GET\"",
",",
"data",
"=",
"None",
")",
":",
"load_variables",
"(",
")",
"return",
"_rest",
"(",
"base_url",
"+",
"url",
",",
"req",
",",
"data",
")"
] | 34.111111 | 0.003175 |
def open_channel_with_funding(
self,
registry_address_hex,
token_address_hex,
peer_address_hex,
total_deposit,
settle_timeout=None,
):
""" Convenience method to open a channel.
Args:
registry_address_hex (str): hex ... | [
"def",
"open_channel_with_funding",
"(",
"self",
",",
"registry_address_hex",
",",
"token_address_hex",
",",
"peer_address_hex",
",",
"total_deposit",
",",
"settle_timeout",
"=",
"None",
",",
")",
":",
"# Check, if peer is discoverable",
"registry_address",
"=",
"decode_h... | 35 | 0.004525 |
def changelog(since, to, write, force):
"""
Generates a markdown file containing the list of checks that changed for a
given Agent release. Agent version numbers are derived inspecting tags on
`integrations-core` so running this tool might provide unexpected results
if the repo is not up to date wit... | [
"def",
"changelog",
"(",
"since",
",",
"to",
",",
"write",
",",
"force",
")",
":",
"agent_tags",
"=",
"get_agent_tags",
"(",
"since",
",",
"to",
")",
"# store the changes in a mapping {agent_version --> {check_name --> current_version}}",
"changes_per_agent",
"=",
"Orde... | 45.957447 | 0.002719 |
def deploy_deb(self,
file_name,
distribution,
component,
architecture,
parameters={}):
"""
Convenience method to deploy .deb packages
Keyword arguments:
file_name -- full path to local file th... | [
"def",
"deploy_deb",
"(",
"self",
",",
"file_name",
",",
"distribution",
",",
"component",
",",
"architecture",
",",
"parameters",
"=",
"{",
"}",
")",
":",
"params",
"=",
"{",
"'deb.distribution'",
":",
"distribution",
",",
"'deb.component'",
":",
"component",... | 33.583333 | 0.008444 |
def jobs_insert_query(self, sql, code=None, imports=None, table_name=None, append=False,
overwrite=False, dry_run=False, use_cache=True, batch=True,
allow_large_results=False, table_definitions=None, dialect=None,
billing_tier=None):
"""Issues ... | [
"def",
"jobs_insert_query",
"(",
"self",
",",
"sql",
",",
"code",
"=",
"None",
",",
"imports",
"=",
"None",
",",
"table_name",
"=",
"None",
",",
"append",
"=",
"False",
",",
"overwrite",
"=",
"False",
",",
"dry_run",
"=",
"False",
",",
"use_cache",
"="... | 42.035294 | 0.006836 |
def displayMousePosition(xOffset=0, yOffset=0):
"""This function is meant to be run from the command line. It will
automatically display the location and RGB of the mouse cursor."""
print('Press Ctrl-C to quit.')
if xOffset != 0 or yOffset != 0:
print('xOffset: %s yOffset: %s' % (xOffset, yOffse... | [
"def",
"displayMousePosition",
"(",
"xOffset",
"=",
"0",
",",
"yOffset",
"=",
"0",
")",
":",
"print",
"(",
"'Press Ctrl-C to quit.'",
")",
"if",
"xOffset",
"!=",
"0",
"or",
"yOffset",
"!=",
"0",
":",
"print",
"(",
"'xOffset: %s yOffset: %s'",
"%",
"(",
"xO... | 48.12 | 0.002445 |
def _raise_error_if_column_exists(dataset, column_name = 'dataset',
dataset_variable_name = 'dataset',
column_name_error_message_name = 'column_name'):
"""
Check if a column exists in an SFrame with error message.
"""
err_msg = 'The SFrame {0} must... | [
"def",
"_raise_error_if_column_exists",
"(",
"dataset",
",",
"column_name",
"=",
"'dataset'",
",",
"dataset_variable_name",
"=",
"'dataset'",
",",
"column_name_error_message_name",
"=",
"'column_name'",
")",
":",
"err_msg",
"=",
"'The SFrame {0} must contain the column {1}.'"... | 52.727273 | 0.018644 |
def load_modules(self):
"""Should instance interfaces and set them to interface, following `modules`"""
if self.INTERFACES_MODULE is None:
raise NotImplementedError("A module containing interfaces modules "
"should be setup in INTERFACES_MODULE !")
... | [
"def",
"load_modules",
"(",
"self",
")",
":",
"if",
"self",
".",
"INTERFACES_MODULE",
"is",
"None",
":",
"raise",
"NotImplementedError",
"(",
"\"A module containing interfaces modules \"",
"\"should be setup in INTERFACES_MODULE !\"",
")",
"else",
":",
"for",
"module",
... | 53.9 | 0.005474 |
def sample(self, bqm, **parameters):
"""Cutoff and sample from the provided binary quadratic model.
Removes interactions smaller than a given cutoff. Isolated
variables (after the cutoff) are also removed.
Note that if the problem had isolated variables before the cutoff, they
... | [
"def",
"sample",
"(",
"self",
",",
"bqm",
",",
"*",
"*",
"parameters",
")",
":",
"child",
"=",
"self",
".",
"child",
"cutoff",
"=",
"self",
".",
"_cutoff",
"cutoff_vartype",
"=",
"self",
".",
"_cutoff_vartype",
"comp",
"=",
"self",
".",
"_comparison",
... | 37.727273 | 0.00274 |
def print_continuum(self):
"""Prints a ketama compatible continuum report.
"""
numpoints = len(self.runtime._keys)
if numpoints:
print('Numpoints in continuum: {}'.format(numpoints))
else:
print('Continuum empty')
for p in self.get_points():
... | [
"def",
"print_continuum",
"(",
"self",
")",
":",
"numpoints",
"=",
"len",
"(",
"self",
".",
"runtime",
".",
"_keys",
")",
"if",
"numpoints",
":",
"print",
"(",
"'Numpoints in continuum: {}'",
".",
"format",
"(",
"numpoints",
")",
")",
"else",
":",
"print",... | 34.545455 | 0.005128 |
def _get_album_or_image(json, imgur):
"""Return a gallery image/album depending on what the json represent."""
if json['is_album']:
return Gallery_album(json, imgur, has_fetched=False)
return Gallery_image(json, imgur) | [
"def",
"_get_album_or_image",
"(",
"json",
",",
"imgur",
")",
":",
"if",
"json",
"[",
"'is_album'",
"]",
":",
"return",
"Gallery_album",
"(",
"json",
",",
"imgur",
",",
"has_fetched",
"=",
"False",
")",
"return",
"Gallery_image",
"(",
"json",
",",
"imgur",... | 46.8 | 0.004202 |
def load_matrix_sparse(filename):
coo = np.load(filename)
"""Check if coo is (M, 3) ndarray"""
if len(coo.shape) == 2 and coo.shape[1] == 3:
row = coo[:, 0]
col = coo[:, 1]
values = coo[:, 2]
"""Check if imaginary part of row and col is zero"""
if np.all(np.isreal(r... | [
"def",
"load_matrix_sparse",
"(",
"filename",
")",
":",
"coo",
"=",
"np",
".",
"load",
"(",
"filename",
")",
"if",
"len",
"(",
"coo",
".",
"shape",
")",
"==",
"2",
"and",
"coo",
".",
"shape",
"[",
"1",
"]",
"==",
"3",
":",
"row",
"=",
"coo",
"[... | 35.633333 | 0.001821 |
def to_operator(self):
"""Convert to Operator object."""
# Place import here to avoid cyclic import from circuit visualization
from qiskit.quantum_info.operators.operator import Operator
return Operator(self.to_matrix()) | [
"def",
"to_operator",
"(",
"self",
")",
":",
"# Place import here to avoid cyclic import from circuit visualization",
"from",
"qiskit",
".",
"quantum_info",
".",
"operators",
".",
"operator",
"import",
"Operator",
"return",
"Operator",
"(",
"self",
".",
"to_matrix",
"("... | 49.6 | 0.007937 |
def all(self):
""" Returns list with all indexed datasets. """
datasets = []
query = text("""
SELECT vid
FROM dataset_index;""")
for result in self.execute(query):
res = DatasetSearchResult()
res.vid = result[0]
res.b_score = ... | [
"def",
"all",
"(",
"self",
")",
":",
"datasets",
"=",
"[",
"]",
"query",
"=",
"text",
"(",
"\"\"\"\n SELECT vid\n FROM dataset_index;\"\"\"",
")",
"for",
"result",
"in",
"self",
".",
"execute",
"(",
"query",
")",
":",
"res",
"=",
"Dataset... | 26.071429 | 0.005291 |
def create_model_from_job(self, training_job_name, name=None, role=None, primary_container_image=None,
model_data_url=None, env=None, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT):
"""Create an Amazon SageMaker ``Model`` from a SageMaker Training Job.
Args:
... | [
"def",
"create_model_from_job",
"(",
"self",
",",
"training_job_name",
",",
"name",
"=",
"None",
",",
"role",
"=",
"None",
",",
"primary_container_image",
"=",
"None",
",",
"model_data_url",
"=",
"None",
",",
"env",
"=",
"None",
",",
"vpc_config_override",
"="... | 65.909091 | 0.007703 |
def _log_tc_proxy(self):
"""Log the proxy settings."""
if self.default_args.tc_proxy_tc:
self.log.info(
u'Proxy Server (TC): {}:{}.'.format(
self.default_args.tc_proxy_host, self.default_args.tc_proxy_port
)
) | [
"def",
"_log_tc_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"default_args",
".",
"tc_proxy_tc",
":",
"self",
".",
"log",
".",
"info",
"(",
"u'Proxy Server (TC): {}:{}.'",
".",
"format",
"(",
"self",
".",
"default_args",
".",
"tc_proxy_host",
",",
"self... | 36.75 | 0.009967 |
def cancel(self):
"""
Cancels running jobs. The job ids are read from the submission file which has to exist
for obvious reasons.
"""
task = self.task
# get job ids from submission data
job_ids = [
d["job_id"] for d in self.submission_data.jobs.values... | [
"def",
"cancel",
"(",
"self",
")",
":",
"task",
"=",
"self",
".",
"task",
"# get job ids from submission data",
"job_ids",
"=",
"[",
"d",
"[",
"\"job_id\"",
"]",
"for",
"d",
"in",
"self",
".",
"submission_data",
".",
"jobs",
".",
"values",
"(",
")",
"if"... | 37.657143 | 0.003698 |
def new_ph_pic(cls, id_, name, desc, rId):
"""
Return a new `p:pic` placeholder element populated with the supplied
parameters.
"""
return parse_xml(
cls._pic_ph_tmpl() % (id_, name, desc, rId)
) | [
"def",
"new_ph_pic",
"(",
"cls",
",",
"id_",
",",
"name",
",",
"desc",
",",
"rId",
")",
":",
"return",
"parse_xml",
"(",
"cls",
".",
"_pic_ph_tmpl",
"(",
")",
"%",
"(",
"id_",
",",
"name",
",",
"desc",
",",
"rId",
")",
")"
] | 31 | 0.007843 |
def parse_xml_node(self, node):
'''Parse an xml.dom Node object representing a location into this
object.
'''
self.x = int(node.getAttributeNS(RTS_EXT_NS, 'x'))
self.y = int(node.getAttributeNS(RTS_EXT_NS, 'y'))
self.height = int(node.getAttributeNS(RTS_EXT_NS, 'height')... | [
"def",
"parse_xml_node",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"x",
"=",
"int",
"(",
"node",
".",
"getAttributeNS",
"(",
"RTS_EXT_NS",
",",
"'x'",
")",
")",
"self",
".",
"y",
"=",
"int",
"(",
"node",
".",
"getAttributeNS",
"(",
"RTS_EXT_NS... | 41.666667 | 0.005871 |
def callCount(cls, spy, number): #pylint: disable=invalid-name
"""
Checking the inspector is called number times
Args: SinonSpy, number
"""
cls.__is_spy(spy)
if not (spy.callCount == number):
raise cls.failException(cls.message) | [
"def",
"callCount",
"(",
"cls",
",",
"spy",
",",
"number",
")",
":",
"#pylint: disable=invalid-name",
"cls",
".",
"__is_spy",
"(",
"spy",
")",
"if",
"not",
"(",
"spy",
".",
"callCount",
"==",
"number",
")",
":",
"raise",
"cls",
".",
"failException",
"(",... | 35.125 | 0.013889 |
def _SeriesFactory(ser):
"""
Return an instance of the appropriate subclass of _BaseSeries based on the
xChart element *ser* appears in.
"""
xChart_tag = ser.getparent().tag
try:
SeriesCls = {
qn('c:areaChart'): AreaSeries,
qn('c:barChart'): BarSeries,
... | [
"def",
"_SeriesFactory",
"(",
"ser",
")",
":",
"xChart_tag",
"=",
"ser",
".",
"getparent",
"(",
")",
".",
"tag",
"try",
":",
"SeriesCls",
"=",
"{",
"qn",
"(",
"'c:areaChart'",
")",
":",
"AreaSeries",
",",
"qn",
"(",
"'c:barChart'",
")",
":",
"BarSeries... | 31.583333 | 0.00128 |
def remove_function_signature_type_comment(body):
"""Removes the legacy signature type comment, leaving other comments if any."""
for node in body.children:
if node.type == token.INDENT:
prefix = node.prefix.lstrip()
if prefix.startswith('# type: '):
node.prefix =... | [
"def",
"remove_function_signature_type_comment",
"(",
"body",
")",
":",
"for",
"node",
"in",
"body",
".",
"children",
":",
"if",
"node",
".",
"type",
"==",
"token",
".",
"INDENT",
":",
"prefix",
"=",
"node",
".",
"prefix",
".",
"lstrip",
"(",
")",
"if",
... | 45.625 | 0.005376 |
def _validate_num_qubits(state: np.ndarray) -> int:
"""Validates that state's size is a power of 2, returning number of qubits.
"""
size = state.size
if size & (size - 1):
raise ValueError('state.size ({}) is not a power of two.'.format(size))
return size.bit_length() - 1 | [
"def",
"_validate_num_qubits",
"(",
"state",
":",
"np",
".",
"ndarray",
")",
"->",
"int",
":",
"size",
"=",
"state",
".",
"size",
"if",
"size",
"&",
"(",
"size",
"-",
"1",
")",
":",
"raise",
"ValueError",
"(",
"'state.size ({}) is not a power of two.'",
".... | 42 | 0.003333 |
def _get_summary_struct(self):
"""
Returns a structured description of the model, including (where relevant)
the schema of the training data, description of the training data,
training statistics, and model hyperparameters.
Returns
-------
sections : list (of lis... | [
"def",
"_get_summary_struct",
"(",
"self",
")",
":",
"section_titles",
"=",
"[",
"'Schema'",
",",
"'Settings'",
"]",
"vocab_length",
"=",
"len",
"(",
"self",
".",
"vocabulary",
")",
"verbose",
"=",
"self",
".",
"verbose",
"==",
"1",
"sections",
"=",
"[",
... | 36.777778 | 0.006623 |
def show_raslog_output_show_all_raslog_raslog_entries_message_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
output = ET.SubElement(show_raslog, "output")
show_all_raslog = ... | [
"def",
"show_raslog_output_show_all_raslog_raslog_entries_message_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_raslog",
"=",
"ET",
".",
"Element",
"(",
"\"show_raslog\"",
")",
"config",
"... | 44.857143 | 0.00468 |
def addColor(self, level, text):
'''addColor to the prompt (usually prefix) if terminal
supports, and specified to do so'''
if self.colorize:
if level in self.colors:
text = "%s%s%s" % (self.colors[level],
text,
... | [
"def",
"addColor",
"(",
"self",
",",
"level",
",",
"text",
")",
":",
"if",
"self",
".",
"colorize",
":",
"if",
"level",
"in",
"self",
".",
"colors",
":",
"text",
"=",
"\"%s%s%s\"",
"%",
"(",
"self",
".",
"colors",
"[",
"level",
"]",
",",
"text",
... | 40.555556 | 0.005362 |
def hard_limit_remote(self,
yidx,
ridx,
rtype='y',
rmin=None,
rmax=None,
min_yset=0,
max_yset=0):
"""Limit the output of yidx if t... | [
"def",
"hard_limit_remote",
"(",
"self",
",",
"yidx",
",",
"ridx",
",",
"rtype",
"=",
"'y'",
",",
"rmin",
"=",
"None",
",",
"rmax",
"=",
"None",
",",
"min_yset",
"=",
"0",
",",
"max_yset",
"=",
"0",
")",
":",
"ny",
"=",
"len",
"(",
"yidx",
")",
... | 34.711111 | 0.005604 |
def get_python_argv(self):
"""
Return the initial argument vector elements necessary to invoke Python,
by returning a 1-element list containing :attr:`python_path` if it is a
string, or simply returning it if it is already a list.
This allows emulation of existing tools where th... | [
"def",
"get_python_argv",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"python_path",
",",
"list",
")",
":",
"return",
"self",
".",
"python_path",
"return",
"[",
"self",
".",
"python_path",
"]"
] | 42.833333 | 0.00381 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.