text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def searchTag(self,HTAG="#python"):
"""Set Twitter search or stream criteria for the selection of tweets"""
self.t = Twython(app_key =self.app_key ,
app_secret =self.app_secret ,
oauth_token =self.oauth_token ... | [
"def",
"searchTag",
"(",
"self",
",",
"HTAG",
"=",
"\"#python\"",
")",
":",
"self",
".",
"t",
"=",
"Twython",
"(",
"app_key",
"=",
"self",
".",
"app_key",
",",
"app_secret",
"=",
"self",
".",
"app_secret",
",",
"oauth_token",
"=",
"self",
".",
"oauth_t... | 54 | 27.666667 |
def eigendecompose(tensor, normalise=False):
'''
Performs and eigendecomposition of the tensor and orders into
descending eigenvalues
'''
if normalise:
tensor, tensor_norm = normalise_tensor(tensor)
else:
tensor_norm = 1.
eigvals, eigvects = np.linalg.eigh(tensor, UPLO='U')
... | [
"def",
"eigendecompose",
"(",
"tensor",
",",
"normalise",
"=",
"False",
")",
":",
"if",
"normalise",
":",
"tensor",
",",
"tensor_norm",
"=",
"normalise_tensor",
"(",
"tensor",
")",
"else",
":",
"tensor_norm",
"=",
"1.",
"eigvals",
",",
"eigvects",
"=",
"np... | 28.5 | 19.5 |
def trim(self):
"""Clear not used counters"""
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key] | [
"def",
"trim",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"iteritems",
"(",
"self",
".",
"counters",
")",
")",
":",
"if",
"value",
".",
"empty",
"(",
")",
":",
"del",
"self",
".",
"counters",
"[",
"key",
"]"
] | 35.2 | 11 |
def parse_list(cls, data):
"""Parse a list of JSON objects into a result set of model instances."""
results = ResultSet()
data = data or []
for obj in data:
if obj:
results.append(cls.parse(obj))
return results | [
"def",
"parse_list",
"(",
"cls",
",",
"data",
")",
":",
"results",
"=",
"ResultSet",
"(",
")",
"data",
"=",
"data",
"or",
"[",
"]",
"for",
"obj",
"in",
"data",
":",
"if",
"obj",
":",
"results",
".",
"append",
"(",
"cls",
".",
"parse",
"(",
"obj",... | 33.875 | 12.625 |
def match_entries(entries, pattern):
"""A drop-in replacement for fnmatch.filter that supports pattern
variants (ie. {foo,bar}baz = foobaz or barbaz)."""
matching = []
for variant in expand_braces(pattern):
matching.extend(fnmatch.filter(entries, variant))
return list(_deduplicate(matching... | [
"def",
"match_entries",
"(",
"entries",
",",
"pattern",
")",
":",
"matching",
"=",
"[",
"]",
"for",
"variant",
"in",
"expand_braces",
"(",
"pattern",
")",
":",
"matching",
".",
"extend",
"(",
"fnmatch",
".",
"filter",
"(",
"entries",
",",
"variant",
")",... | 34.888889 | 14.111111 |
def delete(self, bulk=False):
"""
Delete the object
"""
meta = self._meta
conn = meta['connection']
conn.delete(meta.index, meta.type, meta.id, bulk=bulk) | [
"def",
"delete",
"(",
"self",
",",
"bulk",
"=",
"False",
")",
":",
"meta",
"=",
"self",
".",
"_meta",
"conn",
"=",
"meta",
"[",
"'connection'",
"]",
"conn",
".",
"delete",
"(",
"meta",
".",
"index",
",",
"meta",
".",
"type",
",",
"meta",
".",
"id... | 28 | 10 |
def _update_job(self, target, args, kwargs):
"""Specify the function this async job is to execute when run."""
target_path, options = get_function_path_and_options(target)
assert isinstance(args, (tuple, list)) or args is None
assert isinstance(kwargs, dict) or kwargs is None
i... | [
"def",
"_update_job",
"(",
"self",
",",
"target",
",",
"args",
",",
"kwargs",
")",
":",
"target_path",
",",
"options",
"=",
"get_function_path_and_options",
"(",
"target",
")",
"assert",
"isinstance",
"(",
"args",
",",
"(",
"tuple",
",",
"list",
")",
")",
... | 38.454545 | 21.090909 |
def dec2hms(dec):
"""
ADW: This should really be replaced by astropy
"""
DEGREE = 360.
HOUR = 24.
MINUTE = 60.
SECOND = 3600.
dec = float(dec)
fhour = dec*(HOUR/DEGREE)
hour = int(fhour)
fminute = (fhour - hour)*MINUTE
minute = int(fminute)
second = (fminut... | [
"def",
"dec2hms",
"(",
"dec",
")",
":",
"DEGREE",
"=",
"360.",
"HOUR",
"=",
"24.",
"MINUTE",
"=",
"60.",
"SECOND",
"=",
"3600.",
"dec",
"=",
"float",
"(",
"dec",
")",
"fhour",
"=",
"dec",
"*",
"(",
"HOUR",
"/",
"DEGREE",
")",
"hour",
"=",
"int",
... | 19.722222 | 17.722222 |
def dpod_port_id_port_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
dpod = ET.SubElement(config, "dpod", xmlns="urn:brocade.com:mgmt:brocade-license")
port_id = ET.SubElement(dpod, "port-id")
port_id = ET.SubElement(port_id, "port-id")
... | [
"def",
"dpod_port_id_port_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"dpod",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"dpod\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgmt:bro... | 40 | 13 |
def delete(self, membershipId):
"""Delete a membership, by ID.
Args:
membershipId(basestring): The membership ID.
Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.
"""
check_type(me... | [
"def",
"delete",
"(",
"self",
",",
"membershipId",
")",
":",
"check_type",
"(",
"membershipId",
",",
"basestring",
")",
"# API request",
"self",
".",
"_session",
".",
"delete",
"(",
"API_ENDPOINT",
"+",
"'/'",
"+",
"membershipId",
")"
] | 27.733333 | 21.8 |
def handle_command_line():
"""Display an image for the phrase in sys.argv, if possible"""
phrase = ' '.join(sys.argv[1:]) or 'random'
try:
giphy = get_random_giphy(phrase)
except ValueError:
sys.stderr.write('Unable to find any GIFs for {!r}\n'.format(phrase))
sys.exit(1)
d... | [
"def",
"handle_command_line",
"(",
")",
":",
"phrase",
"=",
"' '",
".",
"join",
"(",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
"or",
"'random'",
"try",
":",
"giphy",
"=",
"get_random_giphy",
"(",
"phrase",
")",
"except",
"ValueError",
":",
"sys",
... | 30.545455 | 19.818182 |
def convolve_comb_lines(lines_wave, lines_flux, sigma,
crpix1, crval1, cdelt1, naxis1):
"""Convolve a set of lines of known wavelengths and flux.
Parameters
----------
lines_wave : array like
Input array with wavelengths
lines_flux : array like
Input array wi... | [
"def",
"convolve_comb_lines",
"(",
"lines_wave",
",",
"lines_flux",
",",
"sigma",
",",
"crpix1",
",",
"crval1",
",",
"cdelt1",
",",
"naxis1",
")",
":",
"# generate wavelengths for output spectrum",
"xwave",
"=",
"crval1",
"+",
"(",
"np",
".",
"arange",
"(",
"n... | 29.255814 | 19.023256 |
def BE8(value, min_value=None, max_value=None, fuzzable=True, name=None, full_range=False):
'''8-bit field, Big endian encoded'''
return UInt8(value, min_value=min_value, max_value=max_value, encoder=ENC_INT_BE, fuzzable=fuzzable, name=name, full_range=full_range) | [
"def",
"BE8",
"(",
"value",
",",
"min_value",
"=",
"None",
",",
"max_value",
"=",
"None",
",",
"fuzzable",
"=",
"True",
",",
"name",
"=",
"None",
",",
"full_range",
"=",
"False",
")",
":",
"return",
"UInt8",
"(",
"value",
",",
"min_value",
"=",
"min_... | 90 | 50 |
def _add_explicit_includes(lines, dependencies=None, extralinks=None):
"""Adds any relevant libraries that need to be explicitly included according
to the fortpy configuration file. Libraries are appended to the specified
collection of lines. Returns true if relevant libraries were added.
"""
from f... | [
"def",
"_add_explicit_includes",
"(",
"lines",
",",
"dependencies",
"=",
"None",
",",
"extralinks",
"=",
"None",
")",
":",
"from",
"fortpy",
"import",
"config",
"import",
"sys",
"from",
"os",
"import",
"path",
"includes",
"=",
"sys",
".",
"modules",
"[",
"... | 39.804878 | 19.146341 |
def scale(self, factor, inplace=True):
""" Multiplies all branch lengths by factor. """
if not inplace:
t = self.copy()
else:
t = self
t._tree.scale_edges(factor)
t._dirty = True
return t | [
"def",
"scale",
"(",
"self",
",",
"factor",
",",
"inplace",
"=",
"True",
")",
":",
"if",
"not",
"inplace",
":",
"t",
"=",
"self",
".",
"copy",
"(",
")",
"else",
":",
"t",
"=",
"self",
"t",
".",
"_tree",
".",
"scale_edges",
"(",
"factor",
")",
"... | 27.888889 | 13.888889 |
def submit(self, command_line, name = None, array = None, dependencies = [], exec_dir = None, log_dir = None, dry_run = False, stop_on_failure = False, **kwargs):
"""Submits a job that will be executed on the local machine during a call to "run".
All kwargs will simply be ignored."""
# remove duplicate depe... | [
"def",
"submit",
"(",
"self",
",",
"command_line",
",",
"name",
"=",
"None",
",",
"array",
"=",
"None",
",",
"dependencies",
"=",
"[",
"]",
",",
"exec_dir",
"=",
"None",
",",
"log_dir",
"=",
"None",
",",
"dry_run",
"=",
"False",
",",
"stop_on_failure",... | 44.318182 | 31.772727 |
def _validate(self, value):
"""
Predicate used to determine if a computed value is valid, True, or
not, False.
"""
if value is None and not self.nullable:
self.ctx.errors.invalid('not nullable')
return False
return True | [
"def",
"_validate",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"and",
"not",
"self",
".",
"nullable",
":",
"self",
".",
"ctx",
".",
"errors",
".",
"invalid",
"(",
"'not nullable'",
")",
"return",
"False",
"return",
"True"
] | 31.444444 | 13.666667 |
def root(x, k, context=None):
"""
Return the kth root of x.
For k odd and x negative (including -Inf), return a negative number.
For k even and x negative (including -Inf), return NaN.
The kth root of -0 is defined to be -0, whatever the parity of k.
This function is only implemented for nonn... | [
"def",
"root",
"(",
"x",
",",
"k",
",",
"context",
"=",
"None",
")",
":",
"if",
"k",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"root function not implemented for negative k\"",
")",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",... | 26.809524 | 23.095238 |
def batch_augment(x, func, device='/CPU:0'):
"""
Apply dataset augmentation to a batch of exmaples.
:param x: Tensor representing a batch of examples.
:param func: Callable implementing dataset augmentation, operating on
a single image.
:param device: String specifying which device to use.
"""
with tf... | [
"def",
"batch_augment",
"(",
"x",
",",
"func",
",",
"device",
"=",
"'/CPU:0'",
")",
":",
"with",
"tf",
".",
"device",
"(",
"device",
")",
":",
"return",
"tf",
".",
"map_fn",
"(",
"func",
",",
"x",
")"
] | 35.7 | 12.1 |
def setup(app):
"""
Setup for Sphinx extension.
:param app: Sphinx application context.
"""
try:
app.info('adding bolditalic role...', nonl=True)
app.add_role('bolditalic', bolditalic)
app.connect('env-updated', css)
app.info(' done')
except Exception:
ap... | [
"def",
"setup",
"(",
"app",
")",
":",
"try",
":",
"app",
".",
"info",
"(",
"'adding bolditalic role...'",
",",
"nonl",
"=",
"True",
")",
"app",
".",
"add_role",
"(",
"'bolditalic'",
",",
"bolditalic",
")",
"app",
".",
"connect",
"(",
"'env-updated'",
","... | 26.722222 | 14.611111 |
def apply_thresholds(input, thresholds, choices):
"""
Return one of the choices depending on the input position compared to thresholds, for each input.
>>> apply_thresholds(np.array([4]), [5, 7], [10, 15, 20])
array([10])
>>> apply_thresholds(np.array([5]), [5, 7], [10, 15, 20])
array([10])
... | [
"def",
"apply_thresholds",
"(",
"input",
",",
"thresholds",
",",
"choices",
")",
":",
"condlist",
"=",
"[",
"input",
"<=",
"threshold",
"for",
"threshold",
"in",
"thresholds",
"]",
"if",
"len",
"(",
"condlist",
")",
"==",
"len",
"(",
"choices",
")",
"-",... | 44.272727 | 23.727273 |
def evaluate_cut(uncut_subsystem, cut, unpartitioned_ces):
"""Compute the system irreducibility for a given cut.
Args:
uncut_subsystem (Subsystem): The subsystem without the cut applied.
cut (Cut): The cut to evaluate.
unpartitioned_ces (CauseEffectStructure): The cause-effect structure... | [
"def",
"evaluate_cut",
"(",
"uncut_subsystem",
",",
"cut",
",",
"unpartitioned_ces",
")",
":",
"log",
".",
"debug",
"(",
"'Evaluating %s...'",
",",
"cut",
")",
"cut_subsystem",
"=",
"uncut_subsystem",
".",
"apply_cut",
"(",
"cut",
")",
"if",
"config",
".",
"... | 33.210526 | 20.052632 |
def saddr(address):
"""Return a string representation for an address.
The *address* paramater can be a pipe name, an IP address tuple, or a
socket address.
The return value is always a ``str`` instance.
"""
if isinstance(address, six.string_types):
return address
elif isinstance(ad... | [
"def",
"saddr",
"(",
"address",
")",
":",
"if",
"isinstance",
"(",
"address",
",",
"six",
".",
"string_types",
")",
":",
"return",
"address",
"elif",
"isinstance",
"(",
"address",
",",
"tuple",
")",
"and",
"len",
"(",
"address",
")",
">=",
"2",
"and",
... | 37.75 | 20.5 |
async def parse_response(self):
"""
:py:func:`asyncio.coroutine`
Parsing full server response (all lines).
:return: (code, lines)
:rtype: (:py:class:`aioftp.Code`, :py:class:`list` of :py:class:`str`)
:raises aioftp.StatusCodeError: if received code does not matches al... | [
"async",
"def",
"parse_response",
"(",
"self",
")",
":",
"code",
",",
"rest",
"=",
"await",
"self",
".",
"parse_line",
"(",
")",
"info",
"=",
"[",
"rest",
"]",
"curr_code",
"=",
"code",
"while",
"rest",
".",
"startswith",
"(",
"\"-\"",
")",
"or",
"no... | 34.333333 | 16.5 |
def _render(template, callable_, args, data, as_unicode=False):
"""create a Context and return the string
output of the given template and template callable."""
if as_unicode:
buf = util.FastEncodingBuffer(as_unicode=True)
elif template.bytestring_passthrough:
buf = compat.StringIO()
... | [
"def",
"_render",
"(",
"template",
",",
"callable_",
",",
"args",
",",
"data",
",",
"as_unicode",
"=",
"False",
")",
":",
"if",
"as_unicode",
":",
"buf",
"=",
"util",
".",
"FastEncodingBuffer",
"(",
"as_unicode",
"=",
"True",
")",
"elif",
"template",
"."... | 40.25 | 14.1 |
def directive_SPACE(self, label, params):
"""
label SPACE num
Allocate space on the stack. `num` is the number of bytes to allocate
"""
# TODO allow equations
params = params.strip()
try:
self.convert_to_integer(params)
except ValueError:
... | [
"def",
"directive_SPACE",
"(",
"self",
",",
"label",
",",
"params",
")",
":",
"# TODO allow equations",
"params",
"=",
"params",
".",
"strip",
"(",
")",
"try",
":",
"self",
".",
"convert_to_integer",
"(",
"params",
")",
"except",
"ValueError",
":",
"warnings... | 30.210526 | 16.842105 |
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True):
"""Evaluates by creating an Index containing evaluated data.
See `LazyResult`
Returns
-------
Index
Index with evaluated data.
"""
if self.start == ... | [
"def",
"evaluate",
"(",
"self",
",",
"verbose",
"=",
"False",
",",
"decode",
"=",
"True",
",",
"passes",
"=",
"None",
",",
"num_threads",
"=",
"1",
",",
"apply_experimental",
"=",
"True",
")",
":",
"if",
"self",
".",
"start",
"==",
"0",
"and",
"self"... | 33.647059 | 26.882353 |
def adjustFiles(rec, op): # type: (Any, Union[Callable[..., Any], partial[Any]]) -> None
"""Apply a mapping function to each File path in the object `rec`."""
if isinstance(rec, MutableMapping):
if rec.get("class") == "File":
rec["path"] = op(rec["path"])
for d in rec:
... | [
"def",
"adjustFiles",
"(",
"rec",
",",
"op",
")",
":",
"# type: (Any, Union[Callable[..., Any], partial[Any]]) -> None",
"if",
"isinstance",
"(",
"rec",
",",
"MutableMapping",
")",
":",
"if",
"rec",
".",
"get",
"(",
"\"class\"",
")",
"==",
"\"File\"",
":",
"rec"... | 38.818182 | 13.272727 |
def end(self):
"""End the roaster control process via thread signal.
This simply sends an exit signal to the thread, and shuts it down. In
order to stop monitoring, call the `set_monitor` method with false.
:returns: None
"""
self._process.shutdown()
self._roast... | [
"def",
"end",
"(",
"self",
")",
":",
"self",
".",
"_process",
".",
"shutdown",
"(",
")",
"self",
".",
"_roasting",
"=",
"False",
"self",
".",
"_roast",
"[",
"'date'",
"]",
"=",
"now_date",
"(",
"str",
"=",
"True",
")"
] | 33.636364 | 20.181818 |
def _reap_msg_frames(self, method_frame):
'''
Support method to reap header frame and body from current frame buffer.
Used in processing of basic.return, basic.deliver, and basic.get_ok.
Will return a pair (<header frame>, <body>), or re-queue current frames
and raise a FrameUnde... | [
"def",
"_reap_msg_frames",
"(",
"self",
",",
"method_frame",
")",
":",
"# No need to assert that is instance of Header or Content frames",
"# because failure to access as such will result in exception that",
"# channel will pick up and handle accordingly.",
"header_frame",
"=",
"self",
"... | 41.90625 | 19.21875 |
def setData(self, index, value, role=Qt.DisplayRole):
"""Set the value to the index position depending on Qt::ItemDataRole and data type of the column
Args:
index (QtCore.QModelIndex): Index to define column and row.
value (object): new value.
role (Qt::ItemDataRole)... | [
"def",
"setData",
"(",
"self",
",",
"index",
",",
"value",
",",
"role",
"=",
"Qt",
".",
"DisplayRole",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
"or",
"not",
"self",
".",
"editable",
":",
"return",
"False",
"if",
"value",
"!=",
"ind... | 37.353846 | 21.892308 |
def abort_request(self, stream, ident, parent):
"""abort a specifig msg by id"""
msg_ids = parent['content'].get('msg_ids', None)
if isinstance(msg_ids, basestring):
msg_ids = [msg_ids]
if not msg_ids:
self.abort_queues()
for mid in msg_ids:
se... | [
"def",
"abort_request",
"(",
"self",
",",
"stream",
",",
"ident",
",",
"parent",
")",
":",
"msg_ids",
"=",
"parent",
"[",
"'content'",
"]",
".",
"get",
"(",
"'msg_ids'",
",",
"None",
")",
"if",
"isinstance",
"(",
"msg_ids",
",",
"basestring",
")",
":",... | 37.857143 | 11.571429 |
def subscribe(ws):
"""WebSocket endpoint, used for liveupdates"""
while ws is not None:
gevent.sleep(0.1)
try:
message = ws.receive() # expect function name to subscribe to
if message:
stream.register(ws, message)
except WebSocketError:
... | [
"def",
"subscribe",
"(",
"ws",
")",
":",
"while",
"ws",
"is",
"not",
"None",
":",
"gevent",
".",
"sleep",
"(",
"0.1",
")",
"try",
":",
"message",
"=",
"ws",
".",
"receive",
"(",
")",
"# expect function name to subscribe to",
"if",
"message",
":",
"stream... | 32.2 | 16.4 |
def atualizar_software_sat(self):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
resp = self._http_post('atualizarsoftwaresat')
conteudo = resp.json()
return Res... | [
"def",
"atualizar_software_sat",
"(",
"self",
")",
":",
"resp",
"=",
"self",
".",
"_http_post",
"(",
"'atualizarsoftwaresat'",
")",
"conteudo",
"=",
"resp",
".",
"json",
"(",
")",
"return",
"RespostaSAT",
".",
"atualizar_software_sat",
"(",
"conteudo",
".",
"g... | 40.888889 | 12.888889 |
def delete_video_transcript(video_id, language_code):
"""
Delete transcript for an existing video.
Arguments:
video_id: id identifying the video to which the transcript is associated.
language_code: language code of a video transcript.
"""
video_transcript = VideoTranscript.get_or_n... | [
"def",
"delete_video_transcript",
"(",
"video_id",
",",
"language_code",
")",
":",
"video_transcript",
"=",
"VideoTranscript",
".",
"get_or_none",
"(",
"video_id",
",",
"language_code",
")",
"if",
"video_transcript",
":",
"# delete the transcript content from storage.",
"... | 43.333333 | 19.6 |
def create_arch(configuration, tasks_fs, context, course_factory):
""" Helper that can start a simple complete INGInious arch locally if needed, or a client to a remote backend.
Intended to be used on command line, makes uses of exit() and the logger inginious.frontend.
:param configuration: configurati... | [
"def",
"create_arch",
"(",
"configuration",
",",
"tasks_fs",
",",
"context",
",",
"course_factory",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"\"inginious.frontend\"",
")",
"backend_link",
"=",
"configuration",
".",
"get",
"(",
"\"backend\"",
",... | 53.155172 | 31.413793 |
def get_xml_root(xml_file):
"""Returns XML root."""
try:
xml_root = etree.parse(os.path.expanduser(xml_file), NO_BLANKS_PARSER).getroot()
# pylint: disable=broad-except
except Exception as err:
raise Dump2PolarionException("Failed to parse XML file '{}': {}".format(xml_file, err))
re... | [
"def",
"get_xml_root",
"(",
"xml_file",
")",
":",
"try",
":",
"xml_root",
"=",
"etree",
".",
"parse",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"xml_file",
")",
",",
"NO_BLANKS_PARSER",
")",
".",
"getroot",
"(",
")",
"# pylint: disable=broad-except",
... | 40.75 | 23.375 |
def _scale_fig_size(figsize, textsize, rows=1, cols=1):
"""Scale figure properties according to rows and cols.
Parameters
----------
figsize : float or None
Size of figure in inches
textsize : float or None
fontsize
rows : int
Number of rows
cols : int
Number... | [
"def",
"_scale_fig_size",
"(",
"figsize",
",",
"textsize",
",",
"rows",
"=",
"1",
",",
"cols",
"=",
"1",
")",
":",
"params",
"=",
"mpl",
".",
"rcParams",
"rc_width",
",",
"rc_height",
"=",
"tuple",
"(",
"params",
"[",
"\"figure.figsize\"",
"]",
")",
"r... | 29.061538 | 16.492308 |
def install_bundle(self, name, path=None):
# type: (str, str) -> Bundle
"""
Installs the bundle with the given name
*Note:* Before Pelix 0.5.0, this method returned the ID of the
installed bundle, instead of the Bundle object.
**WARNING:** The behavior of the loading pr... | [
"def",
"install_bundle",
"(",
"self",
",",
"name",
",",
"path",
"=",
"None",
")",
":",
"# type: (str, str) -> Bundle",
"with",
"self",
".",
"__bundles_lock",
":",
"# A bundle can't be installed twice",
"for",
"bundle",
"in",
"self",
".",
"__bundles",
".",
"values"... | 37.26087 | 17.144928 |
def plot_brillouin_zone_from_kpath(kpath, ax=None, **kwargs):
"""
Gives the plot (as a matplotlib object) of the symmetry line path in
the Brillouin Zone.
Args:
kpath (HighSymmKpath): a HighSymmKPath object
ax: matplotlib :class:`Axes` or None if a new figure should be created.
... | [
"def",
"plot_brillouin_zone_from_kpath",
"(",
"kpath",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"lines",
"=",
"[",
"[",
"kpath",
".",
"kpath",
"[",
"'kpoints'",
"]",
"[",
"k",
"]",
"for",
"k",
"in",
"p",
"]",
"for",
"p",
"in",
"... | 35.944444 | 22.611111 |
def replace(self, new_node):
"""Replace a node after first checking integrity of node stack."""
cur_node = self.cur_node
nodestack = self.nodestack
cur = nodestack.pop()
prev = nodestack[-1]
index = prev[-1] - 1
oldnode, name = prev[-2][index]
assert cur[0... | [
"def",
"replace",
"(",
"self",
",",
"new_node",
")",
":",
"cur_node",
"=",
"self",
".",
"cur_node",
"nodestack",
"=",
"self",
".",
"nodestack",
"cur",
"=",
"nodestack",
".",
"pop",
"(",
")",
"prev",
"=",
"nodestack",
"[",
"-",
"1",
"]",
"index",
"=",... | 38.066667 | 10.866667 |
def get_subnet_flow_logs_list(current_config, subnet):
"""
Return the flow logs that cover a given subnet
:param current_config:
:param subnet: the subnet that the flow logs should cover
:return:
"""
flow_logs_list = []
for flow_log in current_config.flow_logs:
if current_config... | [
"def",
"get_subnet_flow_logs_list",
"(",
"current_config",
",",
"subnet",
")",
":",
"flow_logs_list",
"=",
"[",
"]",
"for",
"flow_log",
"in",
"current_config",
".",
"flow_logs",
":",
"if",
"current_config",
".",
"flow_logs",
"[",
"flow_log",
"]",
"[",
"'Resource... | 37.357143 | 18.357143 |
def art_list(test=False):
"""
Print all 1-Line arts.
:param test : exception test flag
:type test : bool
:return: None
"""
for i in sorted(list(art_dic.keys())):
try:
if test:
raise Exception
print(i)
aprint(i)
line()
... | [
"def",
"art_list",
"(",
"test",
"=",
"False",
")",
":",
"for",
"i",
"in",
"sorted",
"(",
"list",
"(",
"art_dic",
".",
"keys",
"(",
")",
")",
")",
":",
"try",
":",
"if",
"test",
":",
"raise",
"Exception",
"print",
"(",
"i",
")",
"aprint",
"(",
"... | 21.5 | 15.6 |
def _build_likelihood(self):
r"""
q_alpha, q_lambda are variational parameters, size N x R
This method computes the variational lower bound on the likelihood,
which is:
E_{q(F)} [ \log p(Y|F) ] - KL[ q(F) || p(F)]
with
q(f) = N(f | K alpha + mean, [K^-1 + ... | [
"def",
"_build_likelihood",
"(",
"self",
")",
":",
"K",
"=",
"self",
".",
"kern",
".",
"K",
"(",
"self",
".",
"X",
")",
"K_alpha",
"=",
"tf",
".",
"matmul",
"(",
"K",
",",
"self",
".",
"q_alpha",
")",
"f_mean",
"=",
"K_alpha",
"+",
"self",
".",
... | 44.875 | 22.03125 |
def add_units(self, units, factor, latexrepr=None):
"""
Add new possible units.
:arg units: units
:type units: :class:`str`
:arg factor: multiplication factor to convert new units into base units
:type factor: :class:`float`
:arg latexr... | [
"def",
"add_units",
"(",
"self",
",",
"units",
",",
"factor",
",",
"latexrepr",
"=",
"None",
")",
":",
"if",
"units",
"in",
"self",
".",
"_units",
":",
"raise",
"ValueError",
"(",
"'%s already defined'",
"%",
"units",
")",
"if",
"factor",
"==",
"1",
":... | 32.954545 | 16.136364 |
def unregister_engine(self, ident, msg):
"""Unregister an engine that explicitly requested to leave."""
try:
eid = msg['content']['id']
except:
self.log.error("registration::bad engine id for unregistration: %r", ident, exc_info=True)
return
self.log.i... | [
"def",
"unregister_engine",
"(",
"self",
",",
"ident",
",",
"msg",
")",
":",
"try",
":",
"eid",
"=",
"msg",
"[",
"'content'",
"]",
"[",
"'id'",
"]",
"except",
":",
"self",
".",
"log",
".",
"error",
"(",
"\"registration::bad engine id for unregistration: %r\"... | 41 | 18.461538 |
def dump_nparray(self, obj, class_name=numpy_ndarray_class_name):
"""
``numpy.ndarray`` dumper.
"""
return {"$" + class_name: self._json_convert(obj.tolist())} | [
"def",
"dump_nparray",
"(",
"self",
",",
"obj",
",",
"class_name",
"=",
"numpy_ndarray_class_name",
")",
":",
"return",
"{",
"\"$\"",
"+",
"class_name",
":",
"self",
".",
"_json_convert",
"(",
"obj",
".",
"tolist",
"(",
")",
")",
"}"
] | 37.4 | 11.8 |
def simulate(self, ts_length=100, random_state=None):
r"""
Simulate a time series of length ts_length, first drawing
.. math::
x_0 \sim N(\mu_0, \Sigma_0)
Parameters
----------
ts_length : scalar(int), optional(default=100)
The length of the sim... | [
"def",
"simulate",
"(",
"self",
",",
"ts_length",
"=",
"100",
",",
"random_state",
"=",
"None",
")",
":",
"random_state",
"=",
"check_random_state",
"(",
"random_state",
")",
"x0",
"=",
"multivariate_normal",
"(",
"self",
".",
"mu_0",
".",
"flatten",
"(",
... | 33.609756 | 22.02439 |
def update_port_statuses_cfg(self, context, port_ids, status):
"""Update the operational statuses of a list of router ports.
This is called by the Cisco cfg agent to update the status of a list
of ports.
:param context: contains user information
:param port_ids: list of ids of ... | [
"def",
"update_port_statuses_cfg",
"(",
"self",
",",
"context",
",",
"port_ids",
",",
"status",
")",
":",
"self",
".",
"_l3plugin",
".",
"update_router_port_statuses",
"(",
"context",
",",
"port_ids",
",",
"status",
")"
] | 45.333333 | 22.5 |
def update_cache(func):
"""Decorate functions that modify the internally stored usernotes JSON.
Ensures that updates are mirrored onto reddit.
Arguments:
func: the function being decorated
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
"""The wrapper function."""
... | [
"def",
"update_cache",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"The wrapper function.\"\"\"",
"lazy",
"=",
"kwargs",
".",
"get",
"(",
"'lazy'",
","... | 25.038462 | 17.923077 |
def get_parameter(self, path, default=None, return_group=False):
"""
Reads hyperparameter from job configuration. If nothing found use given default.
:param path: str
:param default: *
:param return_group: If true and path is a choice_group, we return the dict instead of the gr... | [
"def",
"get_parameter",
"(",
"self",
",",
"path",
",",
"default",
"=",
"None",
",",
"return_group",
"=",
"False",
")",
":",
"value",
"=",
"read_parameter_by_path",
"(",
"self",
".",
"job",
"[",
"'config'",
"]",
"[",
"'parameters'",
"]",
",",
"path",
",",... | 34.333333 | 27.666667 |
def process_data(input_file: str,
output_file: str,
max_path_length: int,
max_num_logical_forms: int,
ignore_agenda: bool,
write_sequences: bool) -> None:
"""
Reads an NLVR dataset and returns a JSON representation containing s... | [
"def",
"process_data",
"(",
"input_file",
":",
"str",
",",
"output_file",
":",
"str",
",",
"max_path_length",
":",
"int",
",",
"max_num_logical_forms",
":",
"int",
",",
"ignore_agenda",
":",
"bool",
",",
"write_sequences",
":",
"bool",
")",
"->",
"None",
":"... | 59.383562 | 26.39726 |
def get_vmotion_enabled(host, username, password, protocol=None, port=None, host_names=None):
'''
Get the VMotion enabled status for a given host or a list of host_names. Returns ``True``
if VMotion is enabled, ``False`` if it is not enabled.
host
The location of the host.
username
... | [
"def",
"get_vmotion_enabled",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
")",
":",
"service_instance",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_service_i... | 40.5 | 30.637931 |
def camera_trigger_send(self, time_usec, seq, force_mavlink1=False):
'''
Camera-IMU triggering and synchronisation message.
time_usec : Timestamp for the image frame in microseconds (uint64_t)
seq : Image frame sequen... | [
"def",
"camera_trigger_send",
"(",
"self",
",",
"time_usec",
",",
"seq",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"camera_trigger_encode",
"(",
"time_usec",
",",
"seq",
")",
",",
"force_mavlink1",
"=",
... | 50.444444 | 37.555556 |
def collect_by_typename(obj_sequence, cache=None):
"""
collects objects from obj_sequence and stores them into buckets by
type name. cache is an optional dict into which we collect the
results.
"""
if cache is None:
cache = {}
for val in obj_sequence:
key = type(val).__name... | [
"def",
"collect_by_typename",
"(",
"obj_sequence",
",",
"cache",
"=",
"None",
")",
":",
"if",
"cache",
"is",
"None",
":",
"cache",
"=",
"{",
"}",
"for",
"val",
"in",
"obj_sequence",
":",
"key",
"=",
"type",
"(",
"val",
")",
".",
"__name__",
"bucket",
... | 23.35 | 19.95 |
def do_work(self, actions_queue, returns_queue, control_queue=None): # pragma: no cover
"""Main function of the worker.
* Get checks
* Launch new checks
* Manage finished checks
:param actions_queue: Global Queue Master->Slave
:type actions_queue: Queue.Queue
:p... | [
"def",
"do_work",
"(",
"self",
",",
"actions_queue",
",",
"returns_queue",
",",
"control_queue",
"=",
"None",
")",
":",
"# pragma: no cover",
"# restore default signal handler for the workers:",
"# signal.signal(signal.SIGTERM, signal.SIG_DFL)",
"self",
".",
"interrupted",
"=... | 42.432099 | 22.234568 |
def get_urls(self):
"""
Add ``layout_placeholder_data`` URL.
"""
# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.
urls = super(LayoutAdmin, self).get_urls()
my_urls = patterns(
'',
url(
r'^placeholder_data/(?P<id>\d... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"# See: `fluent_pages.pagetypes.fluentpage.admin.FluentPageAdmin`.",
"urls",
"=",
"super",
"(",
"LayoutAdmin",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"my_urls",
"=",
"patterns",
"(",
"''",
",",
"url",
"(",
"r'^plac... | 32.4 | 16.533333 |
def identify(text):
"""Identify whether a string is simplified or traditional Chinese.
Returns:
None: if there are no recognizd Chinese characters.
EITHER: if the test is inconclusive.
TRAD: if the text is traditional.
SIMP: if the text is simplified.
BOTH: the text has ... | [
"def",
"identify",
"(",
"text",
")",
":",
"filtered_text",
"=",
"set",
"(",
"list",
"(",
"text",
")",
")",
".",
"intersection",
"(",
"ALL_CHARS",
")",
"if",
"len",
"(",
"filtered_text",
")",
"is",
"0",
":",
"return",
"None",
"if",
"filtered_text",
".",... | 35.608696 | 16.695652 |
def process_events(self):
"""
Loop through and handle all the queued events.
"""
for event in sdl2.ext.get_events():
if event.type == sdl2.SDL_MOUSEMOTION:
self.example.mouse_position_event(event.motion.x, event.motion.y)
elif event.type =... | [
"def",
"process_events",
"(",
"self",
")",
":",
"for",
"event",
"in",
"sdl2",
".",
"ext",
".",
"get_events",
"(",
")",
":",
"if",
"event",
".",
"type",
"==",
"sdl2",
".",
"SDL_MOUSEMOTION",
":",
"self",
".",
"example",
".",
"mouse_position_event",
"(",
... | 42.111111 | 20.444444 |
def nvmlShutdown():
r"""
/**
* Shut down NVML by releasing all GPU resources previously allocated with \ref nvmlInit().
*
* For all products.
*
* This method should be called after NVML work is done, once for each call to \ref nvmlInit()
* A reference count of the number of initial... | [
"def",
"nvmlShutdown",
"(",
")",
":",
"#",
"# Leave the library loaded, but shutdown the interface",
"#",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlShutdown\"",
")",
"ret",
"=",
"fn",
"(",
")",
"_nvmlCheckReturn",
"(",
"ret",
")",
"# Atomically update refcount",... | 36.060606 | 27.060606 |
def get_category(self, metric):
"""
Return a string category for the metric.
The category is made up of this reporter's prefix and the
metric's group and tags.
Examples:
prefix = 'foo', group = 'bar', tags = {'a': 1, 'b': 2}
returns: 'foo.bar.a=1,b=2'
... | [
"def",
"get_category",
"(",
"self",
",",
"metric",
")",
":",
"tags",
"=",
"','",
".",
"join",
"(",
"'%s=%s'",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"metric",
".",
"metric_name",
".",
"tags",
".",
"items",
"(",
... | 33.714286 | 18.571429 |
def _set_bin_view(self, session):
"""Sets the underlying bin view to match current view"""
if self._bin_view == FEDERATED:
try:
session.use_federated_bin_view()
except AttributeError:
pass
else:
try:
session.use_... | [
"def",
"_set_bin_view",
"(",
"self",
",",
"session",
")",
":",
"if",
"self",
".",
"_bin_view",
"==",
"FEDERATED",
":",
"try",
":",
"session",
".",
"use_federated_bin_view",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"else",
":",
"try",
":",
"sessio... | 32 | 12.5 |
def smart_generic_inlineformset_factory(model, request, form=ModelForm, formset=BaseGenericInlineFormSet,
ct_field='content_type', fk_field='object_id', fields=None, exclude=None,
extra=3, can_order=False, can_delete=True, min_num=None, max... | [
"def",
"smart_generic_inlineformset_factory",
"(",
"model",
",",
"request",
",",
"form",
"=",
"ModelForm",
",",
"formset",
"=",
"BaseGenericInlineFormSet",
",",
"ct_field",
"=",
"'content_type'",
",",
"fk_field",
"=",
"'object_id'",
",",
"fields",
"=",
"None",
","... | 45.075472 | 23.716981 |
def create_model(self, model):
"""Ran when a new model is created."""
for field in model._meta.local_fields:
if not isinstance(field, HStoreField):
continue
self.add_field(model, field) | [
"def",
"create_model",
"(",
"self",
",",
"model",
")",
":",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"local_fields",
":",
"if",
"not",
"isinstance",
"(",
"field",
",",
"HStoreField",
")",
":",
"continue",
"self",
".",
"add_field",
"(",
"model",
... | 29.5 | 15.25 |
def _check_perms(obj_name, obj_type, new_perms, cur_perms, access_mode, ret):
'''
Helper function used by ``check_perms`` for checking and setting Grant and
Deny permissions.
Args:
obj_name (str):
The name or full path to the object
obj_type (Optional[str]):
Th... | [
"def",
"_check_perms",
"(",
"obj_name",
",",
"obj_type",
",",
"new_perms",
",",
"cur_perms",
",",
"access_mode",
",",
"ret",
")",
":",
"access_mode",
"=",
"access_mode",
".",
"lower",
"(",
")",
"changes",
"=",
"{",
"}",
"for",
"user",
"in",
"new_perms",
... | 46.095808 | 22.802395 |
def _link_variables_on_expr(self, variable_manager, block, stmt_idx, stmt, expr):
"""
Link atoms (AIL expressions) in the given expression to corresponding variables identified previously.
:param variable_manager: Variable manager of the function.
:param ailment.Block block: AIL bloc... | [
"def",
"_link_variables_on_expr",
"(",
"self",
",",
"variable_manager",
",",
"block",
",",
"stmt_idx",
",",
"stmt",
",",
"expr",
")",
":",
"if",
"type",
"(",
"expr",
")",
"is",
"ailment",
".",
"Expr",
".",
"Register",
":",
"# find a register variable",
"reg_... | 48.619048 | 23 |
def load(self, base_settings):
"""Merge local settings from file with ``base_settings``.
Returns a new settings dict containing the base settings and the
loaded settings. Includes:
- base settings
- settings from extended file(s), if any
- settings from file... | [
"def",
"load",
"(",
"self",
",",
"base_settings",
")",
":",
"is_valid_key",
"=",
"lambda",
"k",
":",
"k",
".",
"isupper",
"(",
")",
"and",
"not",
"k",
".",
"startswith",
"(",
"'_'",
")",
"# Base settings, including `LocalSetting`s, loaded from the",
"# Django se... | 39.615385 | 21.897436 |
def _convert_queue_message_xml(message_text, encode_function, key_encryption_key):
'''
<?xml version="1.0" encoding="utf-8"?>
<QueueMessage>
<MessageText></MessageText>
</QueueMessage>
'''
queue_message_element = ETree.Element('QueueMessage')
# Enabled
message_text = encode_func... | [
"def",
"_convert_queue_message_xml",
"(",
"message_text",
",",
"encode_function",
",",
"key_encryption_key",
")",
":",
"queue_message_element",
"=",
"ETree",
".",
"Element",
"(",
"'QueueMessage'",
")",
"# Enabled",
"message_text",
"=",
"encode_function",
"(",
"message_t... | 33.208333 | 25.291667 |
def join(self, timeout=None):
"""
Waits for all the tasks to be executed
:param timeout: Maximum time to wait (in seconds)
:return: True if the queue has been emptied, else False
"""
if self._queue.empty():
# Nothing to wait for...
return True
... | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"_queue",
".",
"empty",
"(",
")",
":",
"# Nothing to wait for...",
"return",
"True",
"elif",
"timeout",
"is",
"None",
":",
"# Use the original join",
"self",
".",
"_queue... | 33.368421 | 12.736842 |
def _store(self, messages, response, *args, **kwargs):
"""
Delete all messages that are sticky and return the other messages
This storage never save objects
"""
return [message for message in messages if not message.level in STICKY_MESSAGE_LEVELS] | [
"def",
"_store",
"(",
"self",
",",
"messages",
",",
"response",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"message",
"for",
"message",
"in",
"messages",
"if",
"not",
"message",
".",
"level",
"in",
"STICKY_MESSAGE_LEVELS",
"]"
] | 47 | 17 |
def export_to_template(filename, args, exclude=None):
"""Exports given options to the given filename in INI format.
:param filename: Filename to save options to
:param dict args: Arguments to export
:param list exclude (optional): Exclusion list for options that should not
... | [
"def",
"export_to_template",
"(",
"filename",
",",
"args",
",",
"exclude",
"=",
"None",
")",
":",
"exclude",
"=",
"exclude",
"or",
"[",
"]",
"exclude",
".",
"append",
"(",
"'config'",
")",
"exclude",
".",
"append",
"(",
"'really'",
")",
"exclude",
".",
... | 37.090909 | 11 |
def _single_function_inclusion_filter_builder(func: str) -> NodePredicate: # noqa: D202
"""Build a function inclusion filter for a single function."""
def function_inclusion_filter(_: BELGraph, node: BaseEntity) -> bool:
"""Pass only for a node that has the enclosed function."""
return node.fu... | [
"def",
"_single_function_inclusion_filter_builder",
"(",
"func",
":",
"str",
")",
"->",
"NodePredicate",
":",
"# noqa: D202",
"def",
"function_inclusion_filter",
"(",
"_",
":",
"BELGraph",
",",
"node",
":",
"BaseEntity",
")",
"->",
"bool",
":",
"\"\"\"Pass only for ... | 45.625 | 21.125 |
def store(self, filename=None, label=None, desc=None, date=None):
"""Store object to mat-file. TODO: determine format specification
"""
date = datetime.now() if date is None else date
filename = filename if filename else date.replace(microsecond=0).isoformat() + '.mat'
def store... | [
"def",
"store",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"label",
"=",
"None",
",",
"desc",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"date",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"date",
"is",
"None",
"else",
"date",
"filena... | 40.15 | 15.55 |
def get_connection(self):
"""
Return a connection from the pool using the `ConnectionSelector`
instance.
It tries to resurrect eligible connections, forces a resurrection when
no connections are availible and passes the list of live connections to
the selector instance t... | [
"def",
"get_connection",
"(",
"self",
")",
":",
"self",
".",
"resurrect",
"(",
")",
"# no live nodes, resurrect one by force",
"if",
"not",
"self",
".",
"connections",
":",
"self",
".",
"resurrect",
"(",
"True",
")",
"connection",
"=",
"self",
".",
"selector",... | 32.789474 | 21.631579 |
def u64(self, name, value=None, align=None):
"""Add an unsigned 8 byte integer field to template.
This is an convenience method that simply calls `Uint` keyword with predefined length."""
self.uint(8, name, value, align) | [
"def",
"u64",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
",",
"align",
"=",
"None",
")",
":",
"self",
".",
"uint",
"(",
"8",
",",
"name",
",",
"value",
",",
"align",
")"
] | 48.2 | 8.8 |
def collapse_nodes(graph, survivor_mapping: Mapping[BaseEntity, Set[BaseEntity]]) -> None:
"""Collapse all nodes in values to the key nodes, in place.
:param pybel.BELGraph graph: A BEL graph
:param survivor_mapping: A dictionary with survivors as their keys, and iterables of the corresponding victims as
... | [
"def",
"collapse_nodes",
"(",
"graph",
",",
"survivor_mapping",
":",
"Mapping",
"[",
"BaseEntity",
",",
"Set",
"[",
"BaseEntity",
"]",
"]",
")",
"->",
"None",
":",
"inconsistencies",
"=",
"surviors_are_inconsistent",
"(",
"survivor_mapping",
")",
"if",
"inconsis... | 43 | 26.875 |
def plot_density(self, plot_limits=None, fixed_inputs=None,
resolution=None, plot_raw=False,
apply_link=False, visible_dims=None,
which_data_ycols='all',
levels=35, label='gp density',
predict_kw=None,
**kwargs):
"""
Plot the co... | [
"def",
"plot_density",
"(",
"self",
",",
"plot_limits",
"=",
"None",
",",
"fixed_inputs",
"=",
"None",
",",
"resolution",
"=",
"None",
",",
"plot_raw",
"=",
"False",
",",
"apply_link",
"=",
"False",
",",
"visible_dims",
"=",
"None",
",",
"which_data_ycols",
... | 63.216216 | 34.189189 |
def parse_known_args(self, args = None, namespace = None,
config_file_contents = None, env_vars = os.environ):
"""Supports all the same args as the ArgumentParser.parse_args(..),
as well as the following additional args.
Additional Args:
args: a list of args... | [
"def",
"parse_known_args",
"(",
"self",
",",
"args",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"config_file_contents",
"=",
"None",
",",
"env_vars",
"=",
"os",
".",
"environ",
")",
":",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"sys",
".",
... | 46.006173 | 21.759259 |
def newPI(name, content):
"""Creation of a processing instruction element. Use
xmlDocNewPI preferably to get string interning """
ret = libxml2mod.xmlNewPI(name, content)
if ret is None:raise treeError('xmlNewPI() failed')
return xmlNode(_obj=ret) | [
"def",
"newPI",
"(",
"name",
",",
"content",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlNewPI",
"(",
"name",
",",
"content",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
"(",
"'xmlNewPI() failed'",
")",
"return",
"xmlNode",
"(",
"_obj",
... | 44.166667 | 7.666667 |
def to_internal_value(self, value):
"""Basically, each tag dict must include a full dict with id,
name and slug--or else you need to pass in a dict with just a name,
which indicated that the Tag doesn't exist, and should be added."""
if "id" in value:
tag = Tag.objects.get(i... | [
"def",
"to_internal_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"\"id\"",
"in",
"value",
":",
"tag",
"=",
"Tag",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"value",
"[",
"\"id\"",
"]",
")",
"else",
":",
"if",
"\"name\"",
"not",
"in",
"value... | 42.75 | 18.55 |
def main():
"""The main entry point, compatible with setuptools."""
# pylint: disable=bad-continuation
from optparse import OptionParser, OptionGroup
parser = OptionParser(usage="%prog [options] <folder path> ...",
version="%s v%s" % (__appname__, __version__))
parser.add_option('-D', '-... | [
"def",
"main",
"(",
")",
":",
"# pylint: disable=bad-continuation",
"from",
"optparse",
"import",
"OptionParser",
",",
"OptionGroup",
"parser",
"=",
"OptionParser",
"(",
"usage",
"=",
"\"%prog [options] <folder path> ...\"",
",",
"version",
"=",
"\"%s v%s\"",
"%",
"("... | 51.045455 | 25.242424 |
def smart_unicode(string, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a unicode object representing 's'. Treats bytestrings using the
'encoding' codec.
If strings_only is True, don't convert (some) non-string-like objects.
"""
# if isinstance(s, Promise):
# # The... | [
"def",
"smart_unicode",
"(",
"string",
",",
"encoding",
"=",
"'utf-8'",
",",
"strings_only",
"=",
"False",
",",
"errors",
"=",
"'strict'",
")",
":",
"# if isinstance(s, Promise):",
"# # The input is the result of a gettext_lazy() call.",
"# return s",
"return",
"f... | 40 | 22.181818 |
def _proc_pax(self, filetar):
"""Process an extended or global header as described in POSIX.1-2001."""
# Read the header information.
buf = filetar.fileobj.read(self._block(self.size))
# A pax header stores supplemental information for either
# the following file (extended) or all following files
... | [
"def",
"_proc_pax",
"(",
"self",
",",
"filetar",
")",
":",
"# Read the header information.",
"buf",
"=",
"filetar",
".",
"fileobj",
".",
"read",
"(",
"self",
".",
"_block",
"(",
"self",
".",
"size",
")",
")",
"# A pax header stores supplemental information for eit... | 33.258065 | 20.322581 |
def record(self):
# type: () -> bytes
'''
Generate a string representing the Rock Ridge Alternate Name record.
Parameters:
None.
Returns:
String containing the Rock Ridge record.
'''
if not self._initialized:
raise pycdlibexception.P... | [
"def",
"record",
"(",
"self",
")",
":",
"# type: () -> bytes",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'NM record not yet initialized!'",
")",
"return",
"b'NM'",
"+",
"struct",
".",
"pack",
"("... | 35.714286 | 31.714286 |
def Pepper(p=0, per_channel=False, name=None, deterministic=False, random_state=None):
"""
Adds pepper noise to an image, i.e. black-ish pixels.
This is similar to dropout, but slower and the black pixels are not uniformly black.
dtype support::
See ``imgaug.augmenters.arithmetic.ReplaceEleme... | [
"def",
"Pepper",
"(",
"p",
"=",
"0",
",",
"per_channel",
"=",
"False",
",",
"name",
"=",
"None",
",",
"deterministic",
"=",
"False",
",",
"random_state",
"=",
"None",
")",
":",
"replacement01",
"=",
"iap",
".",
"ForceSign",
"(",
"iap",
".",
"Beta",
"... | 33.38806 | 24.58209 |
def citation_count(papers, key='ayjid', verbose=False):
"""
Generates citation counts for all of the papers cited by papers.
Parameters
----------
papers : list
A list of :class:`.Paper` instances.
key : str
Property to use as node key. Default is 'ayjid' (recommended).
verb... | [
"def",
"citation_count",
"(",
"papers",
",",
"key",
"=",
"'ayjid'",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"\"Generating citation counts for \"",
"+",
"unicode",
"(",
"len",
"(",
"papers",
")",
")",
"+",
"\" papers...\"",
"cou... | 25 | 21.896552 |
def _compute_count_availability(resource, status, previous_status):
'''Compute the `check:count-availability` extra value'''
count_availability = resource.extras.get('check:count-availability', 1)
return count_availability + 1 if status == previous_status else 1 | [
"def",
"_compute_count_availability",
"(",
"resource",
",",
"status",
",",
"previous_status",
")",
":",
"count_availability",
"=",
"resource",
".",
"extras",
".",
"get",
"(",
"'check:count-availability'",
",",
"1",
")",
"return",
"count_availability",
"+",
"1",
"i... | 67.75 | 27.75 |
def _normalize_group_attrs(self, attrs):
"""Normalize the attributes used to set groups
If it's a list of one element, it just become this
element.
It raises an error if the attribute doesn't exist
or if it's multivaluated.
"""
for key in self.group_attrs_keys:
... | [
"def",
"_normalize_group_attrs",
"(",
"self",
",",
"attrs",
")",
":",
"for",
"key",
"in",
"self",
".",
"group_attrs_keys",
":",
"if",
"key",
"not",
"in",
"attrs",
":",
"raise",
"MissingGroupAttr",
"(",
"key",
")",
"if",
"type",
"(",
"attrs",
"[",
"key",
... | 43.142857 | 9.785714 |
def _read_stderr(self):
"""Read the stderr file of the kernel."""
# We need to read stderr_file as bytes to be able to
# detect its encoding with chardet
f = open(self.stderr_file, 'rb')
try:
stderr_text = f.read()
# This is needed to avoid show... | [
"def",
"_read_stderr",
"(",
"self",
")",
":",
"# We need to read stderr_file as bytes to be able to\r",
"# detect its encoding with chardet\r",
"f",
"=",
"open",
"(",
"self",
".",
"stderr_file",
",",
"'rb'",
")",
"try",
":",
"stderr_text",
"=",
"f",
".",
"read",
"("... | 35.217391 | 17.391304 |
def apply_trend_constraint(self, limit, dt, distribution_skip=False,
**kwargs):
"""
Constrains change in RV to be less than limit over time dt.
Only works if ``dRV`` and ``Plong`` attributes are defined
for population.
:param limit:
Ra... | [
"def",
"apply_trend_constraint",
"(",
"self",
",",
"limit",
",",
"dt",
",",
"distribution_skip",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"type",
"(",
"limit",
")",
"!=",
"Quantity",
":",
"limit",
"=",
"limit",
"*",
"u",
".",
"m",
"/",
... | 34.825 | 19.175 |
def cctop_save_xml(jobid, outpath):
"""Save the CCTOP results file in XML format.
Args:
jobid (str): Job ID obtained when job was submitted
outpath (str): Path to output filename
Returns:
str: Path to output filename
"""
status = cctop_check_status(jobid=jobid)
if stat... | [
"def",
"cctop_save_xml",
"(",
"jobid",
",",
"outpath",
")",
":",
"status",
"=",
"cctop_check_status",
"(",
"jobid",
"=",
"jobid",
")",
"if",
"status",
"==",
"'Finished'",
":",
"result",
"=",
"'http://cctop.enzim.ttk.mta.hu/php/result.php?jobId={}'",
".",
"format",
... | 32.5 | 19.2 |
async def main():
"""Sample code to retrieve the data."""
async with aiohttp.ClientSession() as session:
data = Luftdaten(SENSOR_ID, loop, session)
await data.get_data()
if not await data.validate_sensor():
print("Station is not available:", data.sensor_id)
retur... | [
"async",
"def",
"main",
"(",
")",
":",
"async",
"with",
"aiohttp",
".",
"ClientSession",
"(",
")",
"as",
"session",
":",
"data",
"=",
"Luftdaten",
"(",
"SENSOR_ID",
",",
"loop",
",",
"session",
")",
"await",
"data",
".",
"get_data",
"(",
")",
"if",
"... | 35.0625 | 17.625 |
def allsame(iterable, eq=operator.eq):
"""
Determine if all items in a sequence are the same
Args:
iterable (Iterable): items to determine if they are all the same
eq (Callable, optional): function to determine equality
(default: operator.eq)
Example:
>>> allsame([... | [
"def",
"allsame",
"(",
"iterable",
",",
"eq",
"=",
"operator",
".",
"eq",
")",
":",
"iter_",
"=",
"iter",
"(",
"iterable",
")",
"try",
":",
"first",
"=",
"next",
"(",
"iter_",
")",
"except",
"StopIteration",
":",
"return",
"True",
"return",
"all",
"(... | 24.40625 | 18.96875 |
def permission_check(apikey, endpoint):
"""
return (user, seckey) if url end point is in allowed entry point list
"""
try:
ak = APIKeys.objects.get(apikey=apikey)
apitree = cPickle.loads(ak.apitree.encode("ascii"))
if apitree.match(endpoint):
... | [
"def",
"permission_check",
"(",
"apikey",
",",
"endpoint",
")",
":",
"try",
":",
"ak",
"=",
"APIKeys",
".",
"objects",
".",
"get",
"(",
"apikey",
"=",
"apikey",
")",
"apitree",
"=",
"cPickle",
".",
"loads",
"(",
"ak",
".",
"apitree",
".",
"encode",
"... | 37.75 | 14.75 |
def tojson(o):
"""
recursive implementation
"""
try:
return json.encode(o)
except json.EncodeError:
pass
try:
return o.tojson()
except AttributeError as e:
pass
t = type(o)
if isinstance(o, list):
return '[%s]' % ', '.join([tojson(e) for e in ... | [
"def",
"tojson",
"(",
"o",
")",
":",
"try",
":",
"return",
"json",
".",
"encode",
"(",
"o",
")",
"except",
"json",
".",
"EncodeError",
":",
"pass",
"try",
":",
"return",
"o",
".",
"tojson",
"(",
")",
"except",
"AttributeError",
"as",
"e",
":",
"pas... | 26.653846 | 16.807692 |
def _print_message(self, prefix, message, verbose=True):
'Prints a message and takes care of all sorts of nasty code'
# Load up the standard output.
output = ['\n', prefix, message['message']]
# We have some extra stuff for verbose mode.
if verbose:
verbose_output =... | [
"def",
"_print_message",
"(",
"self",
",",
"prefix",
",",
"message",
",",
"verbose",
"=",
"True",
")",
":",
"# Load up the standard output.",
"output",
"=",
"[",
"'\\n'",
",",
"prefix",
",",
"message",
"[",
"'message'",
"]",
"]",
"# We have some extra stuff for ... | 40.354839 | 18.806452 |
def ean8(self, data, **kwargs):
"""Render given ``data`` as **JAN-8/EAN-8** barcode symbology."""
if not re.match(r'\d{8}', data):
raise ValueError('JAN-8/EAN-8 symbology requires 8 digits of data; '
'got {:d} digits: {!r}'.format(len(data), data))
barcode.validat... | [
"def",
"ean8",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"re",
".",
"match",
"(",
"r'\\d{8}'",
",",
"data",
")",
":",
"raise",
"ValueError",
"(",
"'JAN-8/EAN-8 symbology requires 8 digits of data; '",
"'got {:d} digits: {!r}'",
... | 55 | 12.857143 |
def super_parent(self, mol, skip_standardize=False):
"""Return the super parent of a given molecule.
THe super parent is fragment, charge, isotope, stereochemistry and tautomer insensitive. From the input
molecule, the largest fragment is taken. This is uncharged and then isotope and stereochem... | [
"def",
"super_parent",
"(",
"self",
",",
"mol",
",",
"skip_standardize",
"=",
"False",
")",
":",
"if",
"not",
"skip_standardize",
":",
"mol",
"=",
"self",
".",
"standardize",
"(",
"mol",
")",
"# We don't need to get fragment parent, because the charge parent is the la... | 51.636364 | 23.181818 |
def relStdDev(self, limit=None):
"""return the relative standard deviation optionally limited to the last limit values"""
moments = self.meanAndStdDev(limit)
if moments is None:
return None
return moments[1] / moments[0] | [
"def",
"relStdDev",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"moments",
"=",
"self",
".",
"meanAndStdDev",
"(",
"limit",
")",
"if",
"moments",
"is",
"None",
":",
"return",
"None",
"return",
"moments",
"[",
"1",
"]",
"/",
"moments",
"[",
"0",... | 43.166667 | 7.166667 |
def generate_brome_config():
"""Generate a brome config with default value
Returns:
config (dict)
"""
config = {}
for key in iter(default_config):
for inner_key, value in iter(default_config[key].items()):
if key not in config:
config[key] = {}
... | [
"def",
"generate_brome_config",
"(",
")",
":",
"config",
"=",
"{",
"}",
"for",
"key",
"in",
"iter",
"(",
"default_config",
")",
":",
"for",
"inner_key",
",",
"value",
"in",
"iter",
"(",
"default_config",
"[",
"key",
"]",
".",
"items",
"(",
")",
")",
... | 23.0625 | 20.3125 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.