text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def create_new_scheme(self):
"""Creates a new color scheme with a custom name."""
names = self.get_option('names')
custom_names = self.get_option('custom_names', [])
# Get the available number this new color scheme
counter = len(custom_names) - 1
custom_index = [int(n.sp... | [
"def",
"create_new_scheme",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"get_option",
"(",
"'names'",
")",
"custom_names",
"=",
"self",
".",
"get_option",
"(",
"'custom_names'",
",",
"[",
"]",
")",
"# Get the available number this new color scheme",
"counter... | 43.022727 | 0.001033 |
def Many2ManyThroughModel(field):
'''Create a Many2Many through model with two foreign key fields and a
CompositeFieldId depending on the two foreign keys.'''
from stdnet.odm import ModelType, StdModel, ForeignKey, CompositeIdField
name_model = field.model._meta.name
name_relmodel = field.relmodel.... | [
"def",
"Many2ManyThroughModel",
"(",
"field",
")",
":",
"from",
"stdnet",
".",
"odm",
"import",
"ModelType",
",",
"StdModel",
",",
"ForeignKey",
",",
"CompositeIdField",
"name_model",
"=",
"field",
".",
"model",
".",
"_meta",
".",
"name",
"name_relmodel",
"=",... | 42.578947 | 0.000604 |
def Overlay_setShowDebugBorders(self, show):
"""
Function path: Overlay.setShowDebugBorders
Domain: Overlay
Method name: setShowDebugBorders
Parameters:
Required arguments:
'show' (type: boolean) -> True for showing debug borders
No return value.
Description: Requests that backend show... | [
"def",
"Overlay_setShowDebugBorders",
"(",
"self",
",",
"show",
")",
":",
"assert",
"isinstance",
"(",
"show",
",",
"(",
"bool",
",",
")",
")",
",",
"\"Argument 'show' must be of type '['bool']'. Received type: '%s'\"",
"%",
"type",
"(",
"show",
")",
"subdom_funcs",... | 30.210526 | 0.047297 |
def build_specfile_filesection(spec, files):
""" builds the %file section of the specfile
"""
str = '%files\n'
if 'X_RPM_DEFATTR' not in spec:
spec['X_RPM_DEFATTR'] = '(-,root,root)'
str = str + '%%defattr %s\n' % spec['X_RPM_DEFATTR']
supported_tags = {
'PACKAGING_CONFIG' ... | [
"def",
"build_specfile_filesection",
"(",
"spec",
",",
"files",
")",
":",
"str",
"=",
"'%files\\n'",
"if",
"'X_RPM_DEFATTR'",
"not",
"in",
"spec",
":",
"spec",
"[",
"'X_RPM_DEFATTR'",
"]",
"=",
"'(-,root,root)'",
"str",
"=",
"str",
"+",
"'%%defattr %s\\n'",
"%... | 31.575 | 0.010753 |
def _rgb_triangle(ax, r_label, g_label, b_label, loc):
"""
Draw an RGB triangle legend on the desired axis
"""
if not loc in range(1, 11):
loc = 2
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
inset_ax = inset_axes(ax, width=1, height=1, loc=lo... | [
"def",
"_rgb_triangle",
"(",
"ax",
",",
"r_label",
",",
"g_label",
",",
"b_label",
",",
"loc",
")",
":",
"if",
"not",
"loc",
"in",
"range",
"(",
"1",
",",
"11",
")",
":",
"loc",
"=",
"2",
"from",
"mpl_toolkits",
".",
"axes_grid1",
".",
"inset_locator... | 43.042553 | 0.00145 |
def exists_alias(self, using=None, **kwargs):
"""
Return a boolean indicating whether given alias exists for this index.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.exists_alias`` unchanged.
"""
return self._get_connection(using).indices.ex... | [
"def",
"exists_alias",
"(",
"self",
",",
"using",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_get_connection",
"(",
"using",
")",
".",
"indices",
".",
"exists_alias",
"(",
"index",
"=",
"self",
".",
"_name",
",",
"*",
"*"... | 43.875 | 0.00838 |
def point_on_line(ab, c):
'''
point_on_line((a,b), c) yields True if point x is on line (a,b) and False otherwise.
'''
(a,b) = ab
abc = [np.asarray(u) for u in (a,b,c)]
if any(len(u.shape) == 2 for u in abc): (a,b,c) = [np.reshape(u,(len(u),-1)) for u in abc]
else: ... | [
"def",
"point_on_line",
"(",
"ab",
",",
"c",
")",
":",
"(",
"a",
",",
"b",
")",
"=",
"ab",
"abc",
"=",
"[",
"np",
".",
"asarray",
"(",
"u",
")",
"for",
"u",
"in",
"(",
"a",
",",
"b",
",",
"c",
")",
"]",
"if",
"any",
"(",
"len",
"(",
"u"... | 43.666667 | 0.020927 |
def maximumBelow(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by a constant n.
Draws only the metrics with a maximum value below n.
Example::
&target=maximumBelow(system.interface.eth*.packetsSent,1000)
This would only display interfaces which alw... | [
"def",
"maximumBelow",
"(",
"requestContext",
",",
"seriesList",
",",
"n",
")",
":",
"results",
"=",
"[",
"]",
"for",
"series",
"in",
"seriesList",
":",
"val",
"=",
"safeMax",
"(",
"series",
")",
"if",
"val",
"is",
"None",
"or",
"val",
"<=",
"n",
":"... | 28.777778 | 0.001869 |
def filtered(self, step_names):
"""Returns a "filtered" version of this graph."""
return Graph(steps=self.steps, dag=self.dag.filter(step_names)) | [
"def",
"filtered",
"(",
"self",
",",
"step_names",
")",
":",
"return",
"Graph",
"(",
"steps",
"=",
"self",
".",
"steps",
",",
"dag",
"=",
"self",
".",
"dag",
".",
"filter",
"(",
"step_names",
")",
")"
] | 53 | 0.012422 |
def _dphiTilde(self, r, N, L):
"""
NAME:
_dphiTilde
PURPOSE:
Evaluate the derivative of phiTilde with respect to r
INPUT:
r - spherical radius
N - size of the N dimension
L - size of the L dimension
OUTPUT:
the der... | [
"def",
"_dphiTilde",
"(",
"self",
",",
"r",
",",
"N",
",",
"L",
")",
":",
"a",
"=",
"self",
".",
"_a",
"l",
"=",
"nu",
".",
"arange",
"(",
"0",
",",
"L",
",",
"dtype",
"=",
"float",
")",
"[",
"nu",
".",
"newaxis",
",",
":",
"]",
"n",
"=",... | 35.818182 | 0.017305 |
def load_annotations(self, aname, sep=','):
"""Loads cell annotations.
Loads the cell annoations specified by the 'aname' path.
Parameters
----------
aname - string
The path to the annotations file. First column should be cell IDs
and second column shoul... | [
"def",
"load_annotations",
"(",
"self",
",",
"aname",
",",
"sep",
"=",
"','",
")",
":",
"ann",
"=",
"pd",
".",
"read_csv",
"(",
"aname",
")",
"cell_names",
"=",
"np",
".",
"array",
"(",
"list",
"(",
"self",
".",
"adata",
".",
"obs_names",
")",
")",... | 38.3 | 0.001698 |
def _loci_to_arr(loci, taxdict, mindict):
"""
return a frequency array from a loci file for all loci with taxa from
taxdict and min coverage from mindict.
"""
## make the array (4 or 5) and a mask array to remove loci without cov
nloci = len(loci)
maxlen = np.max(np.array([len(locus.split... | [
"def",
"_loci_to_arr",
"(",
"loci",
",",
"taxdict",
",",
"mindict",
")",
":",
"## make the array (4 or 5) and a mask array to remove loci without cov",
"nloci",
"=",
"len",
"(",
"loci",
")",
"maxlen",
"=",
"np",
".",
"max",
"(",
"np",
".",
"array",
"(",
"[",
"... | 36.957983 | 0.009079 |
def list_uplink_dvportgroup(dvs, service_instance=None):
'''
Returns the uplink portgroup of a distributed virtual switch.
dvs
Name of the DVS containing the portgroup.
service_instance
Service instance (vim.ServiceInstance) of the vCenter.
Default is None.
.. code-block::... | [
"def",
"list_uplink_dvportgroup",
"(",
"dvs",
",",
"service_instance",
"=",
"None",
")",
":",
"proxy_type",
"=",
"get_proxy_type",
"(",
")",
"if",
"proxy_type",
"==",
"'esxdatacenter'",
":",
"datacenter",
"=",
"__salt__",
"[",
"'esxdatacenter.get_details'",
"]",
"... | 39.214286 | 0.000889 |
def WriteApprovalRequest(self, approval_request):
"""Writes an approval request object."""
approvals = self.approvals_by_username.setdefault(
approval_request.requestor_username, {})
approval_id = str(os.urandom(16).encode("hex"))
cloned_request = approval_request.Copy()
cloned_request.time... | [
"def",
"WriteApprovalRequest",
"(",
"self",
",",
"approval_request",
")",
":",
"approvals",
"=",
"self",
".",
"approvals_by_username",
".",
"setdefault",
"(",
"approval_request",
".",
"requestor_username",
",",
"{",
"}",
")",
"approval_id",
"=",
"str",
"(",
"os"... | 38 | 0.002141 |
def delete_record(name, zone, record_type, identifier=None, all_records=False,
region=None, key=None, keyid=None, profile=None,
wait_for_sync=True, split_dns=False, private_zone=False,
retry_on_rate_limit=None, rate_limit_retries=None,
retry_on_err... | [
"def",
"delete_record",
"(",
"name",
",",
"zone",
",",
"record_type",
",",
"identifier",
"=",
"None",
",",
"all_records",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
... | 38.135593 | 0.000867 |
def literalize_string(content, is_unicode=False):
r'''Literalize a string content.
Examples:
>>> print literalize_string('str')
'str'
>>> print literalize_string('\'str\'')
"'str'"
>>> print literalize_string('\"\'str\'\"')
'"\'str\'"'
'''
quote_mark = "'"
if "'" in conten... | [
"def",
"literalize_string",
"(",
"content",
",",
"is_unicode",
"=",
"False",
")",
":",
"quote_mark",
"=",
"\"'\"",
"if",
"\"'\"",
"in",
"content",
":",
"quote_mark",
"=",
"'\"'",
"if",
"'\"'",
"in",
"content",
":",
"quote_mark",
"=",
"\"'\"",
"content",
"=... | 22.625 | 0.001767 |
def _check_euk_contamination(self, hmm_hit_tables):
'''
check_euk_contamination - Check output HMM tables hits reads that hit
the 18S HMM with a higher bit score.
Parameters
----------
hmm_hit_tables : array
Array of paths to the out... | [
"def",
"_check_euk_contamination",
"(",
"self",
",",
"hmm_hit_tables",
")",
":",
"euk_hit_table",
"=",
"HMMreader",
"(",
"hmm_hit_tables",
".",
"pop",
"(",
"-",
"1",
")",
")",
"other_hit_tables",
"=",
"[",
"HMMreader",
"(",
"x",
")",
"for",
"x",
"in",
"hmm... | 36.291667 | 0.002236 |
def all_errors(self, joiner="; "):
"""Returns a string representation of all errors recorded for the instance."""
parts = []
for pname, errs in self.errors.items():
for err in errs:
parts.append("{0}: {1}".format(pname, err))
return joiner.join(parts) | [
"def",
"all_errors",
"(",
"self",
",",
"joiner",
"=",
"\"; \"",
")",
":",
"parts",
"=",
"[",
"]",
"for",
"pname",
",",
"errs",
"in",
"self",
".",
"errors",
".",
"items",
"(",
")",
":",
"for",
"err",
"in",
"errs",
":",
"parts",
".",
"append",
"(",... | 39.285714 | 0.010676 |
def generate_key(url, page_number):
"""
>>> url_a = 'http://localhost:5009/search?keywords=a'
>>> generate_key(url_a, 10)
'http://localhost:5009/search?keywords=a&page=10'
>>> url_b = 'http://localhost:5009/search?keywords=b&page=1'
>>> generate_key(url_b, 10)
'http://localhost:5009/search?k... | [
"def",
"generate_key",
"(",
"url",
",",
"page_number",
")",
":",
"index",
"=",
"url",
".",
"rfind",
"(",
"'page'",
")",
"if",
"index",
"!=",
"-",
"1",
":",
"result",
"=",
"url",
"[",
"0",
":",
"index",
"]",
"result",
"+=",
"'page=%s'",
"%",
"page_n... | 32 | 0.001786 |
def parse(self, msg, name):
"""Parses the message.
We check that the message is properly formatted.
:param msg: a json-encoded value containing a JWS or JWE+JWS token
:raises InvalidMessage: if the message cannot be parsed or validated
:returns: A verified payload
"""... | [
"def",
"parse",
"(",
"self",
",",
"msg",
",",
"name",
")",
":",
"try",
":",
"jtok",
"=",
"JWT",
"(",
"jwt",
"=",
"msg",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"InvalidMessage",
"(",
"'Failed to parse message: %s'",
"%",
"str",
"(",
"e",
... | 36.196078 | 0.001055 |
def messageRemote(self, cmdObj, consequence=None, **args):
"""
Send a message to the peer identified by the target, via the
given L{Command} object and arguments.
@param cmdObj: a L{twisted.protocols.amp.Command}, whose serialized
form will be the message.
@param conseq... | [
"def",
"messageRemote",
"(",
"self",
",",
"cmdObj",
",",
"consequence",
"=",
"None",
",",
"*",
"*",
"args",
")",
":",
"messageBox",
"=",
"cmdObj",
".",
"makeArguments",
"(",
"args",
",",
"self",
")",
"messageBox",
"[",
"COMMAND",
"]",
"=",
"cmdObj",
".... | 39.173913 | 0.002167 |
def binglookup(w1i, w2i):
"""
Bingham statistics lookup table.
"""
K = {'0.06': {'0.02': ['-25.58', '-8.996'], '0.06': ['-9.043', '-9.043'], '0.04': ['-13.14', '-9.019']}, '0.22': {'0.08': ['-6.944', '-2.644'], '0.02': ['-25.63', '-2.712'], '0.20': ['-2.649', '-2.354'], '0.06': ['-9.027', '-2.673'], '0.... | [
"def",
"binglookup",
"(",
"w1i",
",",
"w2i",
")",
":",
"K",
"=",
"{",
"'0.06'",
":",
"{",
"'0.02'",
":",
"[",
"'-25.58'",
",",
"'-8.996'",
"]",
",",
"'0.06'",
":",
"[",
"'-9.043'",
",",
"'-9.043'",
"]",
",",
"'0.04'",
":",
"[",
"'-13.14'",
",",
"... | 465.090909 | 0.000293 |
def _as_array_or_item(data):
"""Return the given values as a numpy array, or as an individual item if
it's a 0d datetime64 or timedelta64 array.
Importantly, this function does not copy data if it is already an ndarray -
otherwise, it will not be possible to update Variable values in place.
This f... | [
"def",
"_as_array_or_item",
"(",
"data",
")",
":",
"data",
"=",
"np",
".",
"asarray",
"(",
"data",
")",
"if",
"data",
".",
"ndim",
"==",
"0",
":",
"if",
"data",
".",
"dtype",
".",
"kind",
"==",
"'M'",
":",
"data",
"=",
"np",
".",
"datetime64",
"(... | 38.142857 | 0.001218 |
def create_random(magf, magf_params, errf, errf_params,
timef=np.linspace, timef_params=None, size=DEFAULT_SIZE,
id=None, ds_name=DS_NAME, description=DESCRIPTION,
bands=BANDS, metadata=METADATA):
"""Generate a data with any given random function.
Parameter... | [
"def",
"create_random",
"(",
"magf",
",",
"magf_params",
",",
"errf",
",",
"errf_params",
",",
"timef",
"=",
"np",
".",
"linspace",
",",
"timef_params",
"=",
"None",
",",
"size",
"=",
"DEFAULT_SIZE",
",",
"id",
"=",
"None",
",",
"ds_name",
"=",
"DS_NAME"... | 31.424658 | 0.000423 |
def stop(name, vmid=None, call=None):
'''
Stop a node ("pulling the plug").
CLI Example:
.. code-block:: bash
salt-cloud -a stop mymachine
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
if no... | [
"def",
"stop",
"(",
"name",
",",
"vmid",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The stop action must be called with -a or --action.'",
")",
"if",
"not",
"set_vm_status",
"(",
... | 26.590909 | 0.00165 |
def touch(path, times=None):
"""Equivalent of unix `touch path`.
:API: public
:path: The file to touch.
:times Either a tuple of (atime, mtime) or else a single time to use for both. If not
specified both atime and mtime are updated to the current time.
"""
if times:
if len(times) > ... | [
"def",
"touch",
"(",
"path",
",",
"times",
"=",
"None",
")",
":",
"if",
"times",
":",
"if",
"len",
"(",
"times",
")",
">",
"2",
":",
"raise",
"ValueError",
"(",
"'times must either be a tuple of (atime, mtime) or else a single time value '",
"'to use for both.'",
... | 29.368421 | 0.013889 |
def option(*param_decls, **attrs):
"""Attach an option to the command.
All positional arguments are passed as parameter declarations
to :class:`Option`, all keyword arguments are forwarded unchanged.
This is equivalent to creating an :class:`Option` instance manually and
attaching it to the :attr:`... | [
"def",
"option",
"(",
"*",
"param_decls",
",",
"*",
"*",
"attrs",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"_param_memo",
"(",
"f",
",",
"GandiOption",
"(",
"param_decls",
",",
"*",
"*",
"attrs",
")",
")",
"return",
"f",
"return",
"decorator... | 38 | 0.002141 |
def d2AIbr_dV2(dIbr_dVa, dIbr_dVm, Ibr, Ybr, V, lam):
""" Computes 2nd derivatives of |complex current|**2 w.r.t. V.
"""
diaglam = spdiag(lam)
diagIbr_conj = spdiag(conj(Ibr))
Iaa, Iav, Iva, Ivv = d2Ibr_dV2(Ybr, V, diagIbr_conj * lam)
Haa = 2 * ( Iaa + dIbr_dVa.T * diaglam * conj(dIbr_dVa) ).r... | [
"def",
"d2AIbr_dV2",
"(",
"dIbr_dVa",
",",
"dIbr_dVm",
",",
"Ibr",
",",
"Ybr",
",",
"V",
",",
"lam",
")",
":",
"diaglam",
"=",
"spdiag",
"(",
"lam",
")",
"diagIbr_conj",
"=",
"spdiag",
"(",
"conj",
"(",
"Ibr",
")",
")",
"Iaa",
",",
"Iav",
",",
"I... | 39.285714 | 0.015986 |
def handle_args_and_set_context(args):
"""
Args:
args: the command line args, probably passed from main() as sys.argv[1:]
Returns:
a populated EFPWContext object
Raises:
RuntimeError: if repo or branch isn't as spec'd in ef_config.EF_REPO and ef_config.EF_REPO_BRANCH
ValueError: if a par... | [
"def",
"handle_args_and_set_context",
"(",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"service\"",
",",
"help",
"=",
"\"name of service password is being generated for\"",
")",
"parser",
".",
"... | 47.944444 | 0.017604 |
def build_trees(fclade_counts, namedict):
"""
A subfunc of consensus_tree(). Build an unrooted consensus tree
from filtered clade counts.
"""
## storage
nodes = {}
idxarr = np.arange(len(fclade_counts[0][0]))
queue = []
## create dict of clade counts and set keys
countdict =... | [
"def",
"build_trees",
"(",
"fclade_counts",
",",
"namedict",
")",
":",
"## storage",
"nodes",
"=",
"{",
"}",
"idxarr",
"=",
"np",
".",
"arange",
"(",
"len",
"(",
"fclade_counts",
"[",
"0",
"]",
"[",
"0",
"]",
")",
")",
"queue",
"=",
"[",
"]",
"## c... | 32.714286 | 0.008008 |
def fix_orientation(self, tour):
"""
Test each scaffold if flipping will increass longest monotonic chain
length.
"""
orientations = dict(tour) # old configuration here
scaffold_oo = defaultdict(list)
scaffolds, oos = zip(*tour)
for mlg in self.linkage_gr... | [
"def",
"fix_orientation",
"(",
"self",
",",
"tour",
")",
":",
"orientations",
"=",
"dict",
"(",
"tour",
")",
"# old configuration here",
"scaffold_oo",
"=",
"defaultdict",
"(",
"list",
")",
"scaffolds",
",",
"oos",
"=",
"zip",
"(",
"*",
"tour",
")",
"for",... | 37 | 0.001463 |
def toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None,
mode=None, channel_axis=None):
"""Takes a numpy array and returns a PIL image.
The mode of the PIL image depends on the array shape and the `pal` and
`mode` keywords.
For 2-D arrays, if `pal` is a valid (N,3) byte-array givi... | [
"def",
"toimage",
"(",
"arr",
",",
"high",
"=",
"255",
",",
"low",
"=",
"0",
",",
"cmin",
"=",
"None",
",",
"cmax",
"=",
"None",
",",
"pal",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"channel_axis",
"=",
"None",
")",
":",
"data",
"=",
"asarra... | 36.848214 | 0.000236 |
async def send_ssh_job_info(self, job_id: BackendJobId, host: str, port: int, key: str):
"""
Send info about the SSH debug connection to the backend/client. Must be called *at most once* for each job.
:exception JobNotRunningException: is raised when the job is not running anymore (send_job_resu... | [
"async",
"def",
"send_ssh_job_info",
"(",
"self",
",",
"job_id",
":",
"BackendJobId",
",",
"host",
":",
"str",
",",
"port",
":",
"int",
",",
"key",
":",
"str",
")",
":",
"if",
"job_id",
"not",
"in",
"self",
".",
"__running_job",
":",
"raise",
"JobNotRu... | 64.583333 | 0.008906 |
def ndimage_to_list(image):
"""
Split a n dimensional ANTsImage into a list
of n-1 dimensional ANTsImages
Arguments
---------
image : ANTsImage
n-dimensional image to split
Returns
-------
list of ANTsImage types
Example
-------
>>> import ants
>>> image = ... | [
"def",
"ndimage_to_list",
"(",
"image",
")",
":",
"inpixeltype",
"=",
"image",
".",
"pixeltype",
"dimension",
"=",
"image",
".",
"dimension",
"components",
"=",
"1",
"imageShape",
"=",
"image",
".",
"shape",
"nSections",
"=",
"imageShape",
"[",
"dimension",
... | 31.446809 | 0.021654 |
def coverage_lineplot (self):
""" Make HTML for coverage line plots """
# Add line graph to section
data = list()
data_labels = list()
if len(self.rna_seqc_norm_high_cov) > 0:
data.append(self.rna_seqc_norm_high_cov)
data_labels.append({'name': 'High Expre... | [
"def",
"coverage_lineplot",
"(",
"self",
")",
":",
"# Add line graph to section",
"data",
"=",
"list",
"(",
")",
"data_labels",
"=",
"list",
"(",
")",
"if",
"len",
"(",
"self",
".",
"rna_seqc_norm_high_cov",
")",
">",
"0",
":",
"data",
".",
"append",
"(",
... | 43.387097 | 0.009455 |
def example():
"""
Some example usage of different twilio resources.
"""
client = Client(ACCOUNT_SID, AUTH_TOKEN)
# Get all messages
all_messages = client.messages.list()
print('There are {} messages in your account.'.format(len(all_messages)))
# Get only last 10 messages...
some_m... | [
"def",
"example",
"(",
")",
":",
"client",
"=",
"Client",
"(",
"ACCOUNT_SID",
",",
"AUTH_TOKEN",
")",
"# Get all messages",
"all_messages",
"=",
"client",
".",
"messages",
".",
"list",
"(",
")",
"print",
"(",
"'There are {} messages in your account.'",
".",
"for... | 32.84375 | 0.001848 |
def _dedent(text):
"""Remove common indentation from each line in a text block.
When text block is a single line, return text block. Otherwise
determine common indentation from last line, strip common
indentation from each line, and return text block consisting of
inner lines (d... | [
"def",
"_dedent",
"(",
"text",
")",
":",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"if",
"len",
"(",
"lines",
")",
"==",
"1",
":",
"indent",
"=",
"0",
"elif",
"lines",
"[",
"0",
"]",
".",
"strip",
"(",
")",
":",
"raise",
"ValueErro... | 35.189189 | 0.001495 |
def _get_exposure(fname, stop=None):
"""
:param fname:
path of the XML file containing the exposure
:param stop:
node at which to stop parsing (or None)
:returns:
a pair (Exposure instance, list of asset nodes)
"""
[exposure] = nrml.read(fname, stop=stop)
if not expos... | [
"def",
"_get_exposure",
"(",
"fname",
",",
"stop",
"=",
"None",
")",
":",
"[",
"exposure",
"]",
"=",
"nrml",
".",
"read",
"(",
"fname",
",",
"stop",
"=",
"stop",
")",
"if",
"not",
"exposure",
".",
"tag",
".",
"endswith",
"(",
"'exposureModel'",
")",
... | 40.540816 | 0.000246 |
def insert_one(self, validate=True):
"""Insert this document.
The `validate` argument translates to the inverse of the `bypass_document_validation` PyMongo option.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
"""
kw = {}
kw['bypass_docu... | [
"def",
"insert_one",
"(",
"self",
",",
"validate",
"=",
"True",
")",
":",
"kw",
"=",
"{",
"}",
"kw",
"[",
"'bypass_document_validation'",
"]",
"=",
"not",
"validate",
"collection",
"=",
"self",
".",
"get_collection",
"(",
"kw",
".",
"pop",
"(",
"'source'... | 34.230769 | 0.041575 |
def to_sql(frame, name, con, schema=None, if_exists='fail', index=True,
index_label=None, chunksize=None, dtype=None, method=None):
"""
Write records stored in a DataFrame to a SQL database.
Parameters
----------
frame : DataFrame, Series
name : string
Name of SQL table.
... | [
"def",
"to_sql",
"(",
"frame",
",",
"name",
",",
"con",
",",
"schema",
"=",
"None",
",",
"if_exists",
"=",
"'fail'",
",",
"index",
"=",
"True",
",",
"index_label",
"=",
"None",
",",
"chunksize",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"method",
... | 46.754098 | 0.000343 |
def service_list(service=None, key_name=None, **kwargs):
"""General list function for Google APIs."""
resp_list = []
req = service.list(**kwargs)
while req is not None:
resp = req.execute()
if key_name and key_name in resp:
resp_list.extend(resp[key_name])
else:
... | [
"def",
"service_list",
"(",
"service",
"=",
"None",
",",
"key_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"resp_list",
"=",
"[",
"]",
"req",
"=",
"service",
".",
"list",
"(",
"*",
"*",
"kwargs",
")",
"while",
"req",
"is",
"not",
"None",
... | 33.166667 | 0.001629 |
def create(
meta_schema,
validators=(),
version=None,
default_types=None,
type_checker=None,
id_of=_id_of,
):
"""
Create a new validator class.
Arguments:
meta_schema (collections.Mapping):
the meta schema for the new validator class
validators (collec... | [
"def",
"create",
"(",
"meta_schema",
",",
"validators",
"=",
"(",
")",
",",
"version",
"=",
"None",
",",
"default_types",
"=",
"None",
",",
"type_checker",
"=",
"None",
",",
"id_of",
"=",
"_id_of",
",",
")",
":",
"if",
"default_types",
"is",
"not",
"No... | 32.398104 | 0.000142 |
def format_help(self):
""" Strip out { } redundant subcommand section.
"""
help_msg = super(FocusArgParser, self).format_help()
return re.sub(r'\{.+\}', '', help_msg) | [
"def",
"format_help",
"(",
"self",
")",
":",
"help_msg",
"=",
"super",
"(",
"FocusArgParser",
",",
"self",
")",
".",
"format_help",
"(",
")",
"return",
"re",
".",
"sub",
"(",
"r'\\{.+\\}'",
",",
"''",
",",
"help_msg",
")"
] | 39.6 | 0.009901 |
def roll(self, shift):
"""shift vector
"""
self._saved = LimitedSizeDict(size_limit=2**5)
new_arr = zeros(len(self), dtype=self.dtype)
if shift < 0:
shift = shift - len(self) * (shift // len(self))
if shift == 0:
return
n... | [
"def",
"roll",
"(",
"self",
",",
"shift",
")",
":",
"self",
".",
"_saved",
"=",
"LimitedSizeDict",
"(",
"size_limit",
"=",
"2",
"**",
"5",
")",
"new_arr",
"=",
"zeros",
"(",
"len",
"(",
"self",
")",
",",
"dtype",
"=",
"self",
".",
"dtype",
")",
"... | 28.875 | 0.010482 |
def list(self, roomId=None, personId=None, personEmail=None, max=None,
**request_parameters):
"""List room memberships.
By default, lists memberships for rooms to which the authenticated user
belongs.
Use query parameters to filter the response.
Use `roomId` to li... | [
"def",
"list",
"(",
"self",
",",
"roomId",
"=",
"None",
",",
"personId",
"=",
"None",
",",
"personEmail",
"=",
"None",
",",
"max",
"=",
"None",
",",
"*",
"*",
"request_parameters",
")",
":",
"check_type",
"(",
"roomId",
",",
"basestring",
")",
"check_t... | 40.672131 | 0.001181 |
def _G(self, x, p):
"""
analytic solution of the 2d projected mass integral
integral: 2 * pi * x * kappa * dx
:param x:
:param p:
:return:
"""
prefactor = (p + p ** 3) ** -1 * p
if isinstance(x, np.ndarray):
inds0 = np.where(x * p ==... | [
"def",
"_G",
"(",
"self",
",",
"x",
",",
"p",
")",
":",
"prefactor",
"=",
"(",
"p",
"+",
"p",
"**",
"3",
")",
"**",
"-",
"1",
"*",
"p",
"if",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"inds0",
"=",
"np",
".",
"where",
"... | 40.8 | 0.009574 |
def _map_arg_names(source, mapping):
"""Map one set of keys to another."""
return {cartopy_name: source[cf_name] for cartopy_name, cf_name in mapping
if cf_name in source} | [
"def",
"_map_arg_names",
"(",
"source",
",",
"mapping",
")",
":",
"return",
"{",
"cartopy_name",
":",
"source",
"[",
"cf_name",
"]",
"for",
"cartopy_name",
",",
"cf_name",
"in",
"mapping",
"if",
"cf_name",
"in",
"source",
"}"
] | 50 | 0.014778 |
def move_to(self, start, end):
"""Moves the `Polynucleotide` to lie on the `start` and `end` vector.
Parameters
----------
start : 3D Vector (tuple or list or numpy.array)
The coordinate of the start of the helix primitive.
end : 3D Vector (tuple or list or numpy.arr... | [
"def",
"move_to",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"start",
"=",
"numpy",
".",
"array",
"(",
"start",
")",
"end",
"=",
"numpy",
".",
"array",
"(",
"end",
")",
"if",
"numpy",
".",
"allclose",
"(",
"start",
",",
"end",
")",
":",
"... | 38.36 | 0.002035 |
def parse_argument(string: str) -> Union[str, Tuple[str, str]]:
"""Return a single value for a string understood as a positional
argument or a |tuple| containing a keyword and its value for a
string understood as a keyword argument.
|parse_argument| is intended to be used as a helper function for
f... | [
"def",
"parse_argument",
"(",
"string",
":",
"str",
")",
"->",
"Union",
"[",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
":",
"idx_equal",
"=",
"string",
".",
"find",
"(",
"'='",
")",
"if",
"idx_equal",
"==",
"-",
"1",
":",
"return",
"... | 32.69697 | 0.0009 |
def fac2real(pp_file=None,factors_file="factors.dat",out_file="test.ref",
upper_lim=1.0e+30,lower_lim=-1.0e+30,fill_value=1.0e+30):
"""A python replication of the PEST fac2real utility for creating a
structure grid array from previously calculated kriging factors (weights)
Parameters
-----... | [
"def",
"fac2real",
"(",
"pp_file",
"=",
"None",
",",
"factors_file",
"=",
"\"factors.dat\"",
",",
"out_file",
"=",
"\"test.ref\"",
",",
"upper_lim",
"=",
"1.0e+30",
",",
"lower_lim",
"=",
"-",
"1.0e+30",
",",
"fill_value",
"=",
"1.0e+30",
")",
":",
"if",
"... | 37.863636 | 0.009827 |
def compute_internal(self, sym_name, bucket_kwargs=None, **arg_dict):
"""
View the internal symbols using the forward function.
:param sym_name:
:param bucket_kwargs:
:param input_dict:
:return:
"""
data_shapes = {k: v.shape for k, v in arg_dict.items()}
... | [
"def",
"compute_internal",
"(",
"self",
",",
"sym_name",
",",
"bucket_kwargs",
"=",
"None",
",",
"*",
"*",
"arg_dict",
")",
":",
"data_shapes",
"=",
"{",
"k",
":",
"v",
".",
"shape",
"for",
"k",
",",
"v",
"in",
"arg_dict",
".",
"items",
"(",
")",
"... | 43.515152 | 0.001362 |
def get_source_attributes(source):
"""
Retreives a dictionary of source attributes from the source class
:param source:
Seismic source as instance of :class:
`openquake.hazardlib.source.base.BaseSeismicSource`
:returns:
Dictionary of source attributes
"""
attrs = {"id": ... | [
"def",
"get_source_attributes",
"(",
"source",
")",
":",
"attrs",
"=",
"{",
"\"id\"",
":",
"source",
".",
"source_id",
",",
"\"name\"",
":",
"source",
".",
"name",
",",
"\"tectonicRegion\"",
":",
"source",
".",
"tectonic_region_type",
"}",
"if",
"isinstance",
... | 34 | 0.001362 |
def get_prefix_dir(archive):
"""
Often, all files are in a single directory. If so, they'll all have
the same prefix. Determine any such prefix.
archive is a ZipFile
"""
names = archive.namelist()
shortest_name = sorted(names, key=len)[0]
candidate_prefixes = [
shortest_name[:len... | [
"def",
"get_prefix_dir",
"(",
"archive",
")",
":",
"names",
"=",
"archive",
".",
"namelist",
"(",
")",
"shortest_name",
"=",
"sorted",
"(",
"names",
",",
"key",
"=",
"len",
")",
"[",
"0",
"]",
"candidate_prefixes",
"=",
"[",
"shortest_name",
"[",
":",
... | 31.75 | 0.001912 |
def replace_cluster_custom_object_status(self, group, version, plural, name, body, **kwargs): # noqa: E501
"""replace_cluster_custom_object_status # noqa: E501
replace status of the cluster scoped specified custom object # noqa: E501
This method makes a synchronous HTTP request by default. T... | [
"def",
"replace_cluster_custom_object_status",
"(",
"self",
",",
"group",
",",
"version",
",",
"plural",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
... | 57.76 | 0.001362 |
def main():
"""Provide the entry point in the the modutils command."""
mod_choices = ('banned', 'contributor', 'moderator')
mod_choices_dsp = ', '.join(['`{}`'.format(x) for x in mod_choices])
msg = {
'add': ('Add users to one of the following categories: {}'
.format(mod_choices_... | [
"def",
"main",
"(",
")",
":",
"mod_choices",
"=",
"(",
"'banned'",
",",
"'contributor'",
",",
"'moderator'",
")",
"mod_choices_dsp",
"=",
"', '",
".",
"join",
"(",
"[",
"'`{}`'",
".",
"format",
"(",
"x",
")",
"for",
"x",
"in",
"mod_choices",
"]",
")",
... | 51.141304 | 0.000209 |
def setVisible(self, state):
"""
Sets whether or not this particular layer is visible. Depending on \
if the inheritVisibility property is set for this layer, it may not \
actually affect the visible state based on its inheritance. If you \
want to force this layer to be visibl... | [
"def",
"setVisible",
"(",
"self",
",",
"state",
")",
":",
"# store the current state",
"currvis",
"=",
"self",
".",
"isVisible",
"(",
")",
"# update the local property",
"self",
".",
"_visible",
"=",
"state",
"# check the new state",
"newvis",
"=",
"self",
".",
... | 31.222222 | 0.009206 |
def arr_base10toN(anum10, aradix, *args):
"""
ARGS
anum10 in number in base 10
aradix in convert <anum10> to number in base
+ <aradix>
OPTIONAL
forcelength in if nonzero, indicates the length
... | [
"def",
"arr_base10toN",
"(",
"anum10",
",",
"aradix",
",",
"*",
"args",
")",
":",
"new_num_arr",
"=",
"array",
"(",
"(",
")",
")",
"current",
"=",
"anum10",
"while",
"current",
"!=",
"0",
":",
"remainder",
"=",
"current",
"%",
"aradix",
"new_num_arr",
... | 31.6 | 0.002047 |
def defrag(plist):
"""defrag(plist) -> ([not fragmented], [defragmented],
[ [bad fragments], [bad fragments], ... ])"""
frags = defaultdict(PacketList)
nofrag = PacketList()
for p in plist:
ip = p[IP]
if IP not in p:
nofrag.append(p)
continue
... | [
"def",
"defrag",
"(",
"plist",
")",
":",
"frags",
"=",
"defaultdict",
"(",
"PacketList",
")",
"nofrag",
"=",
"PacketList",
"(",
")",
"for",
"p",
"in",
"plist",
":",
"ip",
"=",
"p",
"[",
"IP",
"]",
"if",
"IP",
"not",
"in",
"p",
":",
"nofrag",
".",... | 34.232143 | 0.001521 |
def new_text_block(self, **kwargs):
"""Create a new text block."""
proto = {'content': '', 'type': self.markdown}
proto.update(**kwargs)
return proto | [
"def",
"new_text_block",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"proto",
"=",
"{",
"'content'",
":",
"''",
",",
"'type'",
":",
"self",
".",
"markdown",
"}",
"proto",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"return",
"proto"
] | 35.4 | 0.01105 |
def show(self, commit):
"""Display one commit line.
The output will be:
<uuid> <#lines> <author> <short-commit-date>
If verbose flag set, the output will be:
<uuid> <#lines> <author+email> <long-date> <committer+email>
"""
author = commit.author
... | [
"def",
"show",
"(",
"self",
",",
"commit",
")",
":",
"author",
"=",
"commit",
".",
"author",
"author_width",
"=",
"25",
"committer",
"=",
"''",
"commit_date",
"=",
"date_to_str",
"(",
"commit",
".",
"committer_time",
",",
"commit",
".",
"committer_tz",
","... | 38.285714 | 0.002427 |
def _to_pil_rgb_image(image):
"""Returns an PIL Image converted to the RGB color space. If the image has
an alpha channel (transparency), it will be overlaid on a black background.
:param image: the PIL image to convert
:returns: The input image if it was already in RGB mode, or a new RGB image
... | [
"def",
"_to_pil_rgb_image",
"(",
"image",
")",
":",
"if",
"image",
".",
"mode",
"==",
"\"RGB\"",
":",
"return",
"image",
"from",
"PIL",
"import",
"Image",
"image",
".",
"load",
"(",
")",
"rgb_image",
"=",
"Image",
".",
"new",
"(",
"\"RGB\"",
",",
"imag... | 27.307692 | 0.001361 |
def PostUnregistration(method):
# pylint: disable=C0103
"""
The service post-unregistration callback decorator is called after a service
of the component has been unregistered from the framework.
The decorated method must accept the
:class:`~pelix.framework.ServiceReference` of the registered
... | [
"def",
"PostUnregistration",
"(",
"method",
")",
":",
"# pylint: disable=C0103",
"if",
"not",
"isinstance",
"(",
"method",
",",
"types",
".",
"FunctionType",
")",
":",
"raise",
"TypeError",
"(",
"\"@PostUnregistration can only be applied on functions\"",
")",
"# Tests t... | 32.903226 | 0.001905 |
def create_html(self, fname, title="ClassTracker Statistics"):
"""
Create HTML page `fname` and additional files in a directory derived
from `fname`.
"""
# Create a folder to store the charts and additional HTML files.
self.basedir = os.path.dirname(os.path.abspath(fname)... | [
"def",
"create_html",
"(",
"self",
",",
"fname",
",",
"title",
"=",
"\"ClassTracker Statistics\"",
")",
":",
"# Create a folder to store the charts and additional HTML files.",
"self",
".",
"basedir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
... | 43.552632 | 0.001773 |
def reset(self):
"""Reset the state of this updater for a new optimisation problem."""
self.__init__(self.alpha, self.beta1, self.beta2, self.epsilon) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"__init__",
"(",
"self",
".",
"alpha",
",",
"self",
".",
"beta1",
",",
"self",
".",
"beta2",
",",
"self",
".",
"epsilon",
")"
] | 54.666667 | 0.012048 |
def update_mutation_inputs(service):
"""
Args:
service : The service being updated by the mutation
Returns:
(list) : a list of all of the fields availible for the service. Pk
is a required field in order to filter the results
"""
# grab the default lis... | [
"def",
"update_mutation_inputs",
"(",
"service",
")",
":",
"# grab the default list of field summaries",
"inputs",
"=",
"_service_mutation_summaries",
"(",
"service",
")",
"# visit each field",
"for",
"field",
"in",
"inputs",
":",
"# if we're looking at the id field",
"if",
... | 30.041667 | 0.001344 |
def _generate_overview_note(pass_count, only_warning_count, error_count, total_count):
""" Generates and returns the HTML note that provides a summary of validation status. """
note_html = ['<div class="progress">']
pbars = [
[ float(error_count), 'danger', 'had errors' ],
[ float(only_warn... | [
"def",
"_generate_overview_note",
"(",
"pass_count",
",",
"only_warning_count",
",",
"error_count",
",",
"total_count",
")",
":",
"note_html",
"=",
"[",
"'<div class=\"progress\">'",
"]",
"pbars",
"=",
"[",
"[",
"float",
"(",
"error_count",
")",
",",
"'danger'",
... | 40.291667 | 0.021212 |
def visit_loop(self, node, cond=None):
""" Handle incremented variables in loop body.
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse('''
... def foo():
... a = b = c = 2
... while a > 0:
... a -= 1... | [
"def",
"visit_loop",
"(",
"self",
",",
"node",
",",
"cond",
"=",
"None",
")",
":",
"# visit once to gather newly declared vars",
"for",
"stmt",
"in",
"node",
".",
"body",
":",
"self",
".",
"visit",
"(",
"stmt",
")",
"# freeze current state",
"old_range",
"=",
... | 28.238095 | 0.00163 |
def iter_fields(fields):
"""
.. deprecated:: 1.6
Iterate over fields.
The addition of :class:`~urllib3.fields.RequestField` makes this function
obsolete. Instead, use :func:`iter_field_objects`, which returns
:class:`~urllib3.fields.RequestField` objects.
Supports list of (k, v) tuples an... | [
"def",
"iter_fields",
"(",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"dict",
")",
":",
"return",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"fields",
")",
")",
"return",
"(",
"(",
"... | 28.25 | 0.002141 |
def _no_spelling_errors(relative_path, contents, linter_options):
"""No spelling errors in strings, comments or anything of the like."""
block_regexps = linter_options.get("block_regexps", None)
chunks, shadow = spellcheckable_and_shadow_contents(contents,
... | [
"def",
"_no_spelling_errors",
"(",
"relative_path",
",",
"contents",
",",
"linter_options",
")",
":",
"block_regexps",
"=",
"linter_options",
".",
"get",
"(",
"\"block_regexps\"",
",",
"None",
")",
"chunks",
",",
"shadow",
"=",
"spellcheckable_and_shadow_contents",
... | 59.75 | 0.000824 |
def load_theme_from_dict(dict_theme):
"""
Load a theme from a dict.
Expected format:
{
"Question": {
"mark_color": "yellow",
"brackets_color": "normal",
...
},
"List": {
"selection_color": "bold_blue",
"selection_cursor"... | [
"def",
"load_theme_from_dict",
"(",
"dict_theme",
")",
":",
"t",
"=",
"Default",
"(",
")",
"for",
"question_type",
",",
"settings",
"in",
"dict_theme",
".",
"items",
"(",
")",
":",
"if",
"question_type",
"not",
"in",
"vars",
"(",
"t",
")",
":",
"raise",
... | 36.324324 | 0.000725 |
def flux(self, photon_energy, distance=1 * u.kpc, seed=None):
"""Differential flux at a given distance from the source from a single
seed photon field
Parameters
----------
photon_energy : :class:`~astropy.units.Quantity` float or array
Photon energy array.
... | [
"def",
"flux",
"(",
"self",
",",
"photon_energy",
",",
"distance",
"=",
"1",
"*",
"u",
".",
"kpc",
",",
"seed",
"=",
"None",
")",
":",
"model",
"=",
"super",
"(",
"InverseCompton",
",",
"self",
")",
".",
"flux",
"(",
"photon_energy",
",",
"distance",... | 37.730769 | 0.000994 |
def po_to_unicode(po_obj):
"""
Turns a polib :class:`polib.PoFile` or a :class:`polib.PoEntry`
into a :class:`unicode` string.
:param po_obj: Either a :class:`polib.PoFile` or :class:`polib.PoEntry`.
:rtype: :class:`unicode` string.
"""
po_text = po_obj.__str__()
if type(po_text) !... | [
"def",
"po_to_unicode",
"(",
"po_obj",
")",
":",
"po_text",
"=",
"po_obj",
".",
"__str__",
"(",
")",
"if",
"type",
"(",
"po_text",
")",
"!=",
"types",
".",
"UnicodeType",
":",
"po_text",
"=",
"po_text",
".",
"decode",
"(",
"'utf-8'",
")",
"return",
"po... | 30.307692 | 0.012315 |
def CheckLanguage(filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
... | [
"def",
"CheckLanguage",
"(",
"filename",
",",
"clean_lines",
",",
"linenum",
",",
"file_extension",
",",
"include_state",
",",
"nesting_state",
",",
"error",
")",
":",
"# If the line is empty or consists of entirely a comment, no need to",
"# check it.",
"line",
"=",
"cle... | 43.396226 | 0.012326 |
def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 1D attention."""
if num_w_blocks is not None:
if mask_right:
k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)... | [
"def",
"local_1d_halo_exchange",
"(",
"k",
",",
"v",
",",
"num_w_blocks",
",",
"w_dim",
",",
"mask_right",
")",
":",
"if",
"num_w_blocks",
"is",
"not",
"None",
":",
"if",
"mask_right",
":",
"k",
"=",
"mtf",
".",
"left_halo_exchange",
"(",
"k",
",",
"num_... | 40.411765 | 0.018492 |
def extended(self):
"""Determine whether the OAuth token has been extended."""
if self.expires_at:
return self.expires_at - self.issued_at > timedelta(days=30)
else:
return False | [
"def",
"extended",
"(",
"self",
")",
":",
"if",
"self",
".",
"expires_at",
":",
"return",
"self",
".",
"expires_at",
"-",
"self",
".",
"issued_at",
">",
"timedelta",
"(",
"days",
"=",
"30",
")",
"else",
":",
"return",
"False"
] | 36.833333 | 0.00885 |
def viable_dim_config(bytes_available, arrays, template,
dim_ord, nsolvers=1):
"""
Returns the number of timesteps possible, given the registered arrays
and a memory budget defined by bytes_available
Arguments
----------------
bytes_available : int
The memory budget, or availabl... | [
"def",
"viable_dim_config",
"(",
"bytes_available",
",",
"arrays",
",",
"template",
",",
"dim_ord",
",",
"nsolvers",
"=",
"1",
")",
":",
"if",
"not",
"isinstance",
"(",
"dim_ord",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"'dim_ord should be a list'",
... | 37.275 | 0.001307 |
def network_lopf_prepare_solver(network, solver_name="glpk", solver_io=None):
"""
Prepare solver for linear optimal power flow.
Parameters
----------
solver_name : string
Must be a solver name that pyomo recognises and that is
installed, e.g. "glpk", "gurobi"
solver_io : string,... | [
"def",
"network_lopf_prepare_solver",
"(",
"network",
",",
"solver_name",
"=",
"\"glpk\"",
",",
"solver_io",
"=",
"None",
")",
":",
"network",
".",
"opt",
"=",
"SolverFactory",
"(",
"solver_name",
",",
"solver_io",
"=",
"solver_io",
")",
"patch_optsolver_record_me... | 27.5 | 0.001351 |
def _get_engine_filesystem_config(file_types, args, conf_args):
"""Retriever authorization and engine filesystem configuration.
"""
file_types = [x.replace("_container", "") for x in list(file_types)]
out = ""
if "gcp" in file_types:
out += _AUTH_CONFIG_GOOGLE
if "s3" in file_types:
... | [
"def",
"_get_engine_filesystem_config",
"(",
"file_types",
",",
"args",
",",
"conf_args",
")",
":",
"file_types",
"=",
"[",
"x",
".",
"replace",
"(",
"\"_container\"",
",",
"\"\"",
")",
"for",
"x",
"in",
"list",
"(",
"file_types",
")",
"]",
"out",
"=",
"... | 36.153846 | 0.001036 |
def create(self, user, obj, **kwargs):
"""
Create a new follow link between a user and an object
of a registered model type.
"""
follow = Follow(user=user)
follow.target = obj
follow.save()
return follow | [
"def",
"create",
"(",
"self",
",",
"user",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"follow",
"=",
"Follow",
"(",
"user",
"=",
"user",
")",
"follow",
".",
"target",
"=",
"obj",
"follow",
".",
"save",
"(",
")",
"return",
"follow"
] | 26.7 | 0.01087 |
def container_stop(name, timeout=30, force=True, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Stop a container
name :
Name of the container to stop
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide rem... | [
"def",
"container_stop",
"(",
"name",
",",
"timeout",
"=",
"30",
",",
"force",
"=",
"True",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
")",
":",
"container",
"=",
"container_get"... | 26.263158 | 0.000966 |
def text(self):
"""
Content of the response, in unicode.
if Response.encoding is None and chardet module is available, encoding
will be guessed.
"""
if hasattr(self, '_text') and self._text:
return self._text
if not self.content:
return u'... | [
"def",
"text",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_text'",
")",
"and",
"self",
".",
"_text",
":",
"return",
"self",
".",
"_text",
"if",
"not",
"self",
".",
"content",
":",
"return",
"u''",
"if",
"isinstance",
"(",
"self",
"... | 30.793103 | 0.002172 |
def save(self, calc, session):
'''
Saves tilde_obj into the database
NB: this is the PUBLIC method
@returns checksum, error
'''
checksum = calc.get_checksum()
try:
existing_calc = session.query(model.Calculation).filter(model.Calculation.checksum == c... | [
"def",
"save",
"(",
"self",
",",
"calc",
",",
"session",
")",
":",
"checksum",
"=",
"calc",
".",
"get_checksum",
"(",
")",
"try",
":",
"existing_calc",
"=",
"session",
".",
"query",
"(",
"model",
".",
"Calculation",
")",
".",
"filter",
"(",
"model",
... | 54.381944 | 0.0153 |
def get_instance(self, payload):
"""
Build an instance of OriginationUrlInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.trunking.v1.trunk.origination_url.OriginationUrlInstance
:rtype: twilio.rest.trunking.v1.trunk.origination_url.OriginationUr... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"OriginationUrlInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"trunk_sid",
"=",
"self",
".",
"_solution",
"[",
"'trunk_sid'",
"]",
",",
")"
] | 43.5 | 0.011261 |
def findAll(self, tag_name, params=None, fn=None, case_sensitive=False):
"""
Search for elements by their parameters using `Depth-first algorithm
<http://en.wikipedia.org/wiki/Depth-first_search>`_.
Args:
tag_name (str): Name of the tag you are looking for. Set to "" if
... | [
"def",
"findAll",
"(",
"self",
",",
"tag_name",
",",
"params",
"=",
"None",
",",
"fn",
"=",
"None",
",",
"case_sensitive",
"=",
"False",
")",
":",
"output",
"=",
"[",
"]",
"if",
"self",
".",
"isAlmostEqual",
"(",
"tag_name",
",",
"params",
",",
"fn",... | 37.290323 | 0.001686 |
def _write_median_norm(self, norms:[])->None:
"Writes the median norm of the gradients to Tensorboard."
median_norm = statistics.median(norms)
self._add_gradient_scalar('median_norm', scalar_value=median_norm) | [
"def",
"_write_median_norm",
"(",
"self",
",",
"norms",
":",
"[",
"]",
")",
"->",
"None",
":",
"median_norm",
"=",
"statistics",
".",
"median",
"(",
"norms",
")",
"self",
".",
"_add_gradient_scalar",
"(",
"'median_norm'",
",",
"scalar_value",
"=",
"median_no... | 57.5 | 0.017167 |
def clean_core(self, config_file, region=None, profile_name=None):
"""
Clean all Core related provisioned artifacts from both the local file
and the AWS Greengrass service.
:param config_file: config file containing the core to clean
:param region: the region in which the core s... | [
"def",
"clean_core",
"(",
"self",
",",
"config_file",
",",
"region",
"=",
"None",
",",
"profile_name",
"=",
"None",
")",
":",
"config",
"=",
"GroupConfigFile",
"(",
"config_file",
"=",
"config_file",
")",
"if",
"region",
"is",
"None",
":",
"region",
"=",
... | 40.344828 | 0.001669 |
def events(self):
# type: () -> Generator[Event, None, None]
"""
Return a generator that provides any events that have been generated
by protocol activity.
:returns: generator of :class:`Event <wsproto.events.Event>` subclasses
"""
while self._events:
... | [
"def",
"events",
"(",
"self",
")",
":",
"# type: () -> Generator[Event, None, None]",
"while",
"self",
".",
"_events",
":",
"yield",
"self",
".",
"_events",
".",
"popleft",
"(",
")",
"try",
":",
"for",
"frame",
"in",
"self",
".",
"_proto",
".",
"received_fra... | 40.772727 | 0.001633 |
def live(self):
"""Get a live stream of timeseries readings.
This returns an Iterable over a live stream of readings. Note
that the result will need to be closed since the system can
not tell when you'll be done with it.
You can either call ``close`` on the endpoint when you're... | [
"def",
"live",
"(",
"self",
")",
":",
"session",
"=",
"self",
".",
"_session",
"url",
"=",
"\"{}/live\"",
".",
"format",
"(",
"self",
".",
"_base_url",
")",
"supported_params",
"=",
"frozenset",
"(",
"[",
"'filter[port]'",
"]",
")",
"params",
"=",
"{",
... | 32.40625 | 0.001873 |
def _handle_end_way(self):
"""
Handle closing way element
"""
self._result.append(Way(result=self._result, **self._curr))
self._curr = {} | [
"def",
"_handle_end_way",
"(",
"self",
")",
":",
"self",
".",
"_result",
".",
"append",
"(",
"Way",
"(",
"result",
"=",
"self",
".",
"_result",
",",
"*",
"*",
"self",
".",
"_curr",
")",
")",
"self",
".",
"_curr",
"=",
"{",
"}"
] | 28.666667 | 0.011299 |
def deriv(self, x: str, ctype: ContentType) -> SchemaPattern:
"""Return derivative of the receiver."""
return (self.pattern.deriv(x, ctype) if self.check_when() else
NotAllowed()) | [
"def",
"deriv",
"(",
"self",
",",
"x",
":",
"str",
",",
"ctype",
":",
"ContentType",
")",
"->",
"SchemaPattern",
":",
"return",
"(",
"self",
".",
"pattern",
".",
"deriv",
"(",
"x",
",",
"ctype",
")",
"if",
"self",
".",
"check_when",
"(",
")",
"else... | 52 | 0.009479 |
def lists(self, value, key=None):
"""
Get a list with the values of a given key
:rtype: list
"""
results = map(lambda x: x[value], self._items)
return list(results) | [
"def",
"lists",
"(",
"self",
",",
"value",
",",
"key",
"=",
"None",
")",
":",
"results",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
"[",
"value",
"]",
",",
"self",
".",
"_items",
")",
"return",
"list",
"(",
"results",
")"
] | 22.888889 | 0.009346 |
def getargspec_permissive(func):
"""
An `inspect.getargspec` with a relaxed sanity check to support Cython.
Motivation:
A Cython-compiled function is *not* an instance of Python's
types.FunctionType. That is the sanity check the standard Py2
library uses in `inspect.getargspec()`.... | [
"def",
"getargspec_permissive",
"(",
"func",
")",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"func",
"=",
"func",
".",
"im_func",
"# Py2 Stdlib uses isfunction(func) which is too strict for Cython-compiled",
"# functions though such have perfectly usable fu... | 46.148148 | 0.000786 |
def get_sdk_vc_script(self,host_arch, target_arch):
""" Return the script to initialize the VC compiler installed by SDK
"""
if (host_arch == 'amd64' and target_arch == 'x86'):
# No cross tools needed compiling 32 bits on 64 bit machine
host_arch=target_arch
arc... | [
"def",
"get_sdk_vc_script",
"(",
"self",
",",
"host_arch",
",",
"target_arch",
")",
":",
"if",
"(",
"host_arch",
"==",
"'amd64'",
"and",
"target_arch",
"==",
"'x86'",
")",
":",
"# No cross tools needed compiling 32 bits on 64 bit machine",
"host_arch",
"=",
"target_ar... | 44.333333 | 0.018405 |
def decode(self, envelope, session, private_key=None, oaep_hash_fn_name=None, mgf1_hash_fn_name=None, **kwargs):
""" :meth:`.WMessengerOnionCoderLayerProto.decode` method implementation.
:param envelope: original envelope
:param session: original session
:param private_key: private key to decrypt
:param oaep... | [
"def",
"decode",
"(",
"self",
",",
"envelope",
",",
"session",
",",
"private_key",
"=",
"None",
",",
"oaep_hash_fn_name",
"=",
"None",
",",
"mgf1_hash_fn_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"message",
"=",
"private_key",
".",
"decrypt",
... | 41.25 | 0.025185 |
def _wait_for_pod_deletion(self, daemonset_pods=None):
"""
Wait until this K8sNode has evicted all its K8sPods.
:param daemonset_pods: A list of K8sPods on this K8sNode that are managed by a K8sDaemonSet.
:return: None
"""
pods = self._pod_inventory()
... | [
"def",
"_wait_for_pod_deletion",
"(",
"self",
",",
"daemonset_pods",
"=",
"None",
")",
":",
"pods",
"=",
"self",
".",
"_pod_inventory",
"(",
")",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"while",
"len",
"(",
"pods",
")",
">",
"0",
":",
"if",
... | 31.111111 | 0.008666 |
def daily2D(inst, bin1, label1, bin2, label2, data_label, gate, returnBins=False):
"""2D Daily Occurrence Probability of data_label > gate over a season.
If data_label is greater than gate at least once per day,
then a 100% occurrence probability results.Season delineated by the bounds
attached to... | [
"def",
"daily2D",
"(",
"inst",
",",
"bin1",
",",
"label1",
",",
"bin2",
",",
"label2",
",",
"data_label",
",",
"gate",
",",
"returnBins",
"=",
"False",
")",
":",
"return",
"_occurrence2D",
"(",
"inst",
",",
"bin1",
",",
"label1",
",",
"bin2",
",",
"l... | 38.95 | 0.008766 |
def parse_toc(html_content):
"""
Parse TOC of HTML content if the SHOW_TOC config is true.
:param html_content: raw HTML content
:return: tuple(processed HTML, toc list, toc HTML unordered list)
"""
from flask import current_app
from veripress.model.toc import HtmlTocParser
if current_... | [
"def",
"parse_toc",
"(",
"html_content",
")",
":",
"from",
"flask",
"import",
"current_app",
"from",
"veripress",
".",
"model",
".",
"toc",
"import",
"HtmlTocParser",
"if",
"current_app",
".",
"config",
"[",
"'SHOW_TOC'",
"]",
":",
"toc_parser",
"=",
"HtmlTocP... | 36.136364 | 0.001225 |
def transcript_associated_plot (self):
""" Plot a bargraph showing the Transcript-associated reads """
# Plot bar graph of groups
keys = OrderedDict()
keys['Exonic Rate'] = { 'name': 'Exonic', 'color': '#2f7ed8' }
keys['Intronic Rate'] = { 'name': 'Intronic', 'color': '#8bbc21'... | [
"def",
"transcript_associated_plot",
"(",
"self",
")",
":",
"# Plot bar graph of groups",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'Exonic Rate'",
"]",
"=",
"{",
"'name'",
":",
"'Exonic'",
",",
"'color'",
":",
"'#2f7ed8'",
"}",
"keys",
"[",
"'Intron... | 43.964286 | 0.015103 |
def set_password(name, password):
'''
Set the password for a named user (insecure, the password will be in the
process list while the command is running)
:param str name: The name of the local user, which is assumed to be in the
local directory service
:param str password: The plaintext pa... | [
"def",
"set_password",
"(",
"name",
",",
"password",
")",
":",
"cmd",
"=",
"\"dscl . -passwd /Users/{0} '{1}'\"",
".",
"format",
"(",
"name",
",",
"password",
")",
"try",
":",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"execute_return_success",
"(",
"cmd",
... | 32.033333 | 0.00101 |
def get_domains(self):
"""
Retrieves the domains of the users from elastic.
"""
search = User.search()
search.aggs.bucket('domains', 'terms', field='domain', order={'_count': 'desc'}, size=100)
response = search.execute()
return [entry.key for entry in respons... | [
"def",
"get_domains",
"(",
"self",
")",
":",
"search",
"=",
"User",
".",
"search",
"(",
")",
"search",
".",
"aggs",
".",
"bucket",
"(",
"'domains'",
",",
"'terms'",
",",
"field",
"=",
"'domain'",
",",
"order",
"=",
"{",
"'_count'",
":",
"'desc'",
"}"... | 43 | 0.008547 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.