text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def convert_args_to_list(args):
"""Convert all iterable pairs of inputs into a list of list"""
list_of_pairs = []
if len(args) == 0:
return []
if any(isinstance(arg, (list, tuple)) for arg in args):
# Domain([[1, 4]])
# Domain([(1, 4)])
# Domain([(1, 4), (5, 8)])
... | [
"def",
"convert_args_to_list",
"(",
"args",
")",
":",
"list_of_pairs",
"=",
"[",
"]",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"return",
"[",
"]",
"if",
"any",
"(",
"isinstance",
"(",
"arg",
",",
"(",
"list",
",",
"tuple",
")",
")",
"for",
... | 31.290323 | 15.548387 |
def rep(parser: Union[Parser, Sequence[Input]]) -> RepeatedParser:
"""Match a parser zero or more times repeatedly.
This matches ``parser`` multiple times in a row. A list is returned
containing the value from each match. If there are no matches, an empty list
is returned.
Args:
parser: Pa... | [
"def",
"rep",
"(",
"parser",
":",
"Union",
"[",
"Parser",
",",
"Sequence",
"[",
"Input",
"]",
"]",
")",
"->",
"RepeatedParser",
":",
"if",
"isinstance",
"(",
"parser",
",",
"str",
")",
":",
"parser",
"=",
"lit",
"(",
"parser",
")",
"return",
"Repeate... | 32.769231 | 20.538462 |
def validate(self):
""" validate: Makes sure HTML5 app is valid
Args: None
Returns: boolean indicating if HTML5 app is valid
"""
from .files import HTMLZipFile
try:
assert self.kind == content_kinds.HTML5, "Assumption Failed: Node should be an HTML5 ap... | [
"def",
"validate",
"(",
"self",
")",
":",
"from",
".",
"files",
"import",
"HTMLZipFile",
"try",
":",
"assert",
"self",
".",
"kind",
"==",
"content_kinds",
".",
"HTML5",
",",
"\"Assumption Failed: Node should be an HTML5 app\"",
"assert",
"self",
".",
"questions",
... | 53.857143 | 31.285714 |
def get_certificate_request(json_encode=True):
"""Generate a certificatee requests based on the network confioguration
"""
req = CertRequest(json_encode=json_encode)
req.add_hostname_cn()
# Add os-hostname entries
for net_type in [INTERNAL, ADMIN, PUBLIC]:
net_config = config(ADDRESS_MA... | [
"def",
"get_certificate_request",
"(",
"json_encode",
"=",
"True",
")",
":",
"req",
"=",
"CertRequest",
"(",
"json_encode",
"=",
"json_encode",
")",
"req",
".",
"add_hostname_cn",
"(",
")",
"# Add os-hostname entries",
"for",
"net_type",
"in",
"[",
"INTERNAL",
"... | 40.4 | 14.8 |
def zoom(self, factor, order=1, verbose=True):
"""Zoom the data array using spline interpolation of the requested order.
The number of points along each axis is increased by factor.
See `scipy ndimage`__ for more info.
__ http://docs.scipy.org/doc/scipy/reference/
g... | [
"def",
"zoom",
"(",
"self",
",",
"factor",
",",
"order",
"=",
"1",
",",
"verbose",
"=",
"True",
")",
":",
"raise",
"NotImplementedError",
"import",
"scipy",
".",
"ndimage",
"# axes",
"for",
"axis",
"in",
"self",
".",
"_axes",
":",
"axis",
"[",
":",
"... | 37.133333 | 20.933333 |
def _populate_terms(self, optobj):
"""Convert GO IDs to GO Term record objects. Populate children."""
has_relationship = optobj is not None and 'relationship' in optobj.optional_attrs
# Make parents and relationships references to the actual GO terms.
for rec in self.values():
... | [
"def",
"_populate_terms",
"(",
"self",
",",
"optobj",
")",
":",
"has_relationship",
"=",
"optobj",
"is",
"not",
"None",
"and",
"'relationship'",
"in",
"optobj",
".",
"optional_attrs",
"# Make parents and relationships references to the actual GO terms.",
"for",
"rec",
"... | 49.785714 | 21.785714 |
def _h_function(self,h):
""" private method exponential variogram "h" function
Parameters
----------
h : (float or numpy.ndarray)
distance(s)
Returns
-------
h_function : float or numpy.ndarray
the value of the "h" function implied by the... | [
"def",
"_h_function",
"(",
"self",
",",
"h",
")",
":",
"return",
"self",
".",
"contribution",
"*",
"np",
".",
"exp",
"(",
"-",
"1.0",
"*",
"h",
"/",
"self",
".",
"a",
")"
] | 25.933333 | 19.933333 |
def _set_alarm_falling_event_index(self, v, load=False):
"""
Setter method for alarm_falling_event_index, mapped from YANG variable /rmon/alarm_entry/alarm_falling_event_index (alarm-falling-event-index-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_alarm_falling_... | [
"def",
"_set_alarm_falling_event_index",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v"... | 97.363636 | 46.772727 |
def cycle(self, *values):
"""Cycle through values as the loop progresses.
"""
if not values:
raise ValueError("You must provide values to cycle through")
return values[self.index % len(values)] | [
"def",
"cycle",
"(",
"self",
",",
"*",
"values",
")",
":",
"if",
"not",
"values",
":",
"raise",
"ValueError",
"(",
"\"You must provide values to cycle through\"",
")",
"return",
"values",
"[",
"self",
".",
"index",
"%",
"len",
"(",
"values",
")",
"]"
] | 38.666667 | 12 |
def format_uptime(uptime_in_seconds):
"""Format number of seconds into human-readable string.
:param uptime_in_seconds: The server uptime in seconds.
:returns: A human-readable string representing the uptime.
>>> uptime = format_uptime('56892')
>>> print(uptime)
15 hours 48 min 12 sec
"""
... | [
"def",
"format_uptime",
"(",
"uptime_in_seconds",
")",
":",
"m",
",",
"s",
"=",
"divmod",
"(",
"int",
"(",
"uptime_in_seconds",
")",
",",
"60",
")",
"h",
",",
"m",
"=",
"divmod",
"(",
"m",
",",
"60",
")",
"d",
",",
"h",
"=",
"divmod",
"(",
"h",
... | 34.962963 | 18.148148 |
def list_media_endpoint_keys(access_token, subscription_id, rgname, msname):
'''list the media endpoint keys in a media service
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
ms... | [
"def",
"list_media_endpoint_keys",
"(",
"access_token",
",",
"subscription_id",
",",
"rgname",
",",
"msname",
")",
":",
"endpoint",
"=",
"''",
".",
"join",
"(",
"[",
"get_rm_endpoint",
"(",
")",
",",
"'/subscriptions/'",
",",
"subscription_id",
",",
"'/resourceG... | 39.684211 | 18.526316 |
def zipdir(path, ziph, **kwargs):
"""
Zip up a directory.
:param path:
:param ziph:
:param kwargs:
:return:
"""
str_arcroot = ""
for k, v in kwargs.items():
if k == 'arcroot': str_arcroot = v
for root, dirs, files in os.walk(path):
for file in files:
... | [
"def",
"zipdir",
"(",
"path",
",",
"ziph",
",",
"*",
"*",
"kwargs",
")",
":",
"str_arcroot",
"=",
"\"\"",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'arcroot'",
":",
"str_arcroot",
"=",
"v",
"for",
"root"... | 28.083333 | 17.583333 |
def get_attribute_from_config(config, section, attribute):
"""Try to parse an attribute of the config file.
Args:
config (defaultdict): A defaultdict.
section (str): The section of the config file to get information from.
attribute (str): The attribute of the section to fetch.
Retur... | [
"def",
"get_attribute_from_config",
"(",
"config",
",",
"section",
",",
"attribute",
")",
":",
"section",
"=",
"config",
".",
"get",
"(",
"section",
")",
"if",
"section",
":",
"option",
"=",
"section",
".",
"get",
"(",
"attribute",
")",
"if",
"option",
"... | 37.5 | 19.75 |
def draw_final_outputs(img, results):
"""
Args:
results: [DetectionResult]
"""
if len(results) == 0:
return img
# Display in largest to smallest order to reduce occlusion
boxes = np.asarray([r.box for r in results])
areas = np_area(boxes)
sorted_inds = np.argsort(-areas)... | [
"def",
"draw_final_outputs",
"(",
"img",
",",
"results",
")",
":",
"if",
"len",
"(",
"results",
")",
"==",
"0",
":",
"return",
"img",
"# Display in largest to smallest order to reduce occlusion",
"boxes",
"=",
"np",
".",
"asarray",
"(",
"[",
"r",
".",
"box",
... | 24.576923 | 17.961538 |
def upper_price_channel(data, period, upper_percent):
"""
Upper Price Channel.
Formula:
upc = EMA(t) * (1 + upper_percent / 100)
"""
catch_errors.check_for_period_error(data, period)
emas = ema(data, period)
upper_channel = [val * (1+float(upper_percent)/100) for val in emas]
retur... | [
"def",
"upper_price_channel",
"(",
"data",
",",
"period",
",",
"upper_percent",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"emas",
"=",
"ema",
"(",
"data",
",",
"period",
")",
"upper_channel",
"=",
"[",
"val",
... | 27 | 17.833333 |
def set_converter(self, file_format, converter):
"""
Register a Converter and the FileFormat that it is able to convert from
Parameters
----------
converter : Converter
The converter to register
file_format : FileFormat
The file format that can be... | [
"def",
"set_converter",
"(",
"self",
",",
"file_format",
",",
"converter",
")",
":",
"self",
".",
"_converters",
"[",
"file_format",
".",
"name",
"]",
"=",
"(",
"file_format",
",",
"converter",
")"
] | 34.833333 | 17.333333 |
def make_store(name, min_length=4, **kwargs):
"""\
Creates a store with a reasonable keygen.
.. deprecated:: 2.0.0
Instantiate stores directly e.g. ``shorten.MemoryStore(min_length=4)``
"""
if name not in stores:
raise ValueError('valid stores are {0}'.format(', '.join(stores)))
if n... | [
"def",
"make_store",
"(",
"name",
",",
"min_length",
"=",
"4",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
"not",
"in",
"stores",
":",
"raise",
"ValueError",
"(",
"'valid stores are {0}'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"stores",
")... | 24.95 | 20.2 |
def energy(self) -> ErrorValue:
"""X-ray energy"""
return (ErrorValue(*(scipy.constants.physical_constants['speed of light in vacuum'][0::2])) *
ErrorValue(*(scipy.constants.physical_constants['Planck constant in eV s'][0::2])) /
scipy.constants.nano /
sel... | [
"def",
"energy",
"(",
"self",
")",
"->",
"ErrorValue",
":",
"return",
"(",
"ErrorValue",
"(",
"*",
"(",
"scipy",
".",
"constants",
".",
"physical_constants",
"[",
"'speed of light in vacuum'",
"]",
"[",
"0",
":",
":",
"2",
"]",
")",
")",
"*",
"ErrorValue... | 54.666667 | 23.333333 |
def _read_routine_metadata(self):
"""
Returns the metadata of stored routines.
:rtype: dict
"""
metadata = {}
if os.path.isfile(self._metadata_filename):
with open(self._metadata_filename, 'r') as file:
metadata = json.load(file)
retu... | [
"def",
"_read_routine_metadata",
"(",
"self",
")",
":",
"metadata",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"_metadata_filename",
")",
":",
"with",
"open",
"(",
"self",
".",
"_metadata_filename",
",",
"'r'",
")",
"as",
... | 26.666667 | 15.333333 |
def writearff(data, filename, relation_name=None, index=True):
"""Write ARFF file
Parameters
----------
data : :class:`pandas.DataFrame`
DataFrame containing data
filename : string or file-like object
Path to ARFF file or file-like object. In the latter case,
the handle is ... | [
"def",
"writearff",
"(",
"data",
",",
"filename",
",",
"relation_name",
"=",
"None",
",",
"index",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"filename",
",",
"str",
")",
":",
"fp",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"if",
"relation_... | 26.2 | 18.971429 |
def elem2json(elem, options, strip_ns=1, strip=1):
"""Convert an ElementTree or Element into a JSON string."""
if hasattr(elem, 'getroot'):
elem = elem.getroot()
if options.pretty:
return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip), sort_keys=True, indent=4, separato... | [
"def",
"elem2json",
"(",
"elem",
",",
"options",
",",
"strip_ns",
"=",
"1",
",",
"strip",
"=",
"1",
")",
":",
"if",
"hasattr",
"(",
"elem",
",",
"'getroot'",
")",
":",
"elem",
"=",
"elem",
".",
"getroot",
"(",
")",
"if",
"options",
".",
"pretty",
... | 37.909091 | 30 |
def verify_text_present(self, text, msg=None):
"""
Soft assert for whether the text if visible in the current window/frame
:params text: the string to search for
:params msg: (Optional) msg explaining the difference
"""
try:
self.assert_text_present(text, msg... | [
"def",
"verify_text_present",
"(",
"self",
",",
"text",
",",
"msg",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"assert_text_present",
"(",
"text",
",",
"msg",
")",
"except",
"AssertionError",
",",
"e",
":",
"if",
"msg",
":",
"m",
"=",
"\"%s:\\n%s\... | 33.266667 | 14.866667 |
def __driver_helper(self, line):
"""Driver level helper method.
1. Display help message for the given input. Internally calls
self.__get_help_message() to obtain the help message.
2. Re-display the prompt and the input line.
Arguments:
line: The input line.
... | [
"def",
"__driver_helper",
"(",
"self",
",",
"line",
")",
":",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"'?'",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"doc_string",
"(",
... | 35.1875 | 15.09375 |
def camelize(key):
"""Convert a python_style_variable_name to lowerCamelCase.
Examples
--------
>>> camelize('variable_name')
'variableName'
>>> camelize('variableName')
'variableName'
"""
return ''.join(x.capitalize() if i > 0 else x
for i, x in enumerate(key.spl... | [
"def",
"camelize",
"(",
"key",
")",
":",
"return",
"''",
".",
"join",
"(",
"x",
".",
"capitalize",
"(",
")",
"if",
"i",
">",
"0",
"else",
"x",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"key",
".",
"split",
"(",
"'_'",
")",
")",
")"
] | 26.5 | 16.916667 |
async def check_response(response, valid_response_codes):
"""Check the response for correctness."""
if response.status == 204:
return True
if response.status in valid_response_codes:
_js = await response.json()
return _js
else:
raise PvApiResponseStatusError(response.stat... | [
"async",
"def",
"check_response",
"(",
"response",
",",
"valid_response_codes",
")",
":",
"if",
"response",
".",
"status",
"==",
"204",
":",
"return",
"True",
"if",
"response",
".",
"status",
"in",
"valid_response_codes",
":",
"_js",
"=",
"await",
"response",
... | 35 | 14.222222 |
def get_status(*nrs):
"""Returns a list of Bugreport objects.
Given a list of bugnumbers this method returns a list of Bugreport
objects.
Parameters
----------
nrs : int or list of ints
the bugnumbers
Returns
-------
bugs : list of Bugreport objects
"""
# If we ca... | [
"def",
"get_status",
"(",
"*",
"nrs",
")",
":",
"# If we called get_status with one single bug, we get a single bug,",
"# if we called it with a list of bugs, we get a list,",
"# No available bugreports returns an empty list",
"bugs",
"=",
"[",
"]",
"list_",
"=",
"[",
"]",
"for",... | 32.410256 | 20 |
def associate_profile_to_role(profile_name, role_name, region=None, key=None,
keyid=None, profile=None):
'''
Associate an instance profile with an IAM role.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.associate_profile_to_role myirole myiprofile
... | [
"def",
"associate_profile_to_role",
"(",
"profile_name",
",",
"role_name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",... | 39.483871 | 28.967742 |
def get_one(self, object_id):
"""
Retrieve an object by its object_id
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFound when the object could not be found
"""
return self.session.query(self.cls).filter_by(id=object_id)... | [
"def",
"get_one",
"(",
"self",
",",
"object_id",
")",
":",
"return",
"self",
".",
"session",
".",
"query",
"(",
"self",
".",
"cls",
")",
".",
"filter_by",
"(",
"id",
"=",
"object_id",
")",
".",
"one",
"(",
")"
] | 35.333333 | 13.777778 |
def get_example(cls) -> dict:
"""Returns an example value for the Dict type.
If an example isn't a defined attribute on the class we return
a dict of example values based on each property's annotation.
"""
if cls.example is not None:
return cls.example
return... | [
"def",
"get_example",
"(",
"cls",
")",
"->",
"dict",
":",
"if",
"cls",
".",
"example",
"is",
"not",
"None",
":",
"return",
"cls",
".",
"example",
"return",
"{",
"k",
":",
"v",
".",
"get_example",
"(",
")",
"for",
"k",
",",
"v",
"in",
"cls",
".",
... | 40.888889 | 17.222222 |
def save_family(self, family_form, *args, **kwargs):
"""Pass through to provider FamilyAdminSession.update_family"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.update_bin
if family_form.is_for_update():
return self.update_family(family_form, *ar... | [
"def",
"save_family",
"(",
"self",
",",
"family_form",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Implemented from kitosid template for -",
"# osid.resource.BinAdminSession.update_bin",
"if",
"family_form",
".",
"is_for_update",
"(",
")",
":",
"return",
... | 51 | 14.125 |
def scrub(value, scrub_text=_keep_whitespace, scrub_number=_scrub_number):
"""
REMOVE/REPLACE VALUES THAT CAN NOT BE JSON-IZED
"""
return _scrub(value, set(), [], scrub_text=scrub_text, scrub_number=scrub_number) | [
"def",
"scrub",
"(",
"value",
",",
"scrub_text",
"=",
"_keep_whitespace",
",",
"scrub_number",
"=",
"_scrub_number",
")",
":",
"return",
"_scrub",
"(",
"value",
",",
"set",
"(",
")",
",",
"[",
"]",
",",
"scrub_text",
"=",
"scrub_text",
",",
"scrub_number",... | 44.8 | 18 |
def loadlabelfont(self):
"""Auxiliary method to load font if not yet done."""
if self.labelfont == None:
self.labelfont = imft.load_path(os.path.join(fontsdir, "courR10.pil")) | [
"def",
"loadlabelfont",
"(",
"self",
")",
":",
"if",
"self",
".",
"labelfont",
"==",
"None",
":",
"self",
".",
"labelfont",
"=",
"imft",
".",
"load_path",
"(",
"os",
".",
"path",
".",
"join",
"(",
"fontsdir",
",",
"\"courR10.pil\"",
")",
")"
] | 50 | 16 |
def from_pyfile(self, filename):
"""
在一个 Python 文件中读取配置。
:param filename: 配置文件的文件名
:return: 如果读取成功,返回 ``True``,如果失败,会抛出错误异常
"""
d = types.ModuleType('config')
d.__file__ = filename
with open(filename) as config_file:
exec(compile(config_file.r... | [
"def",
"from_pyfile",
"(",
"self",
",",
"filename",
")",
":",
"d",
"=",
"types",
".",
"ModuleType",
"(",
"'config'",
")",
"d",
".",
"__file__",
"=",
"filename",
"with",
"open",
"(",
"filename",
")",
"as",
"config_file",
":",
"exec",
"(",
"compile",
"("... | 30.230769 | 12.384615 |
def _timestamp():
"""Return a timestamp with microsecond precision."""
moment = time.time()
moment_us = repr(moment).split('.')[1]
return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_us), time.gmtime(moment)) | [
"def",
"_timestamp",
"(",
")",
":",
"moment",
"=",
"time",
".",
"time",
"(",
")",
"moment_us",
"=",
"repr",
"(",
"moment",
")",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"return",
"time",
".",
"strftime",
"(",
"\"%Y-%m-%d-%H-%M-%S-{}\"",
".",
"fo... | 45.2 | 17.6 |
def optimal_t(self, t_max=100, plot=False, ax=None):
"""Find the optimal value of t
Selects the optimal value of t based on the knee point of the
Von Neumann Entropy of the diffusion operator.
Parameters
----------
t_max : int, default: 100
Maximum value of ... | [
"def",
"optimal_t",
"(",
"self",
",",
"t_max",
"=",
"100",
",",
"plot",
"=",
"False",
",",
"ax",
"=",
"None",
")",
":",
"tasklogger",
".",
"log_start",
"(",
"\"optimal t\"",
")",
"t",
",",
"h",
"=",
"self",
".",
"von_neumann_entropy",
"(",
"t_max",
"... | 31.886364 | 18.818182 |
def peer_list(self):
""" GET /network/peers
Use the Network APIs to retrieve information about the network of peer
nodes comprising the blockchain network.
```golang
message PeersMessage {
repeated PeerEndpoint peers = 1;
}
message PeerEndpoint {
... | [
"def",
"peer_list",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"_get",
"(",
"self",
".",
"_url",
"(",
"\"/network/peers\"",
")",
")",
"return",
"self",
".",
"_result",
"(",
"res",
",",
"True",
")"
] | 25 | 18.516129 |
def connections(self):
"""
:return list[Connection]: Connections that this effects is present (with input or output port)
"""
function = lambda connection: connection.input.effect == self \
or connection.output.effect == self
return tuple([c fo... | [
"def",
"connections",
"(",
"self",
")",
":",
"function",
"=",
"lambda",
"connection",
":",
"connection",
".",
"input",
".",
"effect",
"==",
"self",
"or",
"connection",
".",
"output",
".",
"effect",
"==",
"self",
"return",
"tuple",
"(",
"[",
"c",
"for",
... | 45.5 | 27.25 |
def rfc19242long(s):
"""Convert an RFC 1924 IPv6 address to a network byte order 128-bit
integer.
>>> expect = 0
>>> rfc19242long('00000000000000000000') == expect
True
>>> expect = 21932261930451111902915077091070067066
>>> rfc19242long('4)+k&C#VzJ4br>0wv%Yp') == expect
True
>>> r... | [
"def",
"rfc19242long",
"(",
"s",
")",
":",
"global",
"_RFC1924_REV",
"if",
"not",
"_RFC1924_RE",
".",
"match",
"(",
"s",
")",
":",
"return",
"None",
"if",
"_RFC1924_REV",
"is",
"None",
":",
"_RFC1924_REV",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v... | 26.088235 | 21.911765 |
def show_instance(name, conn=None, call=None):
'''
Get VM on this OpenStack account
name
name of the instance
CLI Example
.. code-block:: bash
salt-cloud -a show_instance myserver
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance... | [
"def",
"show_instance",
"(",
"name",
",",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The show_instance action must be called with -a or --action.'",
")",
"if",
"conn",
"is",
... | 25.810811 | 20.783784 |
def restore(self, state):
"""Restore a previous state of this stream walker.
Raises:
ArgumentError: If the state refers to a different selector or the
offset is invalid.
"""
selector = DataStreamSelector.FromString(state.get(u'selector'))
if selector... | [
"def",
"restore",
"(",
"self",
",",
"state",
")",
":",
"selector",
"=",
"DataStreamSelector",
".",
"FromString",
"(",
"state",
".",
"get",
"(",
"u'selector'",
")",
")",
"if",
"selector",
"!=",
"self",
".",
"selector",
":",
"raise",
"ArgumentError",
"(",
... | 40.5 | 25.428571 |
def _run_aggregation_cmd(self, session, explicit_session):
"""Run the full aggregation pipeline for this ChangeStream and return
the corresponding CommandCursor.
"""
read_preference = self._target._read_preference_for(session)
client = self._database.client
def _cmd(sess... | [
"def",
"_run_aggregation_cmd",
"(",
"self",
",",
"session",
",",
"explicit_session",
")",
":",
"read_preference",
"=",
"self",
".",
"_target",
".",
"_read_preference_for",
"(",
"session",
")",
"client",
"=",
"self",
".",
"_database",
".",
"client",
"def",
"_cm... | 40.387755 | 16.020408 |
def emit(self, *args, **kwargs):
'''
Emits this signal. As result, all handlers will be invoked.
'''
self._messanger.send(self, *args, **kwargs) | [
"def",
"emit",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_messanger",
".",
"send",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 34.4 | 20.8 |
def select_char_code_table(self, table):
'''Select character code table, from tree built in ones.
Args:
table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare'
Returns:
None
Raises:
... | [
"def",
"select_char_code_table",
"(",
"self",
",",
"table",
")",
":",
"tables",
"=",
"{",
"'standard'",
":",
"0",
",",
"'eastern european'",
":",
"1",
",",
"'western european'",
":",
"2",
",",
"'spare'",
":",
"3",
"}",
"if",
"table",
"in",
"tables",
":",... | 34.736842 | 20.210526 |
async def create(gc: GroupControl, name, slaves):
"""Create new group"""
click.echo("Creating group %s with slaves: %s" % (name, slaves))
click.echo(await gc.create(name, slaves)) | [
"async",
"def",
"create",
"(",
"gc",
":",
"GroupControl",
",",
"name",
",",
"slaves",
")",
":",
"click",
".",
"echo",
"(",
"\"Creating group %s with slaves: %s\"",
"%",
"(",
"name",
",",
"slaves",
")",
")",
"click",
".",
"echo",
"(",
"await",
"gc",
".",
... | 47 | 10.5 |
def serve(context: Context, port=8000, browsersync_port=3000, browsersync_ui_port=3030):
"""
Starts a development server with auto-building and live-reload
"""
try:
from watchdog.observers import Observer
except ImportError:
context.pip_command('install', 'watchdog>0.8,<0.9')
... | [
"def",
"serve",
"(",
"context",
":",
"Context",
",",
"port",
"=",
"8000",
",",
"browsersync_port",
"=",
"3000",
",",
"browsersync_ui_port",
"=",
"3030",
")",
":",
"try",
":",
"from",
"watchdog",
".",
"observers",
"import",
"Observer",
"except",
"ImportError"... | 40.294118 | 17.147059 |
def salt_ssh():
'''
Execute the salt-ssh system
'''
import salt.cli.ssh
if '' in sys.path:
sys.path.remove('')
try:
client = salt.cli.ssh.SaltSSH()
_install_signal_handlers(client)
client.run()
except SaltClientError as err:
trace = traceback.format_ex... | [
"def",
"salt_ssh",
"(",
")",
":",
"import",
"salt",
".",
"cli",
".",
"ssh",
"if",
"''",
"in",
"sys",
".",
"path",
":",
"sys",
".",
"path",
".",
"remove",
"(",
"''",
")",
"try",
":",
"client",
"=",
"salt",
".",
"cli",
".",
"ssh",
".",
"SaltSSH",... | 26.095238 | 14.952381 |
def support_jsonp(api_instance, callback_name_source='callback'):
"""Let API instance can respond jsonp request automatically.
`callback_name_source` can be a string or a callback.
If it is a string, the system will find the argument that named by this string in `query string`.
If found, deter... | [
"def",
"support_jsonp",
"(",
"api_instance",
",",
"callback_name_source",
"=",
"'callback'",
")",
":",
"output_json",
"=",
"api_instance",
".",
"representations",
"[",
"'application/json'",
"]",
"@",
"api_instance",
".",
"representation",
"(",
"'application/json'",
")... | 47.961538 | 30.923077 |
def setEventCallback(self, callback, bequeath=True, channel=0):
"""
Set additional event callbacks for the device.
Set the callback for specific channels or use the device itself and let
it bequeath the callback to all of its children.
Signature for callback-functions: foo(addres... | [
"def",
"setEventCallback",
"(",
"self",
",",
"callback",
",",
"bequeath",
"=",
"True",
",",
"channel",
"=",
"0",
")",
":",
"if",
"hasattr",
"(",
"callback",
",",
"'__call__'",
")",
":",
"if",
"channel",
"==",
"0",
":",
"self",
".",
"_eventcallbacks",
"... | 51.666667 | 19.266667 |
def save(self, force=False, uuid=False, **kwargs):
"""
REPLACES the object in DB. This is forbidden with objects from find() methods unless force=True is given.
"""
if not self._initialized_with_doc and not force:
raise Exception("Cannot save a document not initialized fro... | [
"def",
"save",
"(",
"self",
",",
"force",
"=",
"False",
",",
"uuid",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_initialized_with_doc",
"and",
"not",
"force",
":",
"raise",
"Exception",
"(",
"\"Cannot save a document not in... | 41.333333 | 30.666667 |
def on_save(self, event):
'''called on save button'''
dlg = wx.FileDialog(None, self.settings.get_title(), '', "", '*.*',
wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
self.settings.save(dlg.GetPath()) | [
"def",
"on_save",
"(",
"self",
",",
"event",
")",
":",
"dlg",
"=",
"wx",
".",
"FileDialog",
"(",
"None",
",",
"self",
".",
"settings",
".",
"get_title",
"(",
")",
",",
"''",
",",
"\"\"",
",",
"'*.*'",
",",
"wx",
".",
"FD_SAVE",
"|",
"wx",
".",
... | 47.166667 | 14.166667 |
def svm_score(self, x):
x = x[1:]
'''
original_X = self.svm_processor.train_X[:, 1:]
score = 0
for i in range(len(self.svm_processor.sv_alpha)):
score += self.svm_processor.sv_alpha[i] * self.svm_processor.sv_Y[i] * utility.Kernel.gaussian_kernel(self, original_X[se... | [
"def",
"svm_score",
"(",
"self",
",",
"x",
")",
":",
"x",
"=",
"x",
"[",
"1",
":",
"]",
"score",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"svm_processor",
".",
"sv_alpha",
"*",
"self",
".",
"svm_processor",
".",
"sv_Y",
"*",
"utility",
".",
"Kern... | 40.133333 | 40.266667 |
def inc_ptr(self, ptr):
"""Get next circular buffer data pointer."""
result = ptr + self.reading_len[self.ws_type]
if result >= 0x10000:
result = self.data_start
return result | [
"def",
"inc_ptr",
"(",
"self",
",",
"ptr",
")",
":",
"result",
"=",
"ptr",
"+",
"self",
".",
"reading_len",
"[",
"self",
".",
"ws_type",
"]",
"if",
"result",
">=",
"0x10000",
":",
"result",
"=",
"self",
".",
"data_start",
"return",
"result"
] | 35.666667 | 10.666667 |
def get_client_alg_keys(client):
"""
Takes a client and returns the set of keys associated with it.
Returns a list of keys.
"""
if client.jwt_alg == 'RS256':
keys = []
for rsakey in RSAKey.objects.all():
keys.append(jwk_RSAKey(key=importKey(rsakey.key), kid=rsakey.kid))
... | [
"def",
"get_client_alg_keys",
"(",
"client",
")",
":",
"if",
"client",
".",
"jwt_alg",
"==",
"'RS256'",
":",
"keys",
"=",
"[",
"]",
"for",
"rsakey",
"in",
"RSAKey",
".",
"objects",
".",
"all",
"(",
")",
":",
"keys",
".",
"append",
"(",
"jwk_RSAKey",
... | 33.882353 | 18 |
def output(self):
""" Produce a classic generator for this cell's final results. """
starters = self.finalize()
try:
yield from self._output(starters)
finally:
self.close() | [
"def",
"output",
"(",
"self",
")",
":",
"starters",
"=",
"self",
".",
"finalize",
"(",
")",
"try",
":",
"yield",
"from",
"self",
".",
"_output",
"(",
"starters",
")",
"finally",
":",
"self",
".",
"close",
"(",
")"
] | 31.714286 | 14.571429 |
def word_starts(self):
"""The list of start positions representing ``words`` layer elements."""
if not self.is_tagged(WORDS):
self.tokenize_words()
return self.starts(WORDS) | [
"def",
"word_starts",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"WORDS",
")",
":",
"self",
".",
"tokenize_words",
"(",
")",
"return",
"self",
".",
"starts",
"(",
"WORDS",
")"
] | 41 | 7 |
def wrap_once(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed, unless layout object's parent is already a subclass of
`LayoutClass`.
"""
def wrap_object_once(layout_o... | [
"def",
"wrap_once",
"(",
"self",
",",
"LayoutClass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap_object_once",
"(",
"layout_object",
",",
"j",
")",
":",
"if",
"not",
"isinstance",
"(",
"layout_object",
",",
"LayoutClass",
")",
":",
... | 44 | 21.230769 |
def reset(self):
""" Reset the connection
"""
self._request = None
self._response = None
self._transaction_id = uuid.uuid4().hex | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"_request",
"=",
"None",
"self",
".",
"_response",
"=",
"None",
"self",
".",
"_transaction_id",
"=",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex"
] | 23.285714 | 13.428571 |
def background(self):
"""Only a getter on purpose. See the tests."""
if self._background is None:
self._background = GSBackgroundLayer()
self._background._foreground = self
return self._background | [
"def",
"background",
"(",
"self",
")",
":",
"if",
"self",
".",
"_background",
"is",
"None",
":",
"self",
".",
"_background",
"=",
"GSBackgroundLayer",
"(",
")",
"self",
".",
"_background",
".",
"_foreground",
"=",
"self",
"return",
"self",
".",
"_backgroun... | 39.833333 | 8.166667 |
def vlm_add_broadcast(self, psz_name, psz_input, psz_output, i_options, ppsz_options, b_enabled, b_loop):
'''Add a broadcast, with one input.
@param psz_name: the name of the new broadcast.
@param psz_input: the input MRL.
@param psz_output: the output MRL (the parameter to the "sout" va... | [
"def",
"vlm_add_broadcast",
"(",
"self",
",",
"psz_name",
",",
"psz_input",
",",
"psz_output",
",",
"i_options",
",",
"ppsz_options",
",",
"b_enabled",
",",
"b_loop",
")",
":",
"return",
"libvlc_vlm_add_broadcast",
"(",
"self",
",",
"str_to_bytes",
"(",
"psz_nam... | 64.5 | 29.333333 |
def webui_schematics_assets_asset_asset_type_image_base_64_image(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
webui = ET.SubElement(config, "webui", xmlns="http://tail-f.com/ns/webui")
schematics = ET.SubElement(webui, "schematics")
assets = E... | [
"def",
"webui_schematics_assets_asset_asset_type_image_base_64_image",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"webui",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"webui\"",
",",
"xm... | 46.647059 | 15.058824 |
def allocate_series_dataframes(network, series):
"""
Populate time-varying outputs with default values.
Parameters
----------
network : pypsa.Network
series : dict
Dictionary of components and their attributes to populate (see example)
Returns
-------
None
Examples
... | [
"def",
"allocate_series_dataframes",
"(",
"network",
",",
"series",
")",
":",
"for",
"component",
",",
"attributes",
"in",
"iteritems",
"(",
"series",
")",
":",
"df",
"=",
"network",
".",
"df",
"(",
"component",
")",
"pnl",
"=",
"network",
".",
"pnl",
"(... | 26.310345 | 25.482759 |
def list_images(self):
"""
list all available nspawn images
:return: collection of instances of :class:`conu.backend.nspawn.image.NspawnImage`
"""
# Fedora-Cloud-Base-27-1.6.x86_64 raw no 601.7M Sun 2017-11-05 08:30:10 CET \
# Sun 2017-11-05 08:30:10 CET
data... | [
"def",
"list_images",
"(",
"self",
")",
":",
"# Fedora-Cloud-Base-27-1.6.x86_64 raw no 601.7M Sun 2017-11-05 08:30:10 CET \\",
"# Sun 2017-11-05 08:30:10 CET",
"data",
"=",
"os",
".",
"listdir",
"(",
"CONU_IMAGES_STORE",
")",
"output",
"=",
"[",
"]",
"for",
"name",
"i... | 37.846154 | 19.846154 |
def cancelHistoricalData(self, contracts=None):
""" cancel historical data stream """
if contracts == None:
contracts = list(self.contracts.values())
elif not isinstance(contracts, list):
contracts = [contracts]
for contract in contracts:
# tickerId =... | [
"def",
"cancelHistoricalData",
"(",
"self",
",",
"contracts",
"=",
"None",
")",
":",
"if",
"contracts",
"==",
"None",
":",
"contracts",
"=",
"list",
"(",
"self",
".",
"contracts",
".",
"values",
"(",
")",
")",
"elif",
"not",
"isinstance",
"(",
"contracts... | 43.181818 | 14 |
def create(self,*fields,**kw):
"""Create a new base with specified field names
A keyword argument mode can be specified ; it is used if a file
with the base name already exists
- if mode = 'open' : open the existing base, ignore the fields
- if mode = 'override' : erase the ... | [
"def",
"create",
"(",
"self",
",",
"*",
"fields",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"mode",
"=",
"mode",
"=",
"kw",
".",
"get",
"(",
"\"mode\"",
",",
"None",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"name",
")"... | 42.652174 | 12.608696 |
def _format_obj_count(objects):
"""Formats object count."""
result = []
regex = re.compile(r'<(?P<type>\w+) \'(?P<name>\S+)\'>')
for obj_type, obj_count in objects.items():
if obj_count != 0:
match = re.findall(regex, repr(obj_type))
if match:
obj_type, ob... | [
"def",
"_format_obj_count",
"(",
"objects",
")",
":",
"result",
"=",
"[",
"]",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'<(?P<type>\\w+) \\'(?P<name>\\S+)\\'>'",
")",
"for",
"obj_type",
",",
"obj_count",
"in",
"objects",
".",
"items",
"(",
")",
":",
"if",
... | 42.727273 | 15.727273 |
def abfinfo(self,printToo=False,returnDict=False):
"""show basic info about ABF class variables."""
info="\n### ABF INFO ###\n"
d={}
for thingName in sorted(dir(self)):
if thingName in ['cm','evIs','colormap','dataX','dataY',
'protoX','protoY']:
... | [
"def",
"abfinfo",
"(",
"self",
",",
"printToo",
"=",
"False",
",",
"returnDict",
"=",
"False",
")",
":",
"info",
"=",
"\"\\n### ABF INFO ###\\n\"",
"d",
"=",
"{",
"}",
"for",
"thingName",
"in",
"sorted",
"(",
"dir",
"(",
"self",
")",
")",
":",
"if",
... | 35.166667 | 13.3 |
def json_data(self, extraneous=False):
"""Returns the JSON data form of this ``JsonRecord``. The 'unknown'
JSON keys will be merged back in, if:
1. the ``extraneous=True`` argument is passed.
2. the ``unknown_json_keys`` property on this class is replaced by one
not marked ... | [
"def",
"json_data",
"(",
"self",
",",
"extraneous",
"=",
"False",
")",
":",
"jd",
"=",
"to_json",
"(",
"self",
",",
"extraneous",
")",
"if",
"hasattr",
"(",
"self",
",",
"\"unknown_json_keys\"",
")",
":",
"prop",
"=",
"type",
"(",
"self",
")",
".",
"... | 41.411765 | 14.294118 |
def get_logfile_name(tags):
"""Formulates a log file name that incorporates the provided tags.
The log file will be located in ``scgpm_seqresults_dnanexus.LOG_DIR``.
Args:
tags: `list` of tags to append to the log file name. Each tag will be '_' delimited. Each tag
will be added in the same or... | [
"def",
"get_logfile_name",
"(",
"tags",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"sd",
".",
"LOG_DIR",
")",
":",
"os",
".",
"mkdir",
"(",
"sd",
".",
"LOG_DIR",
")",
"filename",
"=",
"\"log\"",
"for",
"tag",
"in",
"tags",
":",
... | 32.117647 | 20.529412 |
def cr(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None,
callback=None, residuals=None):
"""Conjugate Residual algorithm.
Solves the linear system Ax = b. Left preconditioning is supported.
The matrix A must be Hermitian symmetric (but not necessarily definite).
Parameters
--------... | [
"def",
"cr",
"(",
"A",
",",
"b",
",",
"x0",
"=",
"None",
",",
"tol",
"=",
"1e-5",
",",
"maxiter",
"=",
"None",
",",
"xtype",
"=",
"None",
",",
"M",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"residuals",
"=",
"None",
")",
":",
"A",
",",
... | 29.588571 | 21.24 |
def define_task(name,
tick_script,
task_type='stream',
database=None,
retention_policy='default',
dbrps=None):
'''
Define a task. Serves as both create/update.
name
Name of the task.
tick_script
Path to the... | [
"def",
"define_task",
"(",
"name",
",",
"tick_script",
",",
"task_type",
"=",
"'stream'",
",",
"database",
"=",
"None",
",",
"retention_policy",
"=",
"'default'",
",",
"dbrps",
"=",
"None",
")",
":",
"if",
"not",
"database",
"and",
"not",
"dbrps",
":",
"... | 25.636364 | 24.484848 |
def take_break(minutes: hug.types.number=5):
"""Enables temporarily breaking concentration"""
print("")
print("######################################### ARE YOU SURE? #####################################")
try:
for remaining in range(60, -1, -1):
sys.stdout.write("\r")
s... | [
"def",
"take_break",
"(",
"minutes",
":",
"hug",
".",
"types",
".",
"number",
"=",
"5",
")",
":",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"######################################### ARE YOU SURE? #####################################\"",
")",
"try",
":",
"for",
"r... | 40.363636 | 27.030303 |
def _make_context(self, request: 'Request'=None, state: Text=None):
"""
Build the context for a specific request/state
"""
if request:
self.client.user_context({
'id': request.user.id,
})
self.client.extra_context({
'me... | [
"def",
"_make_context",
"(",
"self",
",",
"request",
":",
"'Request'",
"=",
"None",
",",
"state",
":",
"Text",
"=",
"None",
")",
":",
"if",
"request",
":",
"self",
".",
"client",
".",
"user_context",
"(",
"{",
"'id'",
":",
"request",
".",
"user",
"."... | 35.157895 | 14.526316 |
def re_flags(flags, custom=ReFlags):
"""Parse regexp flag string.
Parameters
----------
flags: `str`
Flag string.
custom: `IntEnum`, optional
Custom flag enum (default: None).
Returns
-------
(`int`, `int`)
(flags for `re.compile`, custom flags)
Raises
... | [
"def",
"re_flags",
"(",
"flags",
",",
"custom",
"=",
"ReFlags",
")",
":",
"re_",
",",
"custom_",
"=",
"0",
",",
"0",
"for",
"flag",
"in",
"flags",
".",
"upper",
"(",
")",
":",
"try",
":",
"re_",
"|=",
"getattr",
"(",
"re",
",",
"flag",
")",
"ex... | 24.5 | 19.03125 |
def encode_signature(sig_r, sig_s):
"""
Encode an ECDSA signature, with low-s
"""
# enforce low-s
if sig_s * 2 >= SECP256k1_order:
log.debug("High-S to low-S")
sig_s = SECP256k1_order - sig_s
sig_bin = '{:064x}{:064x}'.format(sig_r, sig_s).decode('hex')
assert len(sig_bin) ... | [
"def",
"encode_signature",
"(",
"sig_r",
",",
"sig_s",
")",
":",
"# enforce low-s ",
"if",
"sig_s",
"*",
"2",
">=",
"SECP256k1_order",
":",
"log",
".",
"debug",
"(",
"\"High-S to low-S\"",
")",
"sig_s",
"=",
"SECP256k1_order",
"-",
"sig_s",
"sig_bin",
"=",
"... | 26.571429 | 12.428571 |
def expand_date_param(param, lower_upper):
"""
Expands a (possibly) incomplete date string to either the lowest
or highest possible contained date and returns
datetime.datetime for that string.
0753 (lower) => 0753-01-01
2012 (upper) => 2012-12-31
2012 (lower) => 2012-01-01
201208 (uppe... | [
"def",
"expand_date_param",
"(",
"param",
",",
"lower_upper",
")",
":",
"year",
"=",
"datetime",
".",
"MINYEAR",
"month",
"=",
"1",
"day",
"=",
"1",
"hour",
"=",
"0",
"minute",
"=",
"0",
"second",
"=",
"0",
"if",
"lower_upper",
"==",
"'upper'",
":",
... | 28.175 | 15.7 |
def _stop(self):
"""
(internal) stops input and output pool queue manager threads.
"""
if self._started.isSet():
# join threads
self._pool_getter.join()
self._pool_putter.join()
for worker in self.pool:
worker.join()
... | [
"def",
"_stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"_started",
".",
"isSet",
"(",
")",
":",
"# join threads",
"self",
".",
"_pool_getter",
".",
"join",
"(",
")",
"self",
".",
"_pool_putter",
".",
"join",
"(",
")",
"for",
"worker",
"in",
"self"... | 30.65 | 9.35 |
def command(self, command):
"""
Run a command on the currently active container.
:rtype: CommandReply
"""
return self._conn.command('[con_id="{}"] {}'.format(self.id, command)) | [
"def",
"command",
"(",
"self",
",",
"command",
")",
":",
"return",
"self",
".",
"_conn",
".",
"command",
"(",
"'[con_id=\"{}\"] {}'",
".",
"format",
"(",
"self",
".",
"id",
",",
"command",
")",
")"
] | 30.142857 | 17 |
def format_server_configuration_management_settings(result):
'''
Formats the ServerConfigurationsManagementSettings object removing arguments that are empty
'''
from collections import OrderedDict
order_dict = OrderedDict([('sqlConnectivityUpdateSettings',
format_sql_c... | [
"def",
"format_server_configuration_management_settings",
"(",
"result",
")",
":",
"from",
"collections",
"import",
"OrderedDict",
"order_dict",
"=",
"OrderedDict",
"(",
"[",
"(",
"'sqlConnectivityUpdateSettings'",
",",
"format_sql_connectivity_update_settings",
"(",
"result"... | 68.307692 | 47.692308 |
def Planck_2015(flat=False, extras=True):
"""Planck 2015 XII: Cosmological parameters Table 4
column Planck TT, TE, EE + lowP + lensing + ext
from Ade et al. (2015) A&A in press (arxiv:1502.01589v1)
Parameters
----------
flat: boolean
If True, sets omega_lambda_0 = 1 - omega_M_0 to ensu... | [
"def",
"Planck_2015",
"(",
"flat",
"=",
"False",
",",
"extras",
"=",
"True",
")",
":",
"omega_b_0",
"=",
"0.02230",
"/",
"(",
"0.6774",
"**",
"2",
")",
"cosmo",
"=",
"{",
"'omega_b_0'",
":",
"omega_b_0",
",",
"'omega_M_0'",
":",
"0.3089",
",",
"'omega_... | 27.638889 | 19.138889 |
def save(self, cfg, filename, print_ir=False, format='dot', options=None):
"""Save basic block graph into a file.
"""
if options is None:
options = {}
try:
dot_graph = Dot(**self.graph_format)
# Add nodes.
nodes = {}
for bb in... | [
"def",
"save",
"(",
"self",
",",
"cfg",
",",
"filename",
",",
"print_ir",
"=",
"False",
",",
"format",
"=",
"'dot'",
",",
"options",
"=",
"None",
")",
":",
"if",
"options",
"is",
"None",
":",
"options",
"=",
"{",
"}",
"try",
":",
"dot_graph",
"=",
... | 38.066667 | 25.033333 |
def payments(self, virtual_account_id, data={}, **kwargs):
""""
Fetch Payment for Virtual Account Id
Args:
virtual_account_id :
Id for which Virtual Account objects has to be retrieved
Returns:
Payment dict for given Virtual Account Id
""... | [
"def",
"payments",
"(",
"self",
",",
"virtual_account_id",
",",
"data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"\"{}/{}/payments\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"virtual_account_id",
")",
"return",
"self",
"."... | 33.153846 | 18.923077 |
def from_file(cls, fn, *args, **kwargs):
"""Constructor to build an AmiraHeader object from a file
:param str fn: Amira file
:return ah: object of class ``AmiraHeader`` containing header metadata
:rtype: ah: :py:class:`ahds.header.AmiraHeader`
"""
return AmiraHea... | [
"def",
"from_file",
"(",
"cls",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"AmiraHeader",
"(",
"get_parsed_data",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
")"
] | 44.25 | 14.5 |
def block_widths(self):
"""Gets the widths of the blocks.
Note: This works with the property structure `_widths_cache` to avoid
having to recompute these values each time they are needed.
"""
if self._widths_cache is None:
try:
# The first column ... | [
"def",
"block_widths",
"(",
"self",
")",
":",
"if",
"self",
".",
"_widths_cache",
"is",
"None",
":",
"try",
":",
"# The first column will have the correct lengths. We have an",
"# invariant that requires that all blocks be the same width in a",
"# column of blocks.",
"self",
".... | 42.368421 | 17.947368 |
def _tokenize_latex(self, exp):
"""
Internal method to tokenize latex
"""
tokens = []
prevexp = ""
while exp:
t, exp = self._get_next_token(exp)
if t.strip() != "":
tokens.append(t)
if prevexp == exp:
bre... | [
"def",
"_tokenize_latex",
"(",
"self",
",",
"exp",
")",
":",
"tokens",
"=",
"[",
"]",
"prevexp",
"=",
"\"\"",
"while",
"exp",
":",
"t",
",",
"exp",
"=",
"self",
".",
"_get_next_token",
"(",
"exp",
")",
"if",
"t",
".",
"strip",
"(",
")",
"!=",
"\"... | 25.5 | 11.357143 |
def detag_string(self, string):
"""Extracts tags from string.
returns (string, list) where
string: string has tags replaced by indices (<BR>... => <0>, <1>, <2>, etc.)
list: list of the removed tags ('<BR>', '<I>', '</I>')
"""
counter = itertools.count(0)
... | [
"def",
"detag_string",
"(",
"self",
",",
"string",
")",
":",
"counter",
"=",
"itertools",
".",
"count",
"(",
"0",
")",
"count",
"=",
"lambda",
"m",
":",
"'<%s>'",
"%",
"next",
"(",
"counter",
")",
"tags",
"=",
"self",
".",
"tag_pattern",
".",
"findal... | 41.266667 | 13.666667 |
def filter_by_analysis_period(self, analysis_period):
"""Filter the Data Collection based on an analysis period.
Args:
analysis period: A Ladybug analysis period
Return:
A new Data Collection with filtered data
"""
self._check_analysis_period(analysis_per... | [
"def",
"filter_by_analysis_period",
"(",
"self",
",",
"analysis_period",
")",
":",
"self",
".",
"_check_analysis_period",
"(",
"analysis_period",
")",
"_filtered_data",
"=",
"self",
".",
"filter_by_doys",
"(",
"analysis_period",
".",
"doys_int",
")",
"_filtered_data",... | 36.769231 | 19 |
def optimize(self, init_method='default', inference=None, n_times=10, perturb=False, pertSize=1e-3, verbose=None):
"""
Train the model using the specified initialization strategy
Args:
init_method: initialization strategy:
'default': variance is eq... | [
"def",
"optimize",
"(",
"self",
",",
"init_method",
"=",
"'default'",
",",
"inference",
"=",
"None",
",",
"n_times",
"=",
"10",
",",
"perturb",
"=",
"False",
",",
"pertSize",
"=",
"1e-3",
",",
"verbose",
"=",
"None",
")",
":",
"#verbose = dlimix.getVerbose... | 56.270833 | 35.729167 |
def scope_required(*scopes):
"""
Test for specific scopes that the access token has been authenticated for before
processing the request and eventual response.
The scopes that are passed in determine how the decorator will respond to incoming
requests:
- If no scopes are passed in the argument... | [
"def",
"scope_required",
"(",
"*",
"scopes",
")",
":",
"def",
"decorator",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
",",
"assigned",
"=",
"available_attrs",
"(",
"view_func",
")",
")",
"def",
"_wrapped_view",
"(",
"request",
",",
"*",
... | 39.056338 | 24.042254 |
def init_config_json(config_file):
"""Deserializes a JSON configuration file.
Args:
config_file (str): The path to the JSON file.
Returns:
dict: A dictionary object containing the JSON data. If ``config_file`` does not exist, returns ``None``.
"""
json_data = None
try:
... | [
"def",
"init_config_json",
"(",
"config_file",
")",
":",
"json_data",
"=",
"None",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"#Load the config file",
"with",
"open",
"(",
"config_file",
")",
"as",
"json_file",
":",
"... | 28.088235 | 18.529412 |
def batched(iterable, size):
"""
Split an iterable into constant sized chunks
Recipe from http://stackoverflow.com/a/8290514
"""
length = len(iterable)
for batch_start in range(0, length, size):
yield iterable[batch_start:batch_start+size] | [
"def",
"batched",
"(",
"iterable",
",",
"size",
")",
":",
"length",
"=",
"len",
"(",
"iterable",
")",
"for",
"batch_start",
"in",
"range",
"(",
"0",
",",
"length",
",",
"size",
")",
":",
"yield",
"iterable",
"[",
"batch_start",
":",
"batch_start",
"+",... | 33 | 7.75 |
def cross_product(x1, y1, z1, x2, y2, z2):
"""
Cross product of two vectors, v1 x v2
Parameters
----------
x1 : float or array-like
X component of vector 1
y1 : float or array-like
Y component of vector 1
z1 : float or array-like
Z component of vector 1
x2 : ... | [
"def",
"cross_product",
"(",
"x1",
",",
"y1",
",",
"z1",
",",
"x2",
",",
"y2",
",",
"z2",
")",
":",
"x",
"=",
"y1",
"*",
"z2",
"-",
"y2",
"*",
"z1",
"y",
"=",
"z1",
"*",
"x2",
"-",
"x1",
"*",
"z2",
"z",
"=",
"x1",
"*",
"y2",
"-",
"y1",
... | 22.37931 | 15.551724 |
def clear(self):
"""Clear all data from this sensor_log.
All readings in all walkers are skipped and buffered data is
destroyed.
"""
for walker in self._virtual_walkers:
walker.skip_all()
self._engine.clear()
for walker in self._queue_walkers:
... | [
"def",
"clear",
"(",
"self",
")",
":",
"for",
"walker",
"in",
"self",
".",
"_virtual_walkers",
":",
"walker",
".",
"skip_all",
"(",
")",
"self",
".",
"_engine",
".",
"clear",
"(",
")",
"for",
"walker",
"in",
"self",
".",
"_queue_walkers",
":",
"walker"... | 22.625 | 20.25 |
def get_next_action(self, request, application, roles):
""" Retrieve the next state. """
application.reopen()
link, is_secret = base.get_email_link(application)
emails.send_invite_email(application, link, is_secret)
messages.success(
request,
"Sent an invi... | [
"def",
"get_next_action",
"(",
"self",
",",
"request",
",",
"application",
",",
"roles",
")",
":",
"application",
".",
"reopen",
"(",
")",
"link",
",",
"is_secret",
"=",
"base",
".",
"get_email_link",
"(",
"application",
")",
"emails",
".",
"send_invite_emai... | 39.3 | 12.1 |
def set_vm_status(self, device='FLOPPY',
boot_option='BOOT_ONCE', write_protect='YES'):
"""Sets the Virtual Media drive status
It sets the boot option for virtual media device.
Note: boot option can be set only for CD device.
:param device: virual media device
... | [
"def",
"set_vm_status",
"(",
"self",
",",
"device",
"=",
"'FLOPPY'",
",",
"boot_option",
"=",
"'BOOT_ONCE'",
",",
"write_protect",
"=",
"'YES'",
")",
":",
"# CONNECT is a RIBCL call. There is no such property to set in Redfish.",
"if",
"boot_option",
"==",
"'CONNECT'",
... | 43.868421 | 20.263158 |
def _sanitise(self):
"""
Convert attributes of type npumpy.float32 to numpy.float64 so that they will print properly.
"""
for k in self.__dict__:
if isinstance(self.__dict__[k], np.float32): # np.float32 has a broken __str__ method
self.__dict__[k] = np.float... | [
"def",
"_sanitise",
"(",
"self",
")",
":",
"for",
"k",
"in",
"self",
".",
"__dict__",
":",
"if",
"isinstance",
"(",
"self",
".",
"__dict__",
"[",
"k",
"]",
",",
"np",
".",
"float32",
")",
":",
"# np.float32 has a broken __str__ method",
"self",
".",
"__d... | 47.714286 | 24.285714 |
def set_options_from_dict(self, data_dict, filename=None):
"""Load options from a dictionary.
:param dict data_dict: Dictionary with the options to load.
:param str filename: If provided, assume that non-absolute
paths provided are in reference to the file.
"""
if fi... | [
"def",
"set_options_from_dict",
"(",
"self",
",",
"data_dict",
",",
"filename",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"not",
"None",
":",
"filename",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"for",
"k",
"in",
"data_dict",
... | 50.30303 | 17.969697 |
def get_removes(self, api=None, profile=None):
"""Returns filtered list of Remove objects in this registry
:param str api: Return Remove objects with this api name or None to
return all Remove objects.
:param str profile: Return Remove objects with this profile or None
... | [
"def",
"get_removes",
"(",
"self",
",",
"api",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"out",
"=",
"[",
"]",
"for",
"ft",
"in",
"self",
".",
"get_features",
"(",
"api",
")",
":",
"out",
".",
"extend",
"(",
"ft",
".",
"get_removes",
"(... | 41.692308 | 15.230769 |
def format_cftime_datetime(date):
"""Converts a cftime.datetime object to a string with the format:
YYYY-MM-DD HH:MM:SS.UUUUUU
"""
return '{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:06d}'.format(
date.year, date.month, date.day, date.hour, date.minute, date.second,
date.microsecond) | [
"def",
"format_cftime_datetime",
"(",
"date",
")",
":",
"return",
"'{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:06d}'",
".",
"format",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
",",
"date",
".",
"hour",
",",
"date",
".",
"... | 44.285714 | 14 |
def height_to_pressure_std(height):
r"""Convert height data to pressures using the U.S. standard atmosphere.
The implementation inverts the formula outlined in [Hobbs1977]_ pg.60-61.
Parameters
----------
height : `pint.Quantity`
Atmospheric height
Returns
-------
`pint.Quanti... | [
"def",
"height_to_pressure_std",
"(",
"height",
")",
":",
"t0",
"=",
"288.",
"*",
"units",
".",
"kelvin",
"gamma",
"=",
"6.5",
"*",
"units",
"(",
"'K/km'",
")",
"p0",
"=",
"1013.25",
"*",
"units",
".",
"mbar",
"return",
"p0",
"*",
"(",
"1",
"-",
"(... | 26.166667 | 24.041667 |
def install_pip(env, requirements):
"""Install pip and its requirements using setuptools."""
try:
installation_source_folder = config.installation_cache_folder()
options = setuptools_install_options(installation_source_folder)
if installation_source_folder is not None:
... | [
"def",
"install_pip",
"(",
"env",
",",
"requirements",
")",
":",
"try",
":",
"installation_source_folder",
"=",
"config",
".",
"installation_cache_folder",
"(",
")",
"options",
"=",
"setuptools_install_options",
"(",
"installation_source_folder",
")",
"if",
"installat... | 47.75 | 19.166667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.