text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def list_all_before(self, message_id, limit=None):
"""Return all group messages created before a message.
:param str message_id: the ID of a message
:param int limit: maximum number of messages per page
:return: group messages
:rtype: generator
"""
return self.li... | [
"def",
"list_all_before",
"(",
"self",
",",
"message_id",
",",
"limit",
"=",
"None",
")",
":",
"return",
"self",
".",
"list_before",
"(",
"message_id",
",",
"limit",
"=",
"limit",
")",
".",
"autopage",
"(",
")"
] | 39.666667 | 0.005479 |
def reindex_repo_dev_panel(self, project, repository):
"""
Reindex all of the Jira issues related to this repository, including branches and pull requests.
This automatically happens as part of an upgrade, and calling this manually should only be required
if something unforeseen happens ... | [
"def",
"reindex_repo_dev_panel",
"(",
"self",
",",
"project",
",",
"repository",
")",
":",
"url",
"=",
"'rest/jira-dev/1.0/projects/{projectKey}/repos/{repositorySlug}/reindex'",
".",
"format",
"(",
"projectKey",
"=",
"project",
",",
"repositorySlug",
"=",
"repository",
... | 61.692308 | 0.0086 |
def intersperse(lis, value):
"""Put value between each existing item in list.
Parameters
----------
lis : list
List to intersperse.
value : object
Value to insert.
Returns
-------
list
interspersed list
"""
out = [value] * (len(lis) * 2 - 1)
out[0::2... | [
"def",
"intersperse",
"(",
"lis",
",",
"value",
")",
":",
"out",
"=",
"[",
"value",
"]",
"*",
"(",
"len",
"(",
"lis",
")",
"*",
"2",
"-",
"1",
")",
"out",
"[",
"0",
":",
":",
"2",
"]",
"=",
"lis",
"return",
"out"
] | 18.055556 | 0.002924 |
def set_weather(self, weather_type):
"""Queue up a set weather command. It will be applied when `tick` or `step` is called next.
By the next tick, the lighting, skysphere, fog, and relevant particle systems will be updated and/or spawned
to the given weather. If there is no skysphere or directio... | [
"def",
"set_weather",
"(",
"self",
",",
"weather_type",
")",
":",
"if",
"not",
"SetWeatherCommand",
".",
"has_type",
"(",
"weather_type",
".",
"lower",
"(",
")",
")",
":",
"raise",
"HolodeckException",
"(",
"\"Invalid weather type \"",
"+",
"weather_type",
")",
... | 58.190476 | 0.007246 |
def check_unused(intersection, duplicates, intersections):
"""Check if a "valid" ``intersection`` is already in ``intersections``.
This assumes that
* ``intersection`` will have at least one of ``s == 0.0`` or ``t == 0.0``
* At least one of the intersections in ``intersections`` is classified as
... | [
"def",
"check_unused",
"(",
"intersection",
",",
"duplicates",
",",
"intersections",
")",
":",
"for",
"other",
"in",
"intersections",
":",
"if",
"(",
"other",
".",
"interior_curve",
"==",
"UNUSED_T",
"and",
"intersection",
".",
"index_first",
"==",
"other",
".... | 35.575758 | 0.000829 |
def _split_url_string(param_str):
"""Turn URL string into parameters."""
if not PY3:
# If passed unicode with quoted UTF8, Python2's parse_qs leaves
# mojibake'd uniocde after unquoting, so encode first.
param_str = b(param_str, 'utf-8')
parameters = parse_qs(... | [
"def",
"_split_url_string",
"(",
"param_str",
")",
":",
"if",
"not",
"PY3",
":",
"# If passed unicode with quoted UTF8, Python2's parse_qs leaves",
"# mojibake'd uniocde after unquoting, so encode first.",
"param_str",
"=",
"b",
"(",
"param_str",
",",
"'utf-8'",
")",
"paramet... | 43.384615 | 0.003472 |
def get_settings(self, index=None, name=None, params=None):
"""
Retrieve settings for one or more (or all) indices.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-settings.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
... | [
"def",
"get_settings",
"(",
"self",
",",
"index",
"=",
"None",
",",
"name",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"return",
"self",
".",
"transport",
".",
"perform_request",
"(",
"\"GET\"",
",",
"_make_path",
"(",
"index",
",",
"\"_settings\... | 57.6 | 0.002732 |
def _sync(original, processed):
"""
Add output to data if run sucessfully.
For now only macs2 is available, so no need
to consider multiple callers.
"""
for original_sample in original:
original_sample[0]["peaks_files"] = {}
for process_sample in processed:
if dd.get_... | [
"def",
"_sync",
"(",
"original",
",",
"processed",
")",
":",
"for",
"original_sample",
"in",
"original",
":",
"original_sample",
"[",
"0",
"]",
"[",
"\"peaks_files\"",
"]",
"=",
"{",
"}",
"for",
"process_sample",
"in",
"processed",
":",
"if",
"dd",
".",
... | 40.571429 | 0.003442 |
def list(self,walkTrace=tuple(),case=None,element=None):
"""List section titles.
"""
if case == 'sectionmain': print(walkTrace,self.title) | [
"def",
"list",
"(",
"self",
",",
"walkTrace",
"=",
"tuple",
"(",
")",
",",
"case",
"=",
"None",
",",
"element",
"=",
"None",
")",
":",
"if",
"case",
"==",
"'sectionmain'",
":",
"print",
"(",
"walkTrace",
",",
"self",
".",
"title",
")"
] | 39.75 | 0.04321 |
def doc(self):
"""Docstring of property on target or override specified on PV-object."""
return self._pv.doc or inspect.getdoc(
getattr(type(self._target), self._pv.property, None)) or '' | [
"def",
"doc",
"(",
"self",
")",
":",
"return",
"self",
".",
"_pv",
".",
"doc",
"or",
"inspect",
".",
"getdoc",
"(",
"getattr",
"(",
"type",
"(",
"self",
".",
"_target",
")",
",",
"self",
".",
"_pv",
".",
"property",
",",
"None",
")",
")",
"or",
... | 53 | 0.013953 |
def _parse_format(self, format):
"""
Converts the input format to a regular
expression, as well as extracting fields
Raises an exception if it couldn't compile
the generated regex.
"""
format = format.strip()
format = re.sub('[ \t]+',' ',format)
... | [
"def",
"_parse_format",
"(",
"self",
",",
"format",
")",
":",
"format",
"=",
"format",
".",
"strip",
"(",
")",
"format",
"=",
"re",
".",
"sub",
"(",
"'[ \\t]+'",
",",
"' '",
",",
"format",
")",
"subpatterns",
"=",
"[",
"]",
"findquotes",
"=",
"re",
... | 33.086207 | 0.007591 |
def choose_spot_zone(zones, bid, spot_history):
"""
Returns the zone to put the spot request based on, in order of priority:
1) zones with prices currently under the bid
2) zones with the most stable price
:param list[boto.ec2.zone.Zone] zones:
:param float bid:
:param list[boto.ec2... | [
"def",
"choose_spot_zone",
"(",
"zones",
",",
"bid",
",",
"spot_history",
")",
":",
"# Create two lists of tuples of form: [(zone.name, std_deviation), ...] one for zones",
"# over the bid price and one for zones under bid price. Each are sorted by increasing",
"# standard deviation values."... | 43.745455 | 0.002846 |
def selected_display_item(self) -> typing.Optional[DisplayItem.DisplayItem]:
"""Return the selected display item.
The selected display is the display ite that has keyboard focus in the data panel or a display panel.
"""
# first check for the [focused] data browser
display_item =... | [
"def",
"selected_display_item",
"(",
"self",
")",
"->",
"typing",
".",
"Optional",
"[",
"DisplayItem",
".",
"DisplayItem",
"]",
":",
"# first check for the [focused] data browser",
"display_item",
"=",
"self",
".",
"focused_display_item",
"if",
"not",
"display_item",
... | 50.636364 | 0.007055 |
def filter_products(self, desired_prods):
"""When asked for a product, filter only those on this list."""
self.filter_prods = True
self.desired_prods = set(desired_prods) | [
"def",
"filter_products",
"(",
"self",
",",
"desired_prods",
")",
":",
"self",
".",
"filter_prods",
"=",
"True",
"self",
".",
"desired_prods",
"=",
"set",
"(",
"desired_prods",
")"
] | 38.2 | 0.010256 |
def read_frames(self, copy=True):
'''Iterate over the data frames from our C3D file handle.
Parameters
----------
copy : bool
If False, the reader returns a reference to the same data buffers
for every frame. The default is True, which causes the reader to
... | [
"def",
"read_frames",
"(",
"self",
",",
"copy",
"=",
"True",
")",
":",
"scale",
"=",
"abs",
"(",
"self",
".",
"point_scale",
")",
"is_float",
"=",
"self",
".",
"point_scale",
"<",
"0",
"point_bytes",
"=",
"[",
"2",
",",
"4",
"]",
"[",
"is_float",
"... | 42.395833 | 0.001441 |
def check_api_version(self):
"""
Self check that the client expects the api version used by the
server. /status/ is available without authentication so it
will not interfere with hello.
"""
url = self.base_url + "/status/"
juicer.utils.Log.log_debug("[REST:GET:%s]... | [
"def",
"check_api_version",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"/status/\"",
"juicer",
".",
"utils",
".",
"Log",
".",
"log_debug",
"(",
"\"[REST:GET:%s]\"",
",",
"url",
")",
"_r",
"=",
"requests",
".",
"get",
"(",
"url",
... | 48.166667 | 0.006787 |
def pixel(self, func:PixelFunc, *args, **kwargs)->'Image':
"Equivalent to `image.px = func(image.px)`."
self.px = func(self.px, *args, **kwargs)
return self | [
"def",
"pixel",
"(",
"self",
",",
"func",
":",
"PixelFunc",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"'Image'",
":",
"self",
".",
"px",
"=",
"func",
"(",
"self",
".",
"px",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
... | 44.25 | 0.022222 |
def getArguments(names, local_dict=None, global_dict=None):
"""Get the arguments based on the names."""
call_frame = sys._getframe(2)
clear_local_dict = False
if local_dict is None:
local_dict = call_frame.f_locals
clear_local_dict = True
try:
frame_globals = call_frame.f_gl... | [
"def",
"getArguments",
"(",
"names",
",",
"local_dict",
"=",
"None",
",",
"global_dict",
"=",
"None",
")",
":",
"call_frame",
"=",
"sys",
".",
"_getframe",
"(",
"2",
")",
"clear_local_dict",
"=",
"False",
"if",
"local_dict",
"is",
"None",
":",
"local_dict"... | 35.25 | 0.004314 |
def map_routes(
feed: "Feed",
route_ids: List[str],
date: Optional[str] = None,
color_palette: List[str] = cs.COLORS_SET2,
*,
include_stops: bool = True,
):
"""
Return a Folium map showing the given routes and (optionally)
their stops.
Parameters
----------
feed : Feed
... | [
"def",
"map_routes",
"(",
"feed",
":",
"\"Feed\"",
",",
"route_ids",
":",
"List",
"[",
"str",
"]",
",",
"date",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"color_palette",
":",
"List",
"[",
"str",
"]",
"=",
"cs",
".",
"COLORS_SET2",
",",
"... | 27.903846 | 0.000333 |
def parse_keyvalue(parser, event, node): #pylint: disable=unused-argument
"""Parse CIM/CML KEYVALUE element and return key value based on
VALUETYPE or TYPE (future) information
"""
valuetype = _get_required_attribute(node, 'VALUETYPE')
# TODO 2/16 KS: Type attribute not used. Extend to use. Ty... | [
"def",
"parse_keyvalue",
"(",
"parser",
",",
"event",
",",
"node",
")",
":",
"#pylint: disable=unused-argument",
"valuetype",
"=",
"_get_required_attribute",
"(",
"node",
",",
"'VALUETYPE'",
")",
"# TODO 2/16 KS: Type attribute not used. Extend to use. Type was late",
"# ... | 29.508197 | 0.001613 |
def check_predict_status(self, view_id, predict_request_id):
"""
Returns a string indicating the status of the prediction job
:param view_id: The data view id returned from data view create
:param predict_request_id: The id returned from predict
:return: Status data, also includ... | [
"def",
"check_predict_status",
"(",
"self",
",",
"view_id",
",",
"predict_request_id",
")",
":",
"failure_message",
"=",
"\"Get status on predict failed\"",
"bare_response",
"=",
"self",
".",
"_get_success_json",
"(",
"self",
".",
"_get",
"(",
"'v1/data_views/'",
"+",... | 38.789474 | 0.003974 |
def check_errors(self, response):
" Check some common errors."
# Read content.
content = response.content
if 'status' not in content:
raise self.GeneralError('We expect a status field.')
# Return the decoded content if status is success.
if content['status'... | [
"def",
"check_errors",
"(",
"self",
",",
"response",
")",
":",
"# Read content.",
"content",
"=",
"response",
".",
"content",
"if",
"'status'",
"not",
"in",
"content",
":",
"raise",
"self",
".",
"GeneralError",
"(",
"'We expect a status field.'",
")",
"# Return ... | 31.512195 | 0.002252 |
def delete(self, features, make_backup=True, **kwargs):
"""
Delete features from database.
features : str, iterable, FeatureDB instance
If FeatureDB, all features will be used. If string, assume it's the
ID of the feature to remove. Otherwise, assume it's an iterable of
... | [
"def",
"delete",
"(",
"self",
",",
"features",
",",
"make_backup",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"make_backup",
":",
"if",
"isinstance",
"(",
"self",
".",
"dbfn",
",",
"six",
".",
"string_types",
")",
":",
"shutil",
".",
"copy... | 34.8 | 0.001242 |
def setInverted(self, state):
"""
Sets whether or not to invert the check state for collapsing.
:param state | <bool>
"""
collapsed = self.isCollapsed()
self._inverted = state
if self.isCollapsible():
self.setCollapsed(collapsed) | [
"def",
"setInverted",
"(",
"self",
",",
"state",
")",
":",
"collapsed",
"=",
"self",
".",
"isCollapsed",
"(",
")",
"self",
".",
"_inverted",
"=",
"state",
"if",
"self",
".",
"isCollapsible",
"(",
")",
":",
"self",
".",
"setCollapsed",
"(",
"collapsed",
... | 31.1 | 0.009375 |
def levels(self, with_mem=True):
"""Return cache levels, optionally including main memory."""
p = self.first_level
while p is not None:
yield p
# FIXME bad hack to include victim caches, need a more general solution, probably
# involving recursive tree walking... | [
"def",
"levels",
"(",
"self",
",",
"with_mem",
"=",
"True",
")",
":",
"p",
"=",
"self",
".",
"first_level",
"while",
"p",
"is",
"not",
"None",
":",
"yield",
"p",
"# FIXME bad hack to include victim caches, need a more general solution, probably",
"# involving recursiv... | 42.133333 | 0.006192 |
def set_resolved_url(self, item=None, subtitles=None):
'''Takes a url or a listitem to be played. Used in conjunction with a
playable list item with a path that calls back into your addon.
:param item: A playable list item or url. Pass None to alert XBMC of a
failure to res... | [
"def",
"set_resolved_url",
"(",
"self",
",",
"item",
"=",
"None",
",",
"subtitles",
"=",
"None",
")",
":",
"if",
"self",
".",
"_end_of_directory",
":",
"raise",
"Exception",
"(",
"'Current XBMC handle has been removed. Either '",
"'set_resolved_url(), end_of_directory()... | 43.756098 | 0.001091 |
def ends_with(self, other):
'''(<) Ends with a specified parser, and at the end parser hasn't consumed
any input.'''
@Parser
def ends_with_parser(text, index):
res = self(text, index)
if not res.status:
return res
end = other(text, res.... | [
"def",
"ends_with",
"(",
"self",
",",
"other",
")",
":",
"@",
"Parser",
"def",
"ends_with_parser",
"(",
"text",
",",
"index",
")",
":",
"res",
"=",
"self",
"(",
"text",
",",
"index",
")",
"if",
"not",
"res",
".",
"status",
":",
"return",
"res",
"en... | 35.857143 | 0.007767 |
def get_owner(self, default=True):
"""Return (User ID, Group ID) tuple
:param bool default: Whether to return default if not set.
:rtype: tuple[int, int]
"""
uid, gid = self.owner
if not uid and default:
uid = os.getuid()
if not gid and default:
... | [
"def",
"get_owner",
"(",
"self",
",",
"default",
"=",
"True",
")",
":",
"uid",
",",
"gid",
"=",
"self",
".",
"owner",
"if",
"not",
"uid",
"and",
"default",
":",
"uid",
"=",
"os",
".",
"getuid",
"(",
")",
"if",
"not",
"gid",
"and",
"default",
":",... | 23.8 | 0.005391 |
def remove_whitespace(text_string):
'''
Removes all whitespace found within text_string and returns new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a string or NoneType not be passed as an argument
'''
if text_st... | [
"def",
"remove_whitespace",
"(",
"text_string",
")",
":",
"if",
"text_string",
"is",
"None",
"or",
"text_string",
"==",
"\"\"",
":",
"return",
"\"\"",
"elif",
"isinstance",
"(",
"text_string",
",",
"str",
")",
":",
"return",
"\" \"",
".",
"join",
"(",
"tex... | 29.055556 | 0.005556 |
def all_solidity_variables_used_as_args(self):
"""
Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender)
"""
if self._all_solidity_variables_used_as_args is None:
self._all_solid... | [
"def",
"all_solidity_variables_used_as_args",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_solidity_variables_used_as_args",
"is",
"None",
":",
"self",
".",
"_all_solidity_variables_used_as_args",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"se... | 47.090909 | 0.007576 |
def targets(self, module):
"""Find the targets for a given module.
Returns:
list: A sequence of all of the targets for the specified module.
"""
if module not in self.module_targets:
raise BuildError("Could not find module in targets()", module=module)
... | [
"def",
"targets",
"(",
"self",
",",
"module",
")",
":",
"if",
"module",
"not",
"in",
"self",
".",
"module_targets",
":",
"raise",
"BuildError",
"(",
"\"Could not find module in targets()\"",
",",
"module",
"=",
"module",
")",
"return",
"[",
"self",
".",
"fin... | 34.181818 | 0.007772 |
def workflow(
graph: BELGraph,
node: BaseEntity,
key: Optional[str] = None,
tag: Optional[str] = None,
default_score: Optional[float] = None,
runs: Optional[int] = None,
minimum_nodes: int = 1,
) -> List['Runner']:
"""Generate candidate mechanisms and run the ... | [
"def",
"workflow",
"(",
"graph",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
",",
"key",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"tag",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"default_score",
":",
"Optional",
"[",
"float... | 44.071429 | 0.005551 |
def _repr_html_(self, **kwargs):
"""Displays the HTML Map in a Jupyter notebook."""
if self._parent is None:
self.add_to(Figure())
out = self._parent._repr_html_(**kwargs)
self._parent = None
else:
out = self._parent._repr_html_(**kwargs)
r... | [
"def",
"_repr_html_",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"_parent",
"is",
"None",
":",
"self",
".",
"add_to",
"(",
"Figure",
"(",
")",
")",
"out",
"=",
"self",
".",
"_parent",
".",
"_repr_html_",
"(",
"*",
"*",
"kw... | 35.666667 | 0.006079 |
def locked_context(self, key=None, default=dict):
""" Executor context is a shared memory object. All workers share this.
It needs a lock. Its used like this:
with executor.context() as context:
visited = context['visited']
visited.append(state.cpu.PC)
... | [
"def",
"locked_context",
"(",
"self",
",",
"key",
"=",
"None",
",",
"default",
"=",
"dict",
")",
":",
"assert",
"default",
"in",
"(",
"list",
",",
"dict",
",",
"set",
")",
"with",
"self",
".",
"_lock",
":",
"if",
"key",
"is",
"None",
":",
"yield",
... | 39.684211 | 0.002591 |
def store_sentry(self, username, sentry_bytes):
"""
Store sentry bytes under a username
:param username: username
:type username: :class:`str`
:return: Whenver the operation succeed
:rtype: :class:`bool`
"""
filepath = self._get_sentry_path(username)
... | [
"def",
"store_sentry",
"(",
"self",
",",
"username",
",",
"sentry_bytes",
")",
":",
"filepath",
"=",
"self",
".",
"_get_sentry_path",
"(",
"username",
")",
"if",
"filepath",
":",
"try",
":",
"with",
"open",
"(",
"filepath",
",",
"'wb'",
")",
"as",
"f",
... | 29.947368 | 0.003407 |
def add_tag(self, tag):
""" add a tag to the tag list """
if tag not in self._tags:
self._tags[tag] = dict() | [
"def",
"add_tag",
"(",
"self",
",",
"tag",
")",
":",
"if",
"tag",
"not",
"in",
"self",
".",
"_tags",
":",
"self",
".",
"_tags",
"[",
"tag",
"]",
"=",
"dict",
"(",
")"
] | 33.25 | 0.014706 |
def iterate(self, src, tgt, update=True, training=True):
"""
Performs one iteration of the training/validation.
:param src: batch of examples from the source language
:param tgt: batch of examples from the target language
:param update: if True: optimizer does update of the weig... | [
"def",
"iterate",
"(",
"self",
",",
"src",
",",
"tgt",
",",
"update",
"=",
"True",
",",
"training",
"=",
"True",
")",
":",
"src",
",",
"src_length",
"=",
"src",
"tgt",
",",
"tgt_length",
"=",
"tgt",
"src_length",
"=",
"torch",
".",
"LongTensor",
"(",... | 34.347826 | 0.001231 |
def OnButtonCell(self, event):
"""Event handler for cell button toggle button"""
if self.button_cell_button_id == event.GetId():
if event.IsChecked():
label = self._get_button_label()
post_command_event(self, self.ButtonCellMsg, text=label)
else:
... | [
"def",
"OnButtonCell",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"button_cell_button_id",
"==",
"event",
".",
"GetId",
"(",
")",
":",
"if",
"event",
".",
"IsChecked",
"(",
")",
":",
"label",
"=",
"self",
".",
"_get_button_label",
"(",
")"... | 36.727273 | 0.004831 |
def fsdecode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None):
'''
Decode given path.
:param path: path will be decoded if using bytes
:type path: bytes or str
:param os_name: operative system name, defaults to os.name
:type os_name: str
:param fs_encoding: current filesystem en... | [
"def",
"fsdecode",
"(",
"path",
",",
"os_name",
"=",
"os",
".",
"name",
",",
"fs_encoding",
"=",
"FS_ENCODING",
",",
"errors",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"bytes",
")",
":",
"return",
"path",
"if",
"not",
"erro... | 34.210526 | 0.001497 |
def main(command_line=True, **kwargs):
"""
NAME
pmd_magic.py
DESCRIPTION
converts PMD (Enkin) format files to magic_measurements format files
SYNTAX
pmd_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-f FILE: specify input... | [
"def",
"main",
"(",
"command_line",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# initialize some stuff",
"noave",
"=",
"0",
"inst",
"=",
"\"\"",
"samp_con",
",",
"Z",
"=",
"'1'",
",",
"\"\"",
"missing",
"=",
"1",
"demag",
"=",
"\"N\"",
"er_locati... | 38.388889 | 0.021065 |
def up(self):
"""
Function operates on the IMCInterface object and configures the interface into an
administratively up state and refreshes contents of self.adminstatus
:return:
"""
set_interface_up(self.ifIndex, self.auth, self.url, devip=... | [
"def",
"up",
"(",
"self",
")",
":",
"set_interface_up",
"(",
"self",
".",
"ifIndex",
",",
"self",
".",
"auth",
",",
"self",
".",
"url",
",",
"devip",
"=",
"self",
".",
"ip",
")",
"self",
".",
"adminstatus",
"=",
"get_interface_details",
"(",
"self",
... | 50.111111 | 0.010893 |
def reserve_file(self, relative_path):
"""reserve a XML file for the slice at <relative_path>.xml
- the relative path will be created for you
- not writing anything to that file is an error
"""
if os.path.isabs(relative_path):
raise ValueError('%s must be a relative ... | [
"def",
"reserve_file",
"(",
"self",
",",
"relative_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"relative_path",
")",
":",
"raise",
"ValueError",
"(",
"'%s must be a relative path'",
"%",
"relative_path",
")",
"dest_path",
"=",
"os",
".",
"pa... | 34.125 | 0.002375 |
def initialize_tracer(self, io_loop=None):
"""
Initialize Jaeger Tracer based on the passed `jaeger_client.Config`.
Save it to `opentracing.tracer` global variable.
Only the first call to this method has any effect.
"""
with Config._initialized_lock:
if Confi... | [
"def",
"initialize_tracer",
"(",
"self",
",",
"io_loop",
"=",
"None",
")",
":",
"with",
"Config",
".",
"_initialized_lock",
":",
"if",
"Config",
".",
"_initialized",
":",
"logger",
".",
"warn",
"(",
"'Jaeger tracer already initialized, skipping'",
")",
"return",
... | 33.882353 | 0.003378 |
def apply_M(self, ax, ay):
"""Linear operator that converts ax, ay to abcd.
"""
jac = numpy.array(
[[self.dx.dot(ax), self.dy.dot(ax)], [self.dx.dot(ay), self.dy.dot(ay)]]
)
# jacs and J are of shape (2, 2, k). M must be of the same shape and
# contain the re... | [
"def",
"apply_M",
"(",
"self",
",",
"ax",
",",
"ay",
")",
":",
"jac",
"=",
"numpy",
".",
"array",
"(",
"[",
"[",
"self",
".",
"dx",
".",
"dot",
"(",
"ax",
")",
",",
"self",
".",
"dy",
".",
"dot",
"(",
"ax",
")",
"]",
",",
"[",
"self",
"."... | 34.916667 | 0.002322 |
def main_crop():
"""This function does the real work. It is called by main() in
pdfCropMargins.py, which just handles catching exceptions and cleaning up."""
##
## Process some of the command-line arguments.
##
if args.verbose:
print("\nProcessing the PDF with pdfCropMargins (version"... | [
"def",
"main_crop",
"(",
")",
":",
"##",
"## Process some of the command-line arguments.",
"##",
"if",
"args",
".",
"verbose",
":",
"print",
"(",
"\"\\nProcessing the PDF with pdfCropMargins (version\"",
",",
"__version__",
"+",
"\")...\"",
")",
"print",
"(",
"\"System ... | 47.45328 | 0.008001 |
def _lookup_model(cls, kind, default_model=None):
"""Get the model class for the kind.
Args:
kind: A string representing the name of the kind to lookup.
default_model: The model class to use if the kind can't be found.
Returns:
The model class for the requested kind.
Raises:
Ki... | [
"def",
"_lookup_model",
"(",
"cls",
",",
"kind",
",",
"default_model",
"=",
"None",
")",
":",
"modelclass",
"=",
"cls",
".",
"_kind_map",
".",
"get",
"(",
"kind",
",",
"default_model",
")",
"if",
"modelclass",
"is",
"None",
":",
"raise",
"KindError",
"("... | 33.333333 | 0.003241 |
def redirect_to_express(self):
"""
First step of ExpressCheckout. Redirect the request to PayPal using the
data returned from setExpressCheckout.
"""
wpp = PayPalWPP(self.request)
try:
nvp_obj = wpp.setExpressCheckout(self.item)
except PayPalFailure:
... | [
"def",
"redirect_to_express",
"(",
"self",
")",
":",
"wpp",
"=",
"PayPalWPP",
"(",
"self",
".",
"request",
")",
"try",
":",
"nvp_obj",
"=",
"wpp",
".",
"setExpressCheckout",
"(",
"self",
".",
"item",
")",
"except",
"PayPalFailure",
":",
"warn_untested",
"(... | 38.214286 | 0.005474 |
def ib_group_member_add(self, group_id, userids):
''' ib group member add '''
req_hook = 'pod/v1/admin/group/' + group_id + '/membership/add'
req_args = {'usersListId': userids}
req_args = json.dumps(req_args)
status_code, response = self.__rest__.POST_query(req_hook, req_args)
... | [
"def",
"ib_group_member_add",
"(",
"self",
",",
"group_id",
",",
"userids",
")",
":",
"req_hook",
"=",
"'pod/v1/admin/group/'",
"+",
"group_id",
"+",
"'/membership/add'",
"req_args",
"=",
"{",
"'usersListId'",
":",
"userids",
"}",
"req_args",
"=",
"json",
".",
... | 51.25 | 0.004796 |
def active_power(self):
"""
Takes the sum of all instantaneous active power values
Returns them in kWh
Returns
-------
float
"""
inst = self.load_instantaneous()
values = [float(i['value']) for i in inst if i['key'].endswith('ActivePower')]
... | [
"def",
"active_power",
"(",
"self",
")",
":",
"inst",
"=",
"self",
".",
"load_instantaneous",
"(",
")",
"values",
"=",
"[",
"float",
"(",
"i",
"[",
"'value'",
"]",
")",
"for",
"i",
"in",
"inst",
"if",
"i",
"[",
"'key'",
"]",
".",
"endswith",
"(",
... | 28 | 0.008646 |
def delete_translation(self, language_code, related_name=None):
"""
Delete a translation from a model.
:param language_code: The language to remove.
:param related_name: If given, only the model matching that related_name is removed.
"""
if language_code is None:
... | [
"def",
"delete_translation",
"(",
"self",
",",
"language_code",
",",
"related_name",
"=",
"None",
")",
":",
"if",
"language_code",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"get_null_language_error",
"(",
")",
")",
"if",
"related_name",
"is",
"None",
":",... | 33.560976 | 0.003531 |
def imwrite(img, file_path, params=None, auto_mkdir=True):
"""Write image to file
Args:
img (ndarray): Image array to be written.
file_path (str): Image file path.
params (None or list): Same as opencv's :func:`imwrite` interface.
auto_mkdir (bool): If the parent folder of `file... | [
"def",
"imwrite",
"(",
"img",
",",
"file_path",
",",
"params",
"=",
"None",
",",
"auto_mkdir",
"=",
"True",
")",
":",
"if",
"auto_mkdir",
":",
"dir_name",
"=",
"osp",
".",
"abspath",
"(",
"osp",
".",
"dirname",
"(",
"file_path",
")",
")",
"mkdir_or_exi... | 34.294118 | 0.001669 |
def _partial_search_validator(self, sub, sup, anagram=False,
subsequence=False, supersequence=False):
"""
It's responsible for validating the partial results of `search` method.
If it returns True, the search would return its result. Else, search
method ... | [
"def",
"_partial_search_validator",
"(",
"self",
",",
"sub",
",",
"sup",
",",
"anagram",
"=",
"False",
",",
"subsequence",
"=",
"False",
",",
"supersequence",
"=",
"False",
")",
":",
"def",
"get_all_in",
"(",
"one",
",",
"another",
")",
":",
"for",
"elem... | 39.08046 | 0.001147 |
def devnull():
"""Temporarily redirect stdout and stderr to /dev/null."""
try:
original_stderr = os.dup(sys.stderr.fileno())
original_stdout = os.dup(sys.stdout.fileno())
null = open(os.devnull, 'w')
os.dup2(null.fileno(), sys.stderr.fileno())
os.dup2(null.fileno(), sys.... | [
"def",
"devnull",
"(",
")",
":",
"try",
":",
"original_stderr",
"=",
"os",
".",
"dup",
"(",
"sys",
".",
"stderr",
".",
"fileno",
"(",
")",
")",
"original_stdout",
"=",
"os",
".",
"dup",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
")",
"nu... | 33.166667 | 0.001629 |
def get_prep_value(self, value):
""" Return the integer value to be stored from the hex string """
if value is None or value == "":
return None
if isinstance(value, six.string_types):
value = _hex_string_to_unsigned_integer(value)
if _using_signed_storage():
value = _unsigned_to_signed_integer(value)
... | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"value",
"==",
"\"\"",
":",
"return",
"None",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"_hex_string_to_unsi... | 36.111111 | 0.03003 |
def _percent(data, part, total):
"""
Calculate a percentage.
"""
try:
return round(100 * float(data[part]) / float(data[total]), 1)
except ZeroDivisionError:
return 0 | [
"def",
"_percent",
"(",
"data",
",",
"part",
",",
"total",
")",
":",
"try",
":",
"return",
"round",
"(",
"100",
"*",
"float",
"(",
"data",
"[",
"part",
"]",
")",
"/",
"float",
"(",
"data",
"[",
"total",
"]",
")",
",",
"1",
")",
"except",
"ZeroD... | 24.375 | 0.00495 |
def ResultCollectionForFID(cls, flow_id):
"""Returns the ResultCollection for the flow with a given flow_id.
Args:
flow_id: The id of the flow, a RDFURN of the form aff4:/flows/F:123456.
Returns:
The collection containing the results for the flow identified by the id.
"""
# TODO: Disal... | [
"def",
"ResultCollectionForFID",
"(",
"cls",
",",
"flow_id",
")",
":",
"# TODO: Disallow/remove URNs after migration.",
"if",
"not",
"isinstance",
"(",
"flow_id",
",",
"rdfvalue",
".",
"RDFURN",
")",
":",
"flow_id",
"=",
"rdfvalue",
".",
"RDFURN",
"(",
"flow_id",
... | 35 | 0.003711 |
def _homogenize_linesep(line):
"""Enforce line separators to be the right one depending on platform."""
token = str(uuid.uuid4())
line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "")
return line.replace(token, os.linesep) | [
"def",
"_homogenize_linesep",
"(",
"line",
")",
":",
"token",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"line",
"=",
"line",
".",
"replace",
"(",
"os",
".",
"linesep",
",",
"token",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",... | 51 | 0.003861 |
def data_uuids(self, uuids, start, end, archiver="", timeout=DEFAULT_TIMEOUT):
"""
With the given list of UUIDs, retrieves all RAW data between the 2 given timestamps
Arguments:
[uuids]: list of UUIDs
[start, end]: time references:
[archiver]: if specified, this is the a... | [
"def",
"data_uuids",
"(",
"self",
",",
"uuids",
",",
"start",
",",
"end",
",",
"archiver",
"=",
"\"\"",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
")",
":",
"if",
"not",
"isinstance",
"(",
"uuids",
",",
"list",
")",
":",
"uuids",
"=",
"[",
"uuids",
"]",... | 52.533333 | 0.007481 |
def default(self, obj):
"""Serialize obj into JSON."""
# pylint: disable=method-hidden, protected-access, arguments-differ
if isinstance(obj, Sensor):
return {
'sensor_id': obj.sensor_id,
'children': obj.children,
'type': obj.type,
... | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"# pylint: disable=method-hidden, protected-access, arguments-differ",
"if",
"isinstance",
"(",
"obj",
",",
"Sensor",
")",
":",
"return",
"{",
"'sensor_id'",
":",
"obj",
".",
"sensor_id",
",",
"'children'",
":",... | 38.227273 | 0.00232 |
def wait(self, timeout=None):
"""Wait for a change in the journal.
`timeout` is the maximum time in seconds to wait, or None which
means to wait forever.
Returns one of NOP (no change), APPEND (new entries have been added to
the end of the journal), or INVALIDATE (journal files... | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"us",
"=",
"-",
"1",
"if",
"timeout",
"is",
"None",
"else",
"int",
"(",
"timeout",
"*",
"1000000",
")",
"return",
"super",
"(",
"Reader",
",",
"self",
")",
".",
"wait",
"(",
"us",... | 38.75 | 0.006303 |
def get_password(prompt='Password: ', confirm=False):
"""
<Purpose>
Return the password entered by the user. If 'confirm' is True, the user is
asked to enter the previously entered password once again. If they match,
the password is returned to the caller.
<Arguments>
prompt:
The text of ... | [
"def",
"get_password",
"(",
"prompt",
"=",
"'Password: '",
",",
"confirm",
"=",
"False",
")",
":",
"# Are the arguments the expected type?",
"# If not, raise 'securesystemslib.exceptions.FormatError'.",
"securesystemslib",
".",
"formats",
".",
"TEXT_SCHEMA",
".",
"check_match... | 27.2 | 0.007886 |
def add_general_optgroup(parser):
"""
option group for general-use features of all javatool CLIs
"""
g = parser.add_argument_group("General Options")
g.add_argument("-q", "--quiet", dest="silent",
action="store_true", default=False)
g.add_argument("-v", "--verbose", nargs=0... | [
"def",
"add_general_optgroup",
"(",
"parser",
")",
":",
"g",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"General Options\"",
")",
"g",
".",
"add_argument",
"(",
"\"-q\"",
",",
"\"--quiet\"",
",",
"dest",
"=",
"\"silent\"",
",",
"action",
"=",
"\"store_tr... | 34.454545 | 0.001284 |
def add_error(self, property_name, message):
"""Add an error for the given property."""
if property_name not in self.errors:
self.errors[property_name] = []
self.errors[property_name].append(message) | [
"def",
"add_error",
"(",
"self",
",",
"property_name",
",",
"message",
")",
":",
"if",
"property_name",
"not",
"in",
"self",
".",
"errors",
":",
"self",
".",
"errors",
"[",
"property_name",
"]",
"=",
"[",
"]",
"self",
".",
"errors",
"[",
"property_name",... | 42.6 | 0.009217 |
def image(self,path_img):
""" Open image file """
im_open = Image.open(path_img)
im = im_open.convert("RGB")
# Convert the RGB image in printable image
pix_line, img_size = self._convert_image(im)
self._print_image(pix_line, img_size) | [
"def",
"image",
"(",
"self",
",",
"path_img",
")",
":",
"im_open",
"=",
"Image",
".",
"open",
"(",
"path_img",
")",
"im",
"=",
"im_open",
".",
"convert",
"(",
"\"RGB\"",
")",
"# Convert the RGB image in printable image",
"pix_line",
",",
"img_size",
"=",
"se... | 39.428571 | 0.010638 |
def _parse_openssh_output(lines, fingerprint_hash_type=None):
'''
Helper function which parses ssh-keygen -F and ssh-keyscan function output
and yield dict with keys information, one by one.
'''
for line in lines:
# We don't need any whitespace-only containing lines or arbitrary doubled newl... | [
"def",
"_parse_openssh_output",
"(",
"lines",
",",
"fingerprint_hash_type",
"=",
"None",
")",
":",
"for",
"line",
"in",
"lines",
":",
"# We don't need any whitespace-only containing lines or arbitrary doubled newlines",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",... | 35.375 | 0.002294 |
def _is_known_unsigned_by_dtype(dt):
"""Helper returning True if dtype is known to be unsigned."""
return {
tf.bool: True,
tf.uint8: True,
tf.uint16: True,
}.get(dt.base_dtype, False) | [
"def",
"_is_known_unsigned_by_dtype",
"(",
"dt",
")",
":",
"return",
"{",
"tf",
".",
"bool",
":",
"True",
",",
"tf",
".",
"uint8",
":",
"True",
",",
"tf",
".",
"uint16",
":",
"True",
",",
"}",
".",
"get",
"(",
"dt",
".",
"base_dtype",
",",
"False",... | 28.714286 | 0.014493 |
def chhome(name, home, **kwargs):
'''
Change the home directory of the user, pass True for persist to move files
to the new home directory if the old home directory exist.
Args:
name (str): The name of the user whose home directory you wish to change
home (str): The new location of the... | [
"def",
"chhome",
"(",
"name",
",",
"home",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"home",
"=",
"_to_unicode",
"(",
"home",
")",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"arg... | 24.434783 | 0.001711 |
def delete_app(self, app_name):
"""
Delete the given app.
Will fail intentionally if there are any service
bindings. You must delete those first.
"""
if app_name not in self.space.get_apps():
logging.warning("App not found so... succeeded?")
retu... | [
"def",
"delete_app",
"(",
"self",
",",
"app_name",
")",
":",
"if",
"app_name",
"not",
"in",
"self",
".",
"space",
".",
"get_apps",
"(",
")",
":",
"logging",
".",
"warning",
"(",
"\"App not found so... succeeded?\"",
")",
"return",
"True",
"guid",
"=",
"sel... | 31.307692 | 0.004773 |
def transform_grid_to_reference_frame(self, grid):
"""Transform a grid of (y,x) coordinates to the reference frame of the profile, including a translation to \
its centre and a rotation to it orientation.
Parameters
----------
grid : ndarray
The (y, x) coordinates in... | [
"def",
"transform_grid_to_reference_frame",
"(",
"self",
",",
"grid",
")",
":",
"if",
"self",
".",
"__class__",
".",
"__name__",
".",
"startswith",
"(",
"\"Spherical\"",
")",
":",
"return",
"super",
"(",
")",
".",
"transform_grid_to_reference_frame",
"(",
"grid"... | 53.888889 | 0.005066 |
def http_sa_http_server_shutdown(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
http_sa = ET.SubElement(config, "http-sa", xmlns="urn:brocade.com:mgmt:brocade-http")
http = ET.SubElement(http_sa, "http")
server = ET.SubElement(http, "server")
... | [
"def",
"http_sa_http_server_shutdown",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"http_sa",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"http-sa\"",
",",
"xmlns",
"=",
"\"urn:brocad... | 41 | 0.006508 |
def message_for_exception(exception: Exception, message: str) -> Sequence[Token]:
""" Returns a tuple suitable for cli_ui.error()
from the given exception.
(Traceback will be part of the message, after
the ``message`` argument)
Useful when the exception occurs in an other thread
than the main o... | [
"def",
"message_for_exception",
"(",
"exception",
":",
"Exception",
",",
"message",
":",
"str",
")",
"->",
"Sequence",
"[",
"Token",
"]",
":",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
"2",
"]",
"buffer",
"=",
"io",
".",
"StringIO",
"(",
")",... | 29.15 | 0.003322 |
def find_python():
"""Search for Python automatically"""
python = (
_state.get("pythonExecutable") or
# Support for multiple executables.
next((
exe for exe in
os.getenv("PYBLISH_QML_PYTHON_EXECUTABLE", "").split(os.pathsep)
if os.path.isfile(exe)), N... | [
"def",
"find_python",
"(",
")",
":",
"python",
"=",
"(",
"_state",
".",
"get",
"(",
"\"pythonExecutable\"",
")",
"or",
"# Support for multiple executables.",
"next",
"(",
"(",
"exe",
"for",
"exe",
"in",
"os",
".",
"getenv",
"(",
"\"PYBLISH_QML_PYTHON_EXECUTABLE\... | 26.047619 | 0.001764 |
def mi_chain_rule(X, y):
'''
Decompose the information between all X and y according to the chain rule and return all the terms in the chain rule.
Inputs:
-------
X: iterable of iterables. You should be able to compute [mi(x, y) for x in X]
y: iterable of symbols
... | [
"def",
"mi_chain_rule",
"(",
"X",
",",
"y",
")",
":",
"# allocate ndarray output",
"chain",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"X",
")",
")",
"# first term in the expansion is not a conditional information, but the information between the first x and y",
"chain",
"... | 28.310345 | 0.005889 |
def crossspec(data, tbin, Df=None, units=False, pointProcess=False):
"""
Calculate (smoothed) cross spectra of data.
If `units`=True, cross spectra are averaged across units.
Note that averaging is done on cross spectra rather than data.
Cross spectra are normalized by the length T of the time seri... | [
"def",
"crossspec",
"(",
"data",
",",
"tbin",
",",
"Df",
"=",
"None",
",",
"units",
"=",
"False",
",",
"pointProcess",
"=",
"False",
")",
":",
"N",
"=",
"len",
"(",
"data",
")",
"if",
"units",
"is",
"True",
":",
"# smoothing and normalization take place ... | 31.390244 | 0.00339 |
def crypto_box_afternm(message, nonce, k):
"""
Encrypts and returns the message ``message`` using the shared key ``k`` and
the nonce ``nonce``.
:param message: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES:
raise exc.Value... | [
"def",
"crypto_box_afternm",
"(",
"message",
",",
"nonce",
",",
"k",
")",
":",
"if",
"len",
"(",
"nonce",
")",
"!=",
"crypto_box_NONCEBYTES",
":",
"raise",
"exc",
".",
"ValueError",
"(",
"\"Invalid nonce\"",
")",
"if",
"len",
"(",
"k",
")",
"!=",
"crypto... | 30.84 | 0.001258 |
def methods_to_table(obj):
r"""
"""
parent = obj.__class__.__mro__[1]
temp = inspect.getmembers(parent, predicate=inspect.isroutine)
parent_funcs = [i[0] for i in temp if not i[0].startswith('_')]
temp = inspect.getmembers(obj.__class__, predicate=inspect.isroutine)
obj_funcs = [i[0] for i ... | [
"def",
"methods_to_table",
"(",
"obj",
")",
":",
"parent",
"=",
"obj",
".",
"__class__",
".",
"__mro__",
"[",
"1",
"]",
"temp",
"=",
"inspect",
".",
"getmembers",
"(",
"parent",
",",
"predicate",
"=",
"inspect",
".",
"isroutine",
")",
"parent_funcs",
"="... | 35.392857 | 0.000982 |
def seconds_to_str_fromatter(_format):
"""
Accepted format directives: %i %s %m %h
"""
# check directives are correct
if _format == "%S":
def _fromatter(seconds):
return "{:.2f}".format(seconds)
elif _format == "%I":
def _fromatter(seconds):
ret... | [
"def",
"seconds_to_str_fromatter",
"(",
"_format",
")",
":",
"# check directives are correct ",
"if",
"_format",
"==",
"\"%S\"",
":",
"def",
"_fromatter",
"(",
"seconds",
")",
":",
"return",
"\"{:.2f}\"",
".",
"format",
"(",
"seconds",
")",
"elif",
"_format",
"=... | 32.029412 | 0.008021 |
def select_as_coordinates(
self, key, where=None, start=None, stop=None, **kwargs):
"""
return the selection as an Index
Parameters
----------
key : object
where : list of Term (or convertible) objects, optional
start : integer (defaults to None), row... | [
"def",
"select_as_coordinates",
"(",
"self",
",",
"key",
",",
"where",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"where",
"=",
"_ensure_term",
"(",
"where",
",",
"scope_level",
"=",
"1",
")",... | 41.4 | 0.00315 |
def has_files(the_path):
"""Given a path, returns whether the path has any files in it or any subfolders. Works recursively."""
the_path = Path(the_path)
try:
for _ in the_path.walkfiles():
return True
return False
except OSError as ex:
if ex.errno == errno.ENOENT:
... | [
"def",
"has_files",
"(",
"the_path",
")",
":",
"the_path",
"=",
"Path",
"(",
"the_path",
")",
"try",
":",
"for",
"_",
"in",
"the_path",
".",
"walkfiles",
"(",
")",
":",
"return",
"True",
"return",
"False",
"except",
"OSError",
"as",
"ex",
":",
"if",
... | 29.461538 | 0.005063 |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: h... | [
"def",
"run_migrations_online",
"(",
")",
":",
"# this callback is used to prevent an auto-migration from being generated",
"# when there are no changes to the schema",
"# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html",
"def",
"process_revision_directives",
"(",
"context",... | 34.934211 | 0.000733 |
def pause(self):
"""Change state to paused."""
if self.state == STATE_PLAYING:
self._player.set_state(Gst.State.PAUSED)
self.state = STATE_PAUSED | [
"def",
"pause",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"STATE_PLAYING",
":",
"self",
".",
"_player",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"PAUSED",
")",
"self",
".",
"state",
"=",
"STATE_PAUSED"
] | 36.2 | 0.010811 |
def _create_model_info_endpoint(self, path='/info/model'):
"""Create an endpoint to serve info GET requests."""
model = self.model
# parse model details
model_details = {}
for key, value in model.__dict__.items():
model_details[key] = make_serializable(value)
... | [
"def",
"_create_model_info_endpoint",
"(",
"self",
",",
"path",
"=",
"'/info/model'",
")",
":",
"model",
"=",
"self",
".",
"model",
"# parse model details",
"model_details",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"model",
".",
"__dict__",
".",
"ite... | 42.555556 | 0.005109 |
def _InsservExpander(self, facilities, val):
"""Expand insserv variables."""
expanded = []
if val.startswith("$"):
vals = facilities.get(val, [])
for v in vals:
expanded.extend(self._InsservExpander(facilities, v))
elif val.startswith("+"):
expanded.append(val[1:])
else:
... | [
"def",
"_InsservExpander",
"(",
"self",
",",
"facilities",
",",
"val",
")",
":",
"expanded",
"=",
"[",
"]",
"if",
"val",
".",
"startswith",
"(",
"\"$\"",
")",
":",
"vals",
"=",
"facilities",
".",
"get",
"(",
"val",
",",
"[",
"]",
")",
"for",
"v",
... | 29.416667 | 0.013736 |
def connection(self, shareable=True):
"""Get a steady, cached DB-API 2 connection from the pool.
If shareable is set and the underlying DB-API 2 allows it,
then the connection may be shared with other threads.
"""
if shareable and self._maxshared:
self._lock.acquire... | [
"def",
"connection",
"(",
"self",
",",
"shareable",
"=",
"True",
")",
":",
"if",
"shareable",
"and",
"self",
".",
"_maxshared",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"while",
"(",
"not",
"self",
".",
"_shared_cache",
"and",
... | 48.362069 | 0.000699 |
def logger(*args, **kwargs):
"""
shortcut to :func:`utils.get_basic_logger`
"""
if mpi.within_mpirun and mpi.myrank == 0:
# tell the workers to invoke the same logger
mpi.comm.bcast({'worker_command': 'logger', 'args': args, 'kwargs': kwargs}, root=0)
return _utils.get_basic_logger(... | [
"def",
"logger",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"mpi",
".",
"within_mpirun",
"and",
"mpi",
".",
"myrank",
"==",
"0",
":",
"# tell the workers to invoke the same logger",
"mpi",
".",
"comm",
".",
"bcast",
"(",
"{",
"'worker_comma... | 36.444444 | 0.005952 |
def _cleanup(self):
"""Remove the connection from the stack, closing out the cursor"""
if self._cursor:
LOGGER.debug('Closing the cursor on %s', self.pid)
self._cursor.close()
self._cursor = None
if self._conn:
LOGGER.debug('Freeing %s in the pool... | [
"def",
"_cleanup",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cursor",
":",
"LOGGER",
".",
"debug",
"(",
"'Closing the cursor on %s'",
",",
"self",
".",
"pid",
")",
"self",
".",
"_cursor",
".",
"close",
"(",
")",
"self",
".",
"_cursor",
"=",
"None",
... | 36.214286 | 0.003846 |
def init_app(self, app, conf_key=None):
"""
:type app: flask.Flask
:parm str conf_key: Key of flask config.
"""
conf_key = conf_key or self.conf_key or 'PYMEMCACHE'
self.conf_key = conf_key
conf = app.config[conf_key]
if not isinstance(conf, dict):
... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"conf_key",
"=",
"None",
")",
":",
"conf_key",
"=",
"conf_key",
"or",
"self",
".",
"conf_key",
"or",
"'PYMEMCACHE'",
"self",
".",
"conf_key",
"=",
"conf_key",
"conf",
"=",
"app",
".",
"config",
"[",
"con... | 37.071429 | 0.002817 |
def findExtname(fimg, extname, extver=None):
"""
Returns the list number of the extension corresponding to EXTNAME given.
"""
i = 0
extnum = None
for chip in fimg:
hdr = chip.header
if 'EXTNAME' in hdr:
if hdr['EXTNAME'].strip() == extname.upper():
if... | [
"def",
"findExtname",
"(",
"fimg",
",",
"extname",
",",
"extver",
"=",
"None",
")",
":",
"i",
"=",
"0",
"extnum",
"=",
"None",
"for",
"chip",
"in",
"fimg",
":",
"hdr",
"=",
"chip",
".",
"header",
"if",
"'EXTNAME'",
"in",
"hdr",
":",
"if",
"hdr",
... | 27.375 | 0.002208 |
def tags_impl(self):
"""Creates the JSON object for the tags route response.
Returns:
The JSON object for the tags route response.
"""
if self._db_connection_provider:
# Read tags from the database.
db = self._db_connection_provider()
cursor = db.execute('''
SELECT
... | [
"def",
"tags_impl",
"(",
"self",
")",
":",
"if",
"self",
".",
"_db_connection_provider",
":",
"# Read tags from the database.",
"db",
"=",
"self",
".",
"_db_connection_provider",
"(",
")",
"cursor",
"=",
"db",
".",
"execute",
"(",
"'''\n SELECT\n Tag... | 35.181818 | 0.008799 |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist and plugin not disabled
if not self.stats or self.is_disable():
return ret
# Build the s... | [
"def",
"msg_curse",
"(",
"self",
",",
"args",
"=",
"None",
",",
"max_width",
"=",
"None",
")",
":",
"# Init the return message",
"ret",
"=",
"[",
"]",
"# Only process if stats exist and plugin not disabled",
"if",
"not",
"self",
".",
"stats",
"or",
"self",
".",
... | 47.757576 | 0.003108 |
def uninstall_all_passbands(local=True):
"""
Uninstall all passbands, either globally or locally (need to call twice to
delete ALL passbands)
If local=False, you must have permission to access the installation directory
"""
pbdir = _pbdir_local if local else _pbdir_global
for f in os.listdi... | [
"def",
"uninstall_all_passbands",
"(",
"local",
"=",
"True",
")",
":",
"pbdir",
"=",
"_pbdir_local",
"if",
"local",
"else",
"_pbdir_global",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"pbdir",
")",
":",
"pbpath",
"=",
"os",
".",
"path",
".",
"join",
... | 36.916667 | 0.004405 |
def get_canonical_correlations(dataframe, column_types):
'''
computes the correlation coefficient between each distinct pairing of columns
preprocessing note:
any rows with missing values (in either paired column) are dropped for that pairing
categorical columns are replaced with one-hot enc... | [
"def",
"get_canonical_correlations",
"(",
"dataframe",
",",
"column_types",
")",
":",
"def",
"preprocess",
"(",
"series",
")",
":",
"if",
"column_types",
"[",
"series",
".",
"name",
"]",
"==",
"'CATEGORICAL'",
":",
"series",
"=",
"pd",
".",
"get_dummies",
"(... | 34.352941 | 0.003885 |
def find_nested_meta_first(d, prop_name, version):
"""Returns obj. for badgerfish and val for hbf. Appropriate for nested literals"""
if _is_badgerfish_version(version):
return find_nested_meta_first_bf(d, prop_name)
p = '^' + prop_name
return d.get(p) | [
"def",
"find_nested_meta_first",
"(",
"d",
",",
"prop_name",
",",
"version",
")",
":",
"if",
"_is_badgerfish_version",
"(",
"version",
")",
":",
"return",
"find_nested_meta_first_bf",
"(",
"d",
",",
"prop_name",
")",
"p",
"=",
"'^'",
"+",
"prop_name",
"return"... | 45.166667 | 0.007246 |
def force_auto(service, _type):
"""
Helper for forcing autoserialization of a datatype with already registered explicit
storable instance.
Arguments:
service (StorableService): active storable service.
_type (type): type to be autoserialized.
**Not tested**
"""
storable =... | [
"def",
"force_auto",
"(",
"service",
",",
"_type",
")",
":",
"storable",
"=",
"service",
".",
"byPythonType",
"(",
"_type",
",",
"istype",
"=",
"True",
")",
"version",
"=",
"max",
"(",
"handler",
".",
"version",
"[",
"0",
"]",
"for",
"handler",
"in",
... | 31.352941 | 0.003643 |
def get_scheme_dirs():
"""Return a set of all scheme directories."""
scheme_glob = rel_to_cwd('schemes', '**', '*.yaml')
scheme_groups = glob(scheme_glob)
scheme_groups = [get_parent_dir(path) for path in scheme_groups]
return set(scheme_groups) | [
"def",
"get_scheme_dirs",
"(",
")",
":",
"scheme_glob",
"=",
"rel_to_cwd",
"(",
"'schemes'",
",",
"'**'",
",",
"'*.yaml'",
")",
"scheme_groups",
"=",
"glob",
"(",
"scheme_glob",
")",
"scheme_groups",
"=",
"[",
"get_parent_dir",
"(",
"path",
")",
"for",
"path... | 43.333333 | 0.003774 |
def getTzid(tzid, smart=True):
"""Return the tzid if it exists, or None."""
tz = __tzidMap.get(toUnicode(tzid), None)
if smart and tzid and not tz:
try:
from pytz import timezone, UnknownTimeZoneError
try:
tz = timezone(tzid)
registerTzid(toUni... | [
"def",
"getTzid",
"(",
"tzid",
",",
"smart",
"=",
"True",
")",
":",
"tz",
"=",
"__tzidMap",
".",
"get",
"(",
"toUnicode",
"(",
"tzid",
")",
",",
"None",
")",
"if",
"smart",
"and",
"tzid",
"and",
"not",
"tz",
":",
"try",
":",
"from",
"pytz",
"impo... | 31.642857 | 0.002193 |
def set_structure(self, lattice, species, coords, coords_are_cartesian):
"""
Sets up the pymatgen structure for which the coordination geometries have to be identified starting from the
lattice, the species and the coordinates
:param lattice: The lattice of the structure
:param s... | [
"def",
"set_structure",
"(",
"self",
",",
"lattice",
",",
"species",
",",
"coords",
",",
"coords_are_cartesian",
")",
":",
"self",
".",
"setup_structure",
"(",
"Structure",
"(",
"lattice",
",",
"species",
",",
"coords",
",",
"coords_are_cartesian",
")",
")"
] | 55.545455 | 0.006441 |
def build_search(self):
"""Builds the Elasticsearch search body represented by this S.
Loop over self.steps to build the search body that will be
sent to Elasticsearch. This returns a Python dict.
If you want the JSON that actually gets sent, then pass the return
value through ... | [
"def",
"build_search",
"(",
"self",
")",
":",
"filters",
"=",
"[",
"]",
"filters_raw",
"=",
"None",
"queries",
"=",
"[",
"]",
"query_raw",
"=",
"None",
"sort",
"=",
"[",
"]",
"dict_fields",
"=",
"set",
"(",
")",
"list_fields",
"=",
"set",
"(",
")",
... | 33.583851 | 0.000359 |
def merge_and_average(self, platform, expression_column, group_by_column,
force=False, merge_on_column=None, gsm_on=None,
gpl_on=None):
"""Merge and average GSE samples.
For given platform prepare the DataFrame with all the samples present in
... | [
"def",
"merge_and_average",
"(",
"self",
",",
"platform",
",",
"expression_column",
",",
"group_by_column",
",",
"force",
"=",
"False",
",",
"merge_on_column",
"=",
"None",
",",
"gsm_on",
"=",
"None",
",",
"gpl_on",
"=",
"None",
")",
":",
"if",
"isinstance",... | 42.907407 | 0.00211 |
def DeleteAddress(self, script_hash):
"""
Deletes an address from the wallet (includes watch-only addresses).
Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.
Returns:
tuple:
bool: True if address removed, False othe... | [
"def",
"DeleteAddress",
"(",
"self",
",",
"script_hash",
")",
":",
"coin_keys_toremove",
"=",
"[",
"]",
"coins_to_remove",
"=",
"[",
"]",
"for",
"key",
",",
"coinref",
"in",
"self",
".",
"_coins",
".",
"items",
"(",
")",
":",
"if",
"coinref",
".",
"Out... | 34.322581 | 0.003656 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.