text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def grid_destroy_from_ids(oargrid_jobids):
"""Destroy all the jobs with corresponding ids
Args:
oargrid_jobids (list): the ``(site, oar_job_id)`` list of tuple
identifying the jobs for each site. """
jobs = grid_reload_from_ids(oargrid_jobids)
for job in jobs:
job.delete()
... | [
"def",
"grid_destroy_from_ids",
"(",
"oargrid_jobids",
")",
":",
"jobs",
"=",
"grid_reload_from_ids",
"(",
"oargrid_jobids",
")",
"for",
"job",
"in",
"jobs",
":",
"job",
".",
"delete",
"(",
")",
"logger",
".",
"info",
"(",
"\"Killing the jobs %s\"",
"%",
"oarg... | 36.9 | 17 |
def _objectdata_cache_key(func, obj):
"""Cache Key for object data
"""
uid = api.get_uid(obj)
modified = api.get_modification_date(obj).millis()
review_state = api.get_review_status(obj)
return "{}-{}-{}".format(uid, review_state, modified) | [
"def",
"_objectdata_cache_key",
"(",
"func",
",",
"obj",
")",
":",
"uid",
"=",
"api",
".",
"get_uid",
"(",
"obj",
")",
"modified",
"=",
"api",
".",
"get_modification_date",
"(",
"obj",
")",
".",
"millis",
"(",
")",
"review_state",
"=",
"api",
".",
"get... | 36.857143 | 7.571429 |
def _ParseDLSPageHeader(self, file_object, page_offset):
"""Parses a DLS page header from a file-like object.
Args:
file_object (file): file-like object to read the header from.
page_offset (int): offset of the start of the page header, relative
to the start of the file.
Returns:
... | [
"def",
"_ParseDLSPageHeader",
"(",
"self",
",",
"file_object",
",",
"page_offset",
")",
":",
"page_header_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'dls_page_header'",
")",
"try",
":",
"page_header",
",",
"page_size",
"=",
"self",
".",
"_ReadStructureFromFi... | 33.242424 | 22.181818 |
def predict(self, log2_bayes_factors, reset_index=False):
"""Guess the most likely modality for each event
For each event that has at least one non-NA value, if no modalilites
have logsumexp'd logliks greater than the log Bayes factor threshold,
then they are assigned the 'multimodal' m... | [
"def",
"predict",
"(",
"self",
",",
"log2_bayes_factors",
",",
"reset_index",
"=",
"False",
")",
":",
"if",
"reset_index",
":",
"x",
"=",
"log2_bayes_factors",
".",
"reset_index",
"(",
"level",
"=",
"0",
",",
"drop",
"=",
"True",
")",
"else",
":",
"x",
... | 42.131579 | 21.526316 |
def has_connection_details_changed(self, req_connection_details):
"""
:param cloudshell.cp.vcenter.models.VCenterConnectionDetails.VCenterConnectionDetails req_connection_details:
:return:
"""
if self.connection_details is None and req_connection_details is None:
retu... | [
"def",
"has_connection_details_changed",
"(",
"self",
",",
"req_connection_details",
")",
":",
"if",
"self",
".",
"connection_details",
"is",
"None",
"and",
"req_connection_details",
"is",
"None",
":",
"return",
"False",
"if",
"self",
".",
"connection_details",
"is"... | 59.615385 | 32.846154 |
def set_pattern_step_setpoint(self, patternnumber, stepnumber, setpointvalue):
"""Set the setpoint value for a step.
Args:
* patternnumber (integer): 0-7
* stepnumber (integer): 0-7
* setpointvalue (float): Setpoint value
"""
_checkPatternNumber(patte... | [
"def",
"set_pattern_step_setpoint",
"(",
"self",
",",
"patternnumber",
",",
"stepnumber",
",",
"setpointvalue",
")",
":",
"_checkPatternNumber",
"(",
"patternnumber",
")",
"_checkStepNumber",
"(",
"stepnumber",
")",
"_checkSetpointValue",
"(",
"setpointvalue",
",",
"s... | 40.142857 | 16.714286 |
def meth_set_acl(args):
""" Assign an ACL role to a list of users for a workflow. """
acl_updates = [{"user": user, "role": args.role} \
for user in set(expand_fc_groups(args.users)) \
if user != fapi.whoami()]
id = args.snapshot_id
if not id:
# get the lat... | [
"def",
"meth_set_acl",
"(",
"args",
")",
":",
"acl_updates",
"=",
"[",
"{",
"\"user\"",
":",
"user",
",",
"\"role\"",
":",
"args",
".",
"role",
"}",
"for",
"user",
"in",
"set",
"(",
"expand_fc_groups",
"(",
"args",
".",
"users",
")",
")",
"if",
"user... | 43.607143 | 19.785714 |
def transform(self, text):
"""Replaces characters in string ``text`` based in regex sub"""
return re.sub(self.regex, self.repl, text) | [
"def",
"transform",
"(",
"self",
",",
"text",
")",
":",
"return",
"re",
".",
"sub",
"(",
"self",
".",
"regex",
",",
"self",
".",
"repl",
",",
"text",
")"
] | 49 | 8 |
def retry_on_signal(function):
"""Retries function until it doesn't raise an EINTR error"""
while True:
try:
return function()
except EnvironmentError, e:
if e.errno != errno.EINTR:
raise | [
"def",
"retry_on_signal",
"(",
"function",
")",
":",
"while",
"True",
":",
"try",
":",
"return",
"function",
"(",
")",
"except",
"EnvironmentError",
",",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"EINTR",
":",
"raise"
] | 30.5 | 12.5 |
def infer_dtypes(fit, model=None):
"""Infer dtypes from Stan model code.
Function strips out generated quantities block and searchs for `int`
dtypes after stripping out comments inside the block.
"""
pattern_remove_comments = re.compile(
r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\... | [
"def",
"infer_dtypes",
"(",
"fit",
",",
"model",
"=",
"None",
")",
":",
"pattern_remove_comments",
"=",
"re",
".",
"compile",
"(",
"r'//.*?$|/\\*.*?\\*/|\\'(?:\\\\.|[^\\\\\\'])*\\'|\"(?:\\\\.|[^\\\\\"])*\"'",
",",
"re",
".",
"DOTALL",
"|",
"re",
".",
"MULTILINE",
")... | 42.806452 | 21.193548 |
def nmap_scan():
"""
Scans the given hosts with nmap.
"""
# Create the search and config objects
hs = HostSearch()
config = Config()
# Static options to be able to figure out what options to use depending on the input the user gives.
nmap_types = ['top10', 'top100', 'custom', 'top10... | [
"def",
"nmap_scan",
"(",
")",
":",
"# Create the search and config objects",
"hs",
"=",
"HostSearch",
"(",
")",
"config",
"=",
"Config",
"(",
")",
"# Static options to be able to figure out what options to use depending on the input the user gives.",
"nmap_types",
"=",
"[",
"... | 43.571429 | 26.673469 |
def use(self, obj, parent_form=None):
"""Note: if title is None, will be replaced with obj.filename
"""
if not isinstance(obj, self.input_classes):
raise RuntimeError('{0!s} cannot handle a {1!s}'.format(self.__class__.__name__, obj.__class__.__name__))
self.parent_form = p... | [
"def",
"use",
"(",
"self",
",",
"obj",
",",
"parent_form",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"self",
".",
"input_classes",
")",
":",
"raise",
"RuntimeError",
"(",
"'{0!s} cannot handle a {1!s}'",
".",
"format",
"(",
"self",... | 35.333333 | 20.333333 |
def _get_program(self):
"""
Fetch the module binary from the master if necessary.
"""
return ansible_mitogen.target.get_small_file(
context=self.service_context,
path=self.path,
) | [
"def",
"_get_program",
"(",
"self",
")",
":",
"return",
"ansible_mitogen",
".",
"target",
".",
"get_small_file",
"(",
"context",
"=",
"self",
".",
"service_context",
",",
"path",
"=",
"self",
".",
"path",
",",
")"
] | 29.5 | 12 |
def DeserializeTX(buffer):
"""
Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction:
"""
mstream = MemoryStream(buffer)
reader = BinaryReade... | [
"def",
"DeserializeTX",
"(",
"buffer",
")",
":",
"mstream",
"=",
"MemoryStream",
"(",
"buffer",
")",
"reader",
"=",
"BinaryReader",
"(",
"mstream",
")",
"tx",
"=",
"Transaction",
".",
"DeserializeFrom",
"(",
"reader",
")",
"return",
"tx"
] | 24 | 19.625 |
def run_container(self, image_id, service_name, **kwargs):
"""Run a particular container. The kwargs argument contains individual
parameter overrides from the service definition."""
run_kwargs = self.run_kwargs_for_service(service_name)
run_kwargs.update(kwargs, relax=True)
logge... | [
"def",
"run_container",
"(",
"self",
",",
"image_id",
",",
"service_name",
",",
"*",
"*",
"kwargs",
")",
":",
"run_kwargs",
"=",
"self",
".",
"run_kwargs_for_service",
"(",
"service_name",
")",
"run_kwargs",
".",
"update",
"(",
"kwargs",
",",
"relax",
"=",
... | 42 | 18.411765 |
def summarize_subgraph_edge_overlap(graph: BELGraph, annotation: str = 'Subgraph') -> Mapping[str, Mapping[str, float]]:
"""Return a similarity matrix between all subgraphs (or other given annotation).
:param annotation: The annotation to group by and compare. Defaults to :code:`"Subgraph"`
:return: A simi... | [
"def",
"summarize_subgraph_edge_overlap",
"(",
"graph",
":",
"BELGraph",
",",
"annotation",
":",
"str",
"=",
"'Subgraph'",
")",
"->",
"Mapping",
"[",
"str",
",",
"Mapping",
"[",
"str",
",",
"float",
"]",
"]",
":",
"_",
",",
"_",
",",
"_",
",",
"subgrap... | 53.333333 | 29.222222 |
def raw_input(prompt=""):
"""raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline befo... | [
"def",
"raw_input",
"(",
"prompt",
"=",
"\"\"",
")",
":",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"tty",
"=",
"STDIN",
".",
"is_a_TTY",
"(",
")",
"and",
"STDOUT",
".",
"is_a_TTY",
"(",
")",
"if",
"RETURN_UNICODE",
":",
"if",
"tty",
":",
"line... | 24.233333 | 22.733333 |
def as_list(callable):
"""Convert a scalar validator in a list validator"""
@wraps(callable)
def wrapper(value_iter):
return [callable(value) for value in value_iter]
return wrapper | [
"def",
"as_list",
"(",
"callable",
")",
":",
"@",
"wraps",
"(",
"callable",
")",
"def",
"wrapper",
"(",
"value_iter",
")",
":",
"return",
"[",
"callable",
"(",
"value",
")",
"for",
"value",
"in",
"value_iter",
"]",
"return",
"wrapper"
] | 28.571429 | 18.285714 |
def get_bounding_box(self):
"""
Returns the bounding box of the catalogue
:returns: (West, East, South, North)
"""
return (np.min(self.data["longitude"]),
np.max(self.data["longitude"]),
np.min(self.data["latitude"]),
np.max(self.d... | [
"def",
"get_bounding_box",
"(",
"self",
")",
":",
"return",
"(",
"np",
".",
"min",
"(",
"self",
".",
"data",
"[",
"\"longitude\"",
"]",
")",
",",
"np",
".",
"max",
"(",
"self",
".",
"data",
"[",
"\"longitude\"",
"]",
")",
",",
"np",
".",
"min",
"... | 32.8 | 9.2 |
def handle_exception(self, e):
"""Default exception handling that kicks in when an exception
occurs that is not caught. In debug mode the exception will
be re-raised immediately, otherwise it is logged and the handler
for a 500 internal server error is used. If no such handler
... | [
"def",
"handle_exception",
"(",
"self",
",",
"e",
")",
":",
"exc_type",
",",
"exc_value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"got_request_exception",
".",
"send",
"(",
"self",
",",
"exception",
"=",
"e",
")",
"handler",
"=",
"self",
".",... | 40.785714 | 19.5 |
def _calc_covariance(r, pmut, tol=1e-14):
"""Calculate the covariance matrix of the fitted parameters
Parameters:
r - n-by-n matrix, the full upper triangle of R
pmut - n-vector, defines the permutation of R
tol - scalar, relative column scale for determining rank
deficiency. Default 1e-14.
Returns:
co... | [
"def",
"_calc_covariance",
"(",
"r",
",",
"pmut",
",",
"tol",
"=",
"1e-14",
")",
":",
"# This routine could save an allocation by operating on r in-place,",
"# which might be worthwhile for large n, and is what the original",
"# Fortran does.",
"n",
"=",
"r",
".",
"shape",
"[... | 26.232323 | 23.969697 |
def data_type(self, data_type):
"""Sets the data_type of this Option.
:param data_type: The data_type of this Option.
:type: str
"""
allowed_values = ["string", "number", "date", "color"]
if data_type is not None and data_type not in allowed_values:
raise Va... | [
"def",
"data_type",
"(",
"self",
",",
"data_type",
")",
":",
"allowed_values",
"=",
"[",
"\"string\"",
",",
"\"number\"",
",",
"\"date\"",
",",
"\"color\"",
"]",
"if",
"data_type",
"is",
"not",
"None",
"and",
"data_type",
"not",
"in",
"allowed_values",
":",
... | 32.733333 | 20.2 |
def boundary(ax, scale, axes_colors=None, **kwargs):
"""
Plots the boundary of the simplex. Creates and returns matplotlib axis if
none given.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
kwargs:
... | [
"def",
"boundary",
"(",
"ax",
",",
"scale",
",",
"axes_colors",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Set default color as black.",
"if",
"axes_colors",
"is",
"None",
":",
"axes_colors",
"=",
"dict",
"(",
")",
"for",
"_axis",
"in",
"[",
"'l'... | 31.827586 | 19 |
def _set_gre(self, v, load=False):
"""
Setter method for gre, mapped from YANG variable /interface/tunnel/mode/gre (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_gre is considered as a private
method. Backends looking to populate this variable should
... | [
"def",
"_set_gre",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"... | 68.045455 | 31.681818 |
def get_weather_forecast(self, latitude, longitude, start, end,
frequency=1, reading_type=None):
"""
Return the weather forecast for a given location for specific
datetime specified in UTC format.
::
results = ws.get_weather_forecast(lat, long, start, end)
... | [
"def",
"get_weather_forecast",
"(",
"self",
",",
"latitude",
",",
"longitude",
",",
"start",
",",
"end",
",",
"frequency",
"=",
"1",
",",
"reading_type",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"# Can get data from NWS1 or NWS3 representing 1-hr and 3-hr",... | 37.162162 | 19.216216 |
def format_pathname(
pathname,
max_length):
"""
Format a pathname
:param str pathname: Pathname to format
:param int max_length: Maximum length of result pathname (> 3)
:return: Formatted pathname
:rtype: str
:raises ValueError: If *max_length* is not larger than 3
This... | [
"def",
"format_pathname",
"(",
"pathname",
",",
"max_length",
")",
":",
"if",
"max_length",
"<=",
"3",
":",
"raise",
"ValueError",
"(",
"\"max length must be larger than 3\"",
")",
"if",
"len",
"(",
"pathname",
")",
">",
"max_length",
":",
"pathname",
"=",
"\"... | 33.52 | 22.08 |
def _cur_band_filled(self):
"""Checks if the current band is filled.
The size of the current band should be equal to s_max_1"""
cur_band = self._hyperbands[self._state["band_idx"]]
return len(cur_band) == self._s_max_1 | [
"def",
"_cur_band_filled",
"(",
"self",
")",
":",
"cur_band",
"=",
"self",
".",
"_hyperbands",
"[",
"self",
".",
"_state",
"[",
"\"band_idx\"",
"]",
"]",
"return",
"len",
"(",
"cur_band",
")",
"==",
"self",
".",
"_s_max_1"
] | 35.142857 | 16.857143 |
def add(self, x, axis):
"""Function to add 3D View with vector or 2D array (type = numpy.ndarray or 2D Field or 2D View) or 2D View with vector (type = numpy.ndarray)
:param x: array(1D, 2D) or field (2D) or View(2D)
:param axis: specifies axis, eg. axis = (1,2) plane lies in yz-plane, axis=0 ve... | [
"def",
"add",
"(",
"self",
",",
"x",
",",
"axis",
")",
":",
"return",
"self",
".",
"__array_op",
"(",
"operator",
".",
"add",
",",
"x",
",",
"axis",
")"
] | 66.571429 | 19.857143 |
def delete(self, shift='up'):
"""
Deletes the cells associated with the range.
:param str shift: Optional. Specifies which way to shift the cells.
The possible values are: up, left.
"""
url = self.build_url(self._endpoints.get('delete_range'))
return bool(self.se... | [
"def",
"delete",
"(",
"self",
",",
"shift",
"=",
"'up'",
")",
":",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'delete_range'",
")",
")",
"return",
"bool",
"(",
"self",
".",
"session",
".",
"post",
"(",
"... | 45.625 | 15.625 |
def _rm_name_match(s1, s2):
"""
determine whether two sequence names from a repeatmasker alignment match.
:return: True if they are the same string, or if one forms a substring of the
other, else False
"""
m_len = min(len(s1), len(s2))
return s1[:m_len] == s2[:m_len] | [
"def",
"_rm_name_match",
"(",
"s1",
",",
"s2",
")",
":",
"m_len",
"=",
"min",
"(",
"len",
"(",
"s1",
")",
",",
"len",
"(",
"s2",
")",
")",
"return",
"s1",
"[",
":",
"m_len",
"]",
"==",
"s2",
"[",
":",
"m_len",
"]"
] | 31.444444 | 17.222222 |
def load_dframe(self, dframe):
"""
Load the file contents into the supplied dataframe using the
specified key and filetype.
"""
filename_series = dframe[self.key]
loaded_data = filename_series.map(self.filetype.data)
keys = [list(el.keys()) for el in loaded_data.v... | [
"def",
"load_dframe",
"(",
"self",
",",
"dframe",
")",
":",
"filename_series",
"=",
"dframe",
"[",
"self",
".",
"key",
"]",
"loaded_data",
"=",
"filename_series",
".",
"map",
"(",
"self",
".",
"filetype",
".",
"data",
")",
"keys",
"=",
"[",
"list",
"("... | 46.5 | 16.375 |
def serialize(self, tag):
"""Return the literal representation of a tag."""
handler = getattr(self, f'serialize_{tag.serializer}', None)
if handler is None:
raise TypeError(f'Can\'t serialize {type(tag)!r} instance')
return handler(tag) | [
"def",
"serialize",
"(",
"self",
",",
"tag",
")",
":",
"handler",
"=",
"getattr",
"(",
"self",
",",
"f'serialize_{tag.serializer}'",
",",
"None",
")",
"if",
"handler",
"is",
"None",
":",
"raise",
"TypeError",
"(",
"f'Can\\'t serialize {type(tag)!r} instance'",
"... | 45.833333 | 16.666667 |
def _tile_images(imgs, tile_shape, concatenated_image):
"""Concatenate images whose sizes are same.
@param imgs: image list which should be concatenated
@param tile_shape: shape for which images should be concatenated
@param concatenated_image: returned image.
if it is None, new image will be c... | [
"def",
"_tile_images",
"(",
"imgs",
",",
"tile_shape",
",",
"concatenated_image",
")",
":",
"y_num",
",",
"x_num",
"=",
"tile_shape",
"one_width",
"=",
"imgs",
"[",
"0",
"]",
".",
"shape",
"[",
"1",
"]",
"one_height",
"=",
"imgs",
"[",
"0",
"]",
".",
... | 39.612903 | 14.580645 |
def choices(self, cl):
"""
Take choices from field's 'choices' attribute for 'ChoicesField' and
use 'flatchoices' as usual for other fields.
"""
#: Just tidy up standard implementation for the sake of DRY principle.
def _choice_item(is_selected, query_string, title):
... | [
"def",
"choices",
"(",
"self",
",",
"cl",
")",
":",
"#: Just tidy up standard implementation for the sake of DRY principle.",
"def",
"_choice_item",
"(",
"is_selected",
",",
"query_string",
",",
"title",
")",
":",
"return",
"{",
"'selected'",
":",
"is_selected",
",",
... | 36 | 16.666667 |
def conf_matrix(p,labels,names=['1','0'],threshold=.5,show=True):
"""
Returns error rate and true/false positives in a binary classification problem
- Actual classes are displayed by column.
- Predicted classes are displayed by row.
:param p: array of class '1' probabilities.
:param labels: arr... | [
"def",
"conf_matrix",
"(",
"p",
",",
"labels",
",",
"names",
"=",
"[",
"'1'",
",",
"'0'",
"]",
",",
"threshold",
"=",
".5",
",",
"show",
"=",
"True",
")",
":",
"assert",
"p",
".",
"size",
"==",
"labels",
".",
"size",
",",
"\"Arrays p and labels have ... | 45.758621 | 16.172414 |
def _execute_query(
self,
sqlQuery):
"""* execute query and trim results*
**Key Arguments:**
- ``sqlQuery`` -- the sql database query to grab low-resolution results.
**Return:**
- ``databaseRows`` -- the database rows found on HTM trixles with re... | [
"def",
"_execute_query",
"(",
"self",
",",
"sqlQuery",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'completed the ````_execute_query`` method'",
")",
"try",
":",
"databaseRows",
"=",
"readquery",
"(",
"log",
"=",
"self",
".",
"log",
",",
"sqlQuery",
"=... | 41.053571 | 21.821429 |
def pathFromHere_explore(self, astr_startPath = '/'):
"""
Return a list of paths from "here" in the stree, using the
child explore access.
:param astr_startPath: path from which to start
:return: a list of paths from "here"
"""
self.l... | [
"def",
"pathFromHere_explore",
"(",
"self",
",",
"astr_startPath",
"=",
"'/'",
")",
":",
"self",
".",
"l_lwd",
"=",
"[",
"]",
"self",
".",
"treeExplore",
"(",
"startPath",
"=",
"astr_startPath",
",",
"f",
"=",
"self",
".",
"lwd",
")",
"return",
"self",
... | 34.833333 | 17.333333 |
def graph_nodes_from_branch(self, branch):
""" Returns nodes that are connected by `branch`
Args
----
branch: BranchDing0
Description #TODO
Returns
-------
(:obj:`GridDing0`, :obj:`GridDing0`)
2-tuple of nodes (Ding0 objec... | [
"def",
"graph_nodes_from_branch",
"(",
"self",
",",
"branch",
")",
":",
"edges",
"=",
"nx",
".",
"get_edge_attributes",
"(",
"self",
".",
"_graph",
",",
"'branch'",
")",
"nodes",
"=",
"list",
"(",
"edges",
".",
"keys",
"(",
")",
")",
"[",
"list",
"(",
... | 30.375 | 17.9375 |
def get_connection(self, is_read_only=False) -> redis.StrictRedis:
"""
Gets a StrictRedis connection for normal redis or for redis sentinel based upon redis mode in configuration.
:type is_read_only: bool
:param is_read_only: In case of redis sentinel, it returns connection to slave
... | [
"def",
"get_connection",
"(",
"self",
",",
"is_read_only",
"=",
"False",
")",
"->",
"redis",
".",
"StrictRedis",
":",
"if",
"self",
".",
"connection",
"is",
"not",
"None",
":",
"return",
"self",
".",
"connection",
"if",
"self",
".",
"is_sentinel",
":",
"... | 42.846154 | 24.461538 |
def save_migration(connection, basename):
""" Save a migration in `migrations_applied` table """
# Prepare query
sql = "INSERT INTO migrations_applied (name, date) VALUES (%s, NOW())"
# Run
with connection.cursor() as cursor:
cursor.execute(sql, (basename,))
connection.commit()
... | [
"def",
"save_migration",
"(",
"connection",
",",
"basename",
")",
":",
"# Prepare query",
"sql",
"=",
"\"INSERT INTO migrations_applied (name, date) VALUES (%s, NOW())\"",
"# Run",
"with",
"connection",
".",
"cursor",
"(",
")",
"as",
"cursor",
":",
"cursor",
".",
"exe... | 26.833333 | 20.5 |
def user_delete(auth=None, **kwargs):
'''
Delete a user
CLI Example:
.. code-block:: bash
salt '*' keystoneng.user_delete name=user1
salt '*' keystoneng.user_delete name=user2 domain_id=b62e76fbeeff4e8fb77073f591cf211e
salt '*' keystoneng.user_delete name=a42cbbfa1e894e839fd0f... | [
"def",
"user_delete",
"(",
"auth",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cloud",
"=",
"get_openstack_cloud",
"(",
"auth",
")",
"kwargs",
"=",
"_clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"return",
"cloud",
".",
"delete_user",
"(",
"*",
"*"... | 29.266667 | 24.066667 |
def change_owner(ctx, owner, uuid):
"""Changes the ownership of objects"""
objects = ctx.obj['objects']
database = ctx.obj['db']
if uuid is True:
owner_filter = {'uuid': owner}
else:
owner_filter = {'name': owner}
owner = database.objectmodels['user'].find_one(owner_filter)
... | [
"def",
"change_owner",
"(",
"ctx",
",",
"owner",
",",
"uuid",
")",
":",
"objects",
"=",
"ctx",
".",
"obj",
"[",
"'objects'",
"]",
"database",
"=",
"ctx",
".",
"obj",
"[",
"'db'",
"]",
"if",
"uuid",
"is",
"True",
":",
"owner_filter",
"=",
"{",
"'uui... | 22.333333 | 20.047619 |
def _inherit_context(self, node):
'''_inherit_context(self, node) -> list
Scan ancestors of attribute and namespace context. Used only
for single element node canonicalization, not for subset
canonicalization.'''
# Collect the initial list of xml:foo attributes.
xmlattr... | [
"def",
"_inherit_context",
"(",
"self",
",",
"node",
")",
":",
"# Collect the initial list of xml:foo attributes.",
"xmlattrs",
"=",
"filter",
"(",
"_IN_XML_NS",
",",
"_attrs",
"(",
"node",
")",
")",
"# Walk up and get all xml:XXX attributes we inherit.",
"inherited",
","... | 41.105263 | 15 |
def dir_between_pts(a=(0.0, 0.0), b=(0.0, 0.0)):
'''Return direction between two points on N dimensions.
List of vectors per pair of dimensions are returned in radians.
E.g. Where X is "right", Y is "up", Z is "in" on a computer screen, and
returned value is [pi/4, -pi/4], then the vector will be coming out the
... | [
"def",
"dir_between_pts",
"(",
"a",
"=",
"(",
"0.0",
",",
"0.0",
")",
",",
"b",
"=",
"(",
"0.0",
",",
"0.0",
")",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"tuple",
")",
"assert",
"isinstance",
"(",
"b",
",",
"tuple",
")",
"l_pt",
"=",
"... | 37.56 | 22.44 |
def get(self, bounce_type=None, inactive=None, email_filter=None,
message_id=None, count=None, offset=None, api_key=None,
secure=None, test=None, **request_args):
'''Builds query string params from inputs. It handles offset and
count defaults and validation.
:param bounc... | [
"def",
"get",
"(",
"self",
",",
"bounce_type",
"=",
"None",
",",
"inactive",
"=",
"None",
",",
"email_filter",
"=",
"None",
",",
"message_id",
"=",
"None",
",",
"count",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"secu... | 53.243243 | 20.702703 |
def write_to_buffer(self, buf):
"""Save the context to a buffer."""
doc = self.to_dict()
if config.rxt_as_yaml:
content = dump_yaml(doc)
else:
content = json.dumps(doc, indent=4, separators=(",", ": "))
buf.write(content) | [
"def",
"write_to_buffer",
"(",
"self",
",",
"buf",
")",
":",
"doc",
"=",
"self",
".",
"to_dict",
"(",
")",
"if",
"config",
".",
"rxt_as_yaml",
":",
"content",
"=",
"dump_yaml",
"(",
"doc",
")",
"else",
":",
"content",
"=",
"json",
".",
"dumps",
"(",
... | 27.8 | 18.7 |
def detach_network_interface(self, network_interface_id, force=False):
"""
Detaches a network interface from an instance.
:type network_interface_id: str
:param network_interface_id: The ID of the network interface to detach.
:type force: bool
:param force: Set to true ... | [
"def",
"detach_network_interface",
"(",
"self",
",",
"network_interface_id",
",",
"force",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'NetworkInterfaceId'",
":",
"network_interface_id",
"}",
"if",
"force",
":",
"params",
"[",
"'Force'",
"]",
"=",
"'true'",
"... | 35.8 | 21.4 |
def publish(self, source, data, metadata=None):
"""Publish data and metadata to all frontends.
See the ``display_data`` message in the messaging documentation for
more details about this message type.
The following MIME types are currently implemented:
* text/plain
* t... | [
"def",
"publish",
"(",
"self",
",",
"source",
",",
"data",
",",
"metadata",
"=",
"None",
")",
":",
"# The default is to simply write the plain text data using io.stdout.",
"if",
"data",
".",
"has_key",
"(",
"'text/plain'",
")",
":",
"print",
"(",
"data",
"[",
"'... | 38.128205 | 22.615385 |
def neg(self, value, name=''):
"""
Integer negative:
name = -value
"""
return self.sub(values.Constant(value.type, 0), value, name=name) | [
"def",
"neg",
"(",
"self",
",",
"value",
",",
"name",
"=",
"''",
")",
":",
"return",
"self",
".",
"sub",
"(",
"values",
".",
"Constant",
"(",
"value",
".",
"type",
",",
"0",
")",
",",
"value",
",",
"name",
"=",
"name",
")"
] | 29.166667 | 12.166667 |
def getOid(self):
"""Returns OID identifying MIB variable.
Returns
-------
: :py:class:`~pysnmp.proto.rfc1902.ObjectName`
full OID identifying MIB variable including possible index part.
Raises
------
SmiError
If MIB variable conversion ha... | [
"def",
"getOid",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"&",
"self",
".",
"ST_CLEAN",
":",
"return",
"self",
".",
"_oid",
"else",
":",
"raise",
"SmiError",
"(",
"'%s object not fully initialized'",
"%",
"self",
".",
"__class__",
".",
"__name__... | 28.62963 | 22.37037 |
def hr_dp004(self, value=None):
""" Corresponds to IDD Field `hr_dp004`
humidity ratio corresponding to
Dew-point temperature corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `hr_dp004`
if `value` is No... | [
"def",
"hr_dp004",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type float... | 37 | 20.952381 |
def _get_single_set(self, num_objects, num_features):
"""Generate one input sequence and output label.
Each sequences of objects has a feature that consists of the feature vector
for that object plus the encoding for its ID, the reference vector ID and
the n-th value relative ID for a total feature siz... | [
"def",
"_get_single_set",
"(",
"self",
",",
"num_objects",
",",
"num_features",
")",
":",
"# Generate random binary vectors",
"data",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"-",
"1",
",",
"1",
",",
"size",
"=",
"(",
"num_objects",
",",
"num_features"... | 35.851064 | 20.382979 |
def _add_access_token_to_response(self, response, access_token):
# type: (oic.message.AccessTokenResponse, se_leg_op.access_token.AccessToken) -> None
"""
Adds the Access Token and the associated parameters to the Token Response.
"""
response['access_token'] = access_token.value
... | [
"def",
"_add_access_token_to_response",
"(",
"self",
",",
"response",
",",
"access_token",
")",
":",
"# type: (oic.message.AccessTokenResponse, se_leg_op.access_token.AccessToken) -> None",
"response",
"[",
"'access_token'",
"]",
"=",
"access_token",
".",
"value",
"response",
... | 52.5 | 19.75 |
def user_verify_password(user_id=None, name=None, password=None,
profile=None, **connection_args):
'''
Verify a user's password
CLI Examples:
.. code-block:: bash
salt '*' keystone.user_verify_password name=test password=foobar
salt '*' keystone.user_verify_pa... | [
"def",
"user_verify_password",
"(",
"user_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"password",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"kstone",
"=",
"auth",
"(",
"profile",
",",
"*",
"*",
"connecti... | 35.021739 | 20.630435 |
def upload_files(selected_file, selected_host, only_link, file_name):
"""
Uploads selected file to the host, thanks to the fact that
every pomf.se based site has pretty much the same architecture.
"""
try:
answer = requests.post(
url=selected_host[0]+"upload.php",
fil... | [
"def",
"upload_files",
"(",
"selected_file",
",",
"selected_host",
",",
"only_link",
",",
"file_name",
")",
":",
"try",
":",
"answer",
"=",
"requests",
".",
"post",
"(",
"url",
"=",
"selected_host",
"[",
"0",
"]",
"+",
"\"upload.php\"",
",",
"files",
"=",
... | 47.352941 | 21.470588 |
def total_count(self, total_count):
"""
Sets the total_count of this ServicePackageQuotaHistoryResponse.
Sum of all quota history entries that should be returned
:param total_count: The total_count of this ServicePackageQuotaHistoryResponse.
:type: int
"""
if tot... | [
"def",
"total_count",
"(",
"self",
",",
"total_count",
")",
":",
"if",
"total_count",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `total_count`, must not be `None`\"",
")",
"if",
"total_count",
"is",
"not",
"None",
"and",
"total_count",
"<",
... | 43.928571 | 24.785714 |
def get_frequent_n_grams(self, input_reader, n, min_frequency, min_pmi, filters):
"""
Finds all frequent (and meaningful) n-grams in a file, treating each new line as a new document.
:param input_reader: LineReader initialized on file with documents to generate n-grams for
:p... | [
"def",
"get_frequent_n_grams",
"(",
"self",
",",
"input_reader",
",",
"n",
",",
"min_frequency",
",",
"min_pmi",
",",
"filters",
")",
":",
"line_counter",
"=",
"0",
"TweetNGramsPMI",
".",
"tweet_reader",
"=",
"input_reader",
"TweetNGramsPMI",
".",
"n_gram_tree",
... | 49.870968 | 27.806452 |
def initialize( # type: ignore
self,
max_clients: int = 10,
hostname_mapping: Dict[str, str] = None,
max_buffer_size: int = 104857600,
resolver: Resolver = None,
defaults: Dict[str, Any] = None,
max_header_size: int = None,
max_body_size: int = None,
... | [
"def",
"initialize",
"(",
"# type: ignore",
"self",
",",
"max_clients",
":",
"int",
"=",
"10",
",",
"hostname_mapping",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
"max_buffer_size",
":",
"int",
"=",
"104857600",
",",
"resolver",
":",
"Re... | 43.391304 | 20.84058 |
def browser(request, path='', template="cloud_browser/browser.html"):
"""View files in a file path.
:param request: The request.
:param path: Path to resource, including container as first part of path.
:param template: Template to render.
"""
from itertools import islice
try:
# p... | [
"def",
"browser",
"(",
"request",
",",
"path",
"=",
"''",
",",
"template",
"=",
"\"cloud_browser/browser.html\"",
")",
":",
"from",
"itertools",
"import",
"islice",
"try",
":",
"# pylint: disable=redefined-builtin",
"from",
"future_builtins",
"import",
"filter",
"ex... | 34.272727 | 17.051948 |
def system(cmd, data=None):
'''
pipes the output of a program
'''
import subprocess
s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
out, err = s.communicate(data)
return out.decode('utf8') | [
"def",
"system",
"(",
"cmd",
",",
"data",
"=",
"None",
")",
":",
"import",
"subprocess",
"s",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"shell",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",... | 29 | 22.5 |
def network_list(provider):
'''
List private networks
CLI Example:
.. code-block:: bash
salt minionname cloud.network_list my-nova
'''
client = _get_client()
return client.extra_action(action='network_list', provider=provider, names='names') | [
"def",
"network_list",
"(",
"provider",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"return",
"client",
".",
"extra_action",
"(",
"action",
"=",
"'network_list'",
",",
"provider",
"=",
"provider",
",",
"names",
"=",
"'names'",
")"
] | 20.692308 | 28.076923 |
def slc_erase(self, address, BE_ID=0x1, PMODE=0x0100):
"""slc erase"""
cmd = ["NVM_CLI_BE_ID=0x%x" % BE_ID, "NVM_CLI_PMODE=0x%x" % PMODE, "nvm_cmd erase", self.envs, "0x%x" % address]
status, _, _ = cij.ssh.command(cmd, shell=True)
return status | [
"def",
"slc_erase",
"(",
"self",
",",
"address",
",",
"BE_ID",
"=",
"0x1",
",",
"PMODE",
"=",
"0x0100",
")",
":",
"cmd",
"=",
"[",
"\"NVM_CLI_BE_ID=0x%x\"",
"%",
"BE_ID",
",",
"\"NVM_CLI_PMODE=0x%x\"",
"%",
"PMODE",
",",
"\"nvm_cmd erase\"",
",",
"self",
"... | 55.4 | 26.2 |
def get_worksheets_section(self):
""" Returns the section dictionary related with Worksheets,
that contains some informative panels (like
WS to be verified, WS with results pending, etc.)
"""
out = []
bc = getToolByName(self.context, CATALOG_WORKSHEET_LISTING)
... | [
"def",
"get_worksheets_section",
"(",
"self",
")",
":",
"out",
"=",
"[",
"]",
"bc",
"=",
"getToolByName",
"(",
"self",
".",
"context",
",",
"CATALOG_WORKSHEET_LISTING",
")",
"query",
"=",
"{",
"'portal_type'",
":",
"\"Worksheet\"",
",",
"}",
"# Check if dashbo... | 40.5 | 18.46 |
def parse(readDataInstance):
"""
Returns a new L{NetMetaDataHeader} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with data to be parsed as a L{NetMetaDataHeader} object.
@rtype: L{NetMetaDataHeader}
@return: A... | [
"def",
"parse",
"(",
"readDataInstance",
")",
":",
"nmh",
"=",
"NetMetaDataHeader",
"(",
")",
"nmh",
".",
"signature",
".",
"value",
"=",
"readDataInstance",
".",
"readDword",
"(",
")",
"nmh",
".",
"majorVersion",
".",
"value",
"=",
"readDataInstance",
".",
... | 42.761905 | 18.952381 |
def load_ipython_extension(shell):
"""
Called when the extension is loaded.
Args:
shell - (NotebookWebApplication): handle to the Notebook interactive shell instance.
"""
# Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request.
def _request(self, uri, metho... | [
"def",
"load_ipython_extension",
"(",
"shell",
")",
":",
"# Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request.",
"def",
"_request",
"(",
"self",
",",
"uri",
",",
"method",
"=",
"\"GET\"",
",",
"body",
"=",
"None",
",",
"header... | 37.367089 | 25.797468 |
def make_coursera_absolute_url(url):
"""
If given url is relative adds coursera netloc,
otherwise returns it without any changes.
"""
if not bool(urlparse(url).netloc):
return urljoin(COURSERA_URL, url)
return url | [
"def",
"make_coursera_absolute_url",
"(",
"url",
")",
":",
"if",
"not",
"bool",
"(",
"urlparse",
"(",
"url",
")",
".",
"netloc",
")",
":",
"return",
"urljoin",
"(",
"COURSERA_URL",
",",
"url",
")",
"return",
"url"
] | 23.8 | 12.8 |
def BinaryRoche (r, D, q, F, Omega=0.0):
r"""
Computes a value of the asynchronous, eccentric Roche potential.
If :envvar:`Omega` is passed, it computes the difference.
The asynchronous, eccentric Roche potential is given by [Wilson1979]_
.. math::
\Omega = \frac{1}{\sqrt{x^2 + y^2 + z^2... | [
"def",
"BinaryRoche",
"(",
"r",
",",
"D",
",",
"q",
",",
"F",
",",
"Omega",
"=",
"0.0",
")",
":",
"return",
"1.0",
"/",
"sqrt",
"(",
"r",
"[",
"0",
"]",
"*",
"r",
"[",
"0",
"]",
"+",
"r",
"[",
"1",
"]",
"*",
"r",
"[",
"1",
"]",
"+",
"... | 36.708333 | 27.916667 |
def hops(node1, node2):
"""returns # of hops it takes to get from node1 to node2, 1 means they're on the same link"""
if node1 == node2:
return 0
elif set(node1.interfaces) & set(node2.interfaces):
# they share a common interface
return 1
else:
# Not implemented yet, grap... | [
"def",
"hops",
"(",
"node1",
",",
"node2",
")",
":",
"if",
"node1",
"==",
"node2",
":",
"return",
"0",
"elif",
"set",
"(",
"node1",
".",
"interfaces",
")",
"&",
"set",
"(",
"node2",
".",
"interfaces",
")",
":",
"# they share a common interface",
"return"... | 37 | 19.1 |
async def send_invoice(self, chat_id: base.Integer, title: base.String,
description: base.String, payload: base.String,
provider_token: base.String, start_parameter: base.String,
currency: base.String, prices: typing.List[types.LabeledPric... | [
"async",
"def",
"send_invoice",
"(",
"self",
",",
"chat_id",
":",
"base",
".",
"Integer",
",",
"title",
":",
"base",
".",
"String",
",",
"description",
":",
"base",
".",
"String",
",",
"payload",
":",
"base",
".",
"String",
",",
"provider_token",
":",
... | 67.428571 | 31.584416 |
def stop(self):
"""Cleanly shutdown the connection to RabbitMQ by stopping the
consumer with RabbitMQ.
When RabbitMQ confirms the cancellation, on_cancelok will be invoked
by pika, which will then closing the channel and connection.
The IOLoop is started again, becuase this met... | [
"def",
"stop",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Stopping'",
")",
"self",
".",
"_closing",
"=",
"True",
"self",
".",
"stop_consuming",
"(",
")",
"self",
".",
"_connection",
".",
"ioloop",
".",
"start",
"(",
")",
"logger",
".",
"de... | 41.277778 | 20.444444 |
def trigger_streamer(self, index):
"""Pass a streamer to the stream manager if it has data."""
self._logger.debug("trigger_streamer RPC called on streamer %d", index)
if index >= len(self.graph.streamers):
return _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED)
if in... | [
"def",
"trigger_streamer",
"(",
"self",
",",
"index",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"\"trigger_streamer RPC called on streamer %d\"",
",",
"index",
")",
"if",
"index",
">=",
"len",
"(",
"self",
".",
"graph",
".",
"streamers",
")",
":",... | 38 | 25.857143 |
def new_worker_redirected_log_file(self, worker_id):
"""Create new logging files for workers to redirect its output."""
worker_stdout_file, worker_stderr_file = (self.new_log_files(
"worker-" + ray.utils.binary_to_hex(worker_id), True))
return worker_stdout_file, worker_stderr_file | [
"def",
"new_worker_redirected_log_file",
"(",
"self",
",",
"worker_id",
")",
":",
"worker_stdout_file",
",",
"worker_stderr_file",
"=",
"(",
"self",
".",
"new_log_files",
"(",
"\"worker-\"",
"+",
"ray",
".",
"utils",
".",
"binary_to_hex",
"(",
"worker_id",
")",
... | 62.8 | 16 |
def _checkpoint_trial_if_needed(self, trial):
"""Checkpoints trial based off trial.last_result."""
if trial.should_checkpoint():
# Save trial runtime if possible
if hasattr(trial, "runner") and trial.runner:
self.trial_executor.save(trial, storage=Checkpoint.DISK)... | [
"def",
"_checkpoint_trial_if_needed",
"(",
"self",
",",
"trial",
")",
":",
"if",
"trial",
".",
"should_checkpoint",
"(",
")",
":",
"# Save trial runtime if possible",
"if",
"hasattr",
"(",
"trial",
",",
"\"runner\"",
")",
"and",
"trial",
".",
"runner",
":",
"s... | 53.857143 | 11.857143 |
def model_to_list(model_class, filter_dict=None, order_by_list=None,
select_related_fields=None, q_filter=None,
values=None,
to_json_method='to_json'):
"""
不分页
:param values:
:param to_json_method:
:param model_class:
:param filter_dict:
... | [
"def",
"model_to_list",
"(",
"model_class",
",",
"filter_dict",
"=",
"None",
",",
"order_by_list",
"=",
"None",
",",
"select_related_fields",
"=",
"None",
",",
"q_filter",
"=",
"None",
",",
"values",
"=",
"None",
",",
"to_json_method",
"=",
"'to_json'",
")",
... | 37 | 18.6 |
def enrollments(db, uuid=None, organization=None, from_date=None, to_date=None):
"""List the enrollment information available in the registry.
This function will return a list of enrollments. If 'uuid'
parameter is set, it will return the enrollments related to that
unique identity; if 'organization' p... | [
"def",
"enrollments",
"(",
"db",
",",
"uuid",
"=",
"None",
",",
"organization",
"=",
"None",
",",
"from_date",
"=",
"None",
",",
"to_date",
"=",
"None",
")",
":",
"if",
"not",
"from_date",
":",
"from_date",
"=",
"MIN_PERIOD_DATE",
"if",
"not",
"to_date",... | 38.158537 | 22.987805 |
def process_exception_message(exception):
"""
Process an exception message.
Args:
exception: The exception to process.
Returns:
A filtered string summarizing the exception.
"""
exception_message = str(exception)
for replace_char in ['\t',... | [
"def",
"process_exception_message",
"(",
"exception",
")",
":",
"exception_message",
"=",
"str",
"(",
"exception",
")",
"for",
"replace_char",
"in",
"[",
"'\\t'",
",",
"'\\n'",
",",
"'\\\\n'",
"]",
":",
"exception_message",
"=",
"exception_message",
".",
"replac... | 35.071429 | 18.357143 |
def saffron(X, q=32, k=4, tangent_dim=1, curv_thresh=0.95, decay_rate=0.9,
max_iter=15, verbose=False):
'''
SAFFRON graph construction method.
X : (n,d)-array of coordinates
q : int, median number of candidate friends per vertex
k : int, number of friends to select per vertex, k < q
tan... | [
"def",
"saffron",
"(",
"X",
",",
"q",
"=",
"32",
",",
"k",
"=",
"4",
",",
"tangent_dim",
"=",
"1",
",",
"curv_thresh",
"=",
"0.95",
",",
"decay_rate",
"=",
"0.9",
",",
"max_iter",
"=",
"15",
",",
"verbose",
"=",
"False",
")",
":",
"n",
"=",
"le... | 35.176471 | 17.835294 |
def get_json(self, link):
"""
Returns specified link instance as JSON.
:param link: the link instance.
:rtype: JSON.
"""
return json.dumps({
'id': link.id,
'title': link.title,
'url': link.get_absolute_url(),
... | [
"def",
"get_json",
"(",
"self",
",",
"link",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'id'",
":",
"link",
".",
"id",
",",
"'title'",
":",
"link",
".",
"title",
",",
"'url'",
":",
"link",
".",
"get_absolute_url",
"(",
")",
",",
"'edit_li... | 28.9375 | 11.6875 |
def get_vnetwork_vswitches_output_vnetwork_vswitches_pnic(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
config = get_vnetwork_vswitches
output = ET.SubElement(get_vnetwork_vswitches,... | [
"def",
"get_vnetwork_vswitches_output_vnetwork_vswitches_pnic",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_vswitches",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_vswitches\"",
")",
... | 44.461538 | 15.923077 |
def _pcdata_nodes(pcdata):
"""Return a list of minidom nodes with the properly escaped ``pcdata``
inside.
The following special XML characters are escaped:
* left angle bracket (<)
* Right angle bracket (>)
* Ampersand (&)
By default, XML-based escaping is used for these characters. ... | [
"def",
"_pcdata_nodes",
"(",
"pcdata",
")",
":",
"nodelist",
"=",
"[",
"]",
"if",
"_CDATA_ESCAPING",
"and",
"isinstance",
"(",
"pcdata",
",",
"six",
".",
"string_types",
")",
"and",
"(",
"pcdata",
".",
"find",
"(",
"\"<\"",
")",
">=",
"0",
"or",
"pcdat... | 38.063291 | 26.405063 |
def dissimilarities(feature_names, fcs):
'''Computes the pairwise dissimilarity matrices.
This returns a dictionary mapping each name in ``feature_names``
to a pairwise dissimilarities matrix. The dissimilaritiy scores
correspond to ``1 - kernel`` between each feature of each
pair of feature collec... | [
"def",
"dissimilarities",
"(",
"feature_names",
",",
"fcs",
")",
":",
"dis",
"=",
"{",
"}",
"for",
"count",
",",
"name",
"in",
"enumerate",
"(",
"feature_names",
",",
"1",
")",
":",
"logger",
".",
"info",
"(",
"'computing pairwise dissimilarity matrix '",
"'... | 46.625 | 21.458333 |
def koji_login(session,
proxyuser=None,
ssl_certs_dir=None,
krb_principal=None,
krb_keytab=None):
"""
Choose the correct login method based on the available credentials,
and call that method on the provided session object.
:param session: koji... | [
"def",
"koji_login",
"(",
"session",
",",
"proxyuser",
"=",
"None",
",",
"ssl_certs_dir",
"=",
"None",
",",
"krb_principal",
"=",
"None",
",",
"krb_keytab",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"if",
"proxyuser",
":",
"kwargs",
"[",
"'proxyuse... | 33.865385 | 19.288462 |
def separation(X,y,samples=False):
""" return the sum of the between-class squared distance"""
# pdb.set_trace()
num_classes = len(np.unique(y))
total_dist = (X.max()-X.min())**2
if samples:
# return intra-class distance for each sample
separation = np.zeros(y.shape)
for labe... | [
"def",
"separation",
"(",
"X",
",",
"y",
",",
"samples",
"=",
"False",
")",
":",
"# pdb.set_trace()",
"num_classes",
"=",
"len",
"(",
"np",
".",
"unique",
"(",
"y",
")",
")",
"total_dist",
"=",
"(",
"X",
".",
"max",
"(",
")",
"-",
"X",
".",
"min"... | 36.413793 | 17 |
def _merge_summary(in_files, out_file, data):
"""Create one big summary file for disambiguation from multiple splits.
"""
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for i, in_file in... | [
"def",
"_merge_summary",
"(",
"in_files",
",",
"out_file",
",",
"data",
")",
":",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"with",
"open",
... | 46.066667 | 10.066667 |
def init_static_field(state, field_class_name, field_name, field_type):
"""
Initialize the static field with an allocated, but not initialized,
object of the given type.
:param state: State associated to the field.
:param field_class_name: Class containing the field.
:pa... | [
"def",
"init_static_field",
"(",
"state",
",",
"field_class_name",
",",
"field_name",
",",
"field_type",
")",
":",
"field_ref",
"=",
"SimSootValue_StaticFieldRef",
".",
"get_ref",
"(",
"state",
",",
"field_class_name",
",",
"field_name",
",",
"field_type",
")",
"f... | 49.928571 | 20.785714 |
def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer):
"""
Split actions into chunks by number or size, serialize them into strings in
the process.
"""
bulk_actions, bulk_data = [], []
size, action_count = 0, 0
for action, data in actions:
raw_data, raw_action = data, ... | [
"def",
"_chunk_actions",
"(",
"actions",
",",
"chunk_size",
",",
"max_chunk_bytes",
",",
"serializer",
")",
":",
"bulk_actions",
",",
"bulk_data",
"=",
"[",
"]",
",",
"[",
"]",
"size",
",",
"action_count",
"=",
"0",
",",
"0",
"for",
"action",
",",
"data"... | 32.135135 | 15.756757 |
def MakeTransaction(self,
tx,
change_address=None,
fee=Fixed8(0),
from_addr=None,
use_standard=False,
watch_only_val=0,
exclude_vin=None,
... | [
"def",
"MakeTransaction",
"(",
"self",
",",
"tx",
",",
"change_address",
"=",
"None",
",",
"fee",
"=",
"Fixed8",
"(",
"0",
")",
",",
"from_addr",
"=",
"None",
",",
"use_standard",
"=",
"False",
",",
"watch_only_val",
"=",
"0",
",",
"exclude_vin",
"=",
... | 42.16129 | 28.532258 |
def htmlNewDoc(URI, ExternalID):
"""Creates a new HTML document """
ret = libxml2mod.htmlNewDoc(URI, ExternalID)
if ret is None:raise treeError('htmlNewDoc() failed')
return xmlDoc(_obj=ret) | [
"def",
"htmlNewDoc",
"(",
"URI",
",",
"ExternalID",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlNewDoc",
"(",
"URI",
",",
"ExternalID",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'htmlNewDoc() failed'",
")",
"return",
"xmlDoc",
"(",... | 40.4 | 9.2 |
def get_unspents(self):
"""Fetches all available unspent transaction outputs.
:rtype: ``list`` of :class:`~bit.network.meta.Unspent`
"""
self.unspents[:] = list(map(
lambda u: u.set_type('p2pkh' if self.is_compressed() else
'p2pkh-uncompresse... | [
"def",
"get_unspents",
"(",
"self",
")",
":",
"self",
".",
"unspents",
"[",
":",
"]",
"=",
"list",
"(",
"map",
"(",
"lambda",
"u",
":",
"u",
".",
"set_type",
"(",
"'p2pkh'",
"if",
"self",
".",
"is_compressed",
"(",
")",
"else",
"'p2pkh-uncompressed'",
... | 39 | 15.941176 |
def complete(self, flag_message="Complete", padding=None, force=False):
""" Log Level: :attr:COMPLETE
@flag_message: #str flags the message with the given text
using :func:flag
@padding: #str 'top', 'bottom' or 'all', adds a new line to the
specified area... | [
"def",
"complete",
"(",
"self",
",",
"flag_message",
"=",
"\"Complete\"",
",",
"padding",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"should_log",
"(",
"self",
".",
"COMPLETE",
")",
"or",
"force",
":",
"self",
".",
"_print_me... | 38.115385 | 18.192308 |
def authenticate(self, username=None, password=None, api_key=None,
tenant_id=None, connect=False):
"""
Using the supplied credentials, connects to the specified
authentication endpoint and attempts to log in.
Credentials can either be passed directly to this method, or
... | [
"def",
"authenticate",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"tenant_id",
"=",
"None",
",",
"connect",
"=",
"False",
")",
":",
"self",
".",
"username",
"=",
"username",
"or",
"self",
... | 44.470588 | 17.803922 |
def get_template(filename_or_string, is_string=False):
'''
Gets a jinja2 ``Template`` object for the input filename or string, with caching
based on the filename of the template, or the SHA1 of the input string.
'''
# Cache against string sha or just the filename
cache_key = sha1_hash(filename_... | [
"def",
"get_template",
"(",
"filename_or_string",
",",
"is_string",
"=",
"False",
")",
":",
"# Cache against string sha or just the filename",
"cache_key",
"=",
"sha1_hash",
"(",
"filename_or_string",
")",
"if",
"is_string",
"else",
"filename_or_string",
"if",
"cache_key"... | 34.347826 | 24.26087 |
def comprehension_walk_newer(self, node, iter_index, code_index=-5):
"""Non-closure-based comprehensions the way they are done in Python3
and some Python 2.7. Note: there are also other set comprehensions.
"""
p = self.prec
self.prec = 27
code = node[code_index].attr
... | [
"def",
"comprehension_walk_newer",
"(",
"self",
",",
"node",
",",
"iter_index",
",",
"code_index",
"=",
"-",
"5",
")",
":",
"p",
"=",
"self",
".",
"prec",
"self",
".",
"prec",
"=",
"27",
"code",
"=",
"node",
"[",
"code_index",
"]",
".",
"attr",
"asse... | 33.535714 | 16.8 |
def copy_database(self, source, destination):
"""
Copy a database's content and structure.
SMALL Database speed improvements (DB size < 5mb)
Using optimized is about 178% faster
Using one_query is about 200% faster
LARGE Database speed improvements (DB size > 5mb)
... | [
"def",
"copy_database",
"(",
"self",
",",
"source",
",",
"destination",
")",
":",
"print",
"(",
"'\\tCopying database {0} structure and data to database {1}'",
".",
"format",
"(",
"source",
",",
"destination",
")",
")",
"with",
"Timer",
"(",
"'\\nSuccess! Copied datab... | 43.214286 | 21.357143 |
def get_dataset_meta(label):
"""Gives you metadata for dataset chosen via 'label' param
:param label: label = key in data_url dict (that big dict containing all possible datasets)
:return: tuple (data_url, url, expected_hash, hash_path, relative_download_dir)
relative_download_dir says where will be do... | [
"def",
"get_dataset_meta",
"(",
"label",
")",
":",
"data_url",
"=",
"data_urls",
"[",
"label",
"]",
"if",
"type",
"(",
"data_url",
")",
"==",
"str",
":",
"# back compatibility",
"data_url",
"=",
"[",
"data_url",
"]",
"if",
"type",
"(",
"data_url",
")",
"... | 41.75 | 20.5 |
def __postCallAction_hwbp(self, event):
"""
Handles hardware breakpoint events on return from the function.
@type event: L{ExceptionEvent}
@param event: Single step event.
"""
# Remove the one shot hardware breakpoint
# at the return address location in the sta... | [
"def",
"__postCallAction_hwbp",
"(",
"self",
",",
"event",
")",
":",
"# Remove the one shot hardware breakpoint",
"# at the return address location in the stack.",
"tid",
"=",
"event",
".",
"get_tid",
"(",
")",
"address",
"=",
"event",
".",
"breakpoint",
".",
"get_addre... | 29.666667 | 15.285714 |
def readline(self, timeout=1): # pylint: disable=unused-argument
"""
Readline implementation.
:param timeout: Timeout, not used
:return: Line read or None
"""
data = None
if self.read_thread:
# Ignore the timeout value, return imediately if no lines ... | [
"def",
"readline",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"# pylint: disable=unused-argument",
"data",
"=",
"None",
"if",
"self",
".",
"read_thread",
":",
"# Ignore the timeout value, return imediately if no lines in queue",
"data",
"=",
"self",
".",
"read_t... | 34.642857 | 14.214286 |
def _drop_privs(self):
""" Reduces effective privileges for this process to that of the task
owner. The umask and environment variables are also modified to
recreate the environment of the user.
"""
uid = self._task.owner
# get pwd database info for task own... | [
"def",
"_drop_privs",
"(",
"self",
")",
":",
"uid",
"=",
"self",
".",
"_task",
".",
"owner",
"# get pwd database info for task owner",
"try",
":",
"pwd_info",
"=",
"pwd",
".",
"getpwuid",
"(",
"uid",
")",
"except",
"OSError",
":",
"pwd_info",
"=",
"None",
... | 27.897059 | 18.632353 |
def _make_sure_table_exists(self, name_seq):
"""
Makes sure the table with the full name comprising of name_seq exists.
"""
t = self
for key in name_seq[:-1]:
t = t[key]
name = name_seq[-1]
if name not in t:
self.append_elements([element_fa... | [
"def",
"_make_sure_table_exists",
"(",
"self",
",",
"name_seq",
")",
":",
"t",
"=",
"self",
"for",
"key",
"in",
"name_seq",
"[",
":",
"-",
"1",
"]",
":",
"t",
"=",
"t",
"[",
"key",
"]",
"name",
"=",
"name_seq",
"[",
"-",
"1",
"]",
"if",
"name",
... | 38.454545 | 17.727273 |
def replace(self, main_type=None, sub_type=None, params=None):
"""
Return a new MimeType with new values for the specified fields.
:param str main_type: The new main type.
:param str sub_type: The new sub type.
:param dict params: The new parameters.
:return: A new instan... | [
"def",
"replace",
"(",
"self",
",",
"main_type",
"=",
"None",
",",
"sub_type",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"main_type",
"is",
"None",
":",
"main_type",
"=",
"self",
".",
"main_type",
"if",
"sub_type",
"is",
"None",
":",
"... | 32.222222 | 14.444444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.