text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def expand(datafile, outfile=None):
"""
Expand and interpolate the given data file using the given method.
Datafile can be a filename or an HDUList
It is assumed that the file has been compressed and that there are `BN_?` keywords in the
fits header that describe how the compression was done.
... | [
"def",
"expand",
"(",
"datafile",
",",
"outfile",
"=",
"None",
")",
":",
"hdulist",
"=",
"load_file_or_hdu",
"(",
"datafile",
")",
"header",
"=",
"hdulist",
"[",
"0",
"]",
".",
"header",
"data",
"=",
"hdulist",
"[",
"0",
"]",
".",
"data",
"# Check for ... | 31.146667 | 0.00249 |
def get_voronoi_polyhedra(self, structure, n):
"""
Gives a weighted polyhedra around a site.
See ref: A Proposed Rigorous Definition of Coordination Number,
M. O'Keeffe, Acta Cryst. (1979). A35, 772-775
Args:
structure (Structure): structure for which to evaluate th... | [
"def",
"get_voronoi_polyhedra",
"(",
"self",
",",
"structure",
",",
"n",
")",
":",
"# Assemble the list of neighbors used in the tessellation",
"# Gets all atoms within a certain radius",
"if",
"self",
".",
"targets",
"is",
"None",
":",
"targets",
"=",
"structure",
".",... | 40.043478 | 0.001413 |
def act(self, world_state, agent_host, current_r ):
"""take 1 action in response to the current world state"""
obs_text = world_state.observations[-1].text
obs = json.loads(obs_text) # most recent observation
self.logger.debug(obs)
if not u'XPos' in obs or not u'ZPos' in... | [
"def",
"act",
"(",
"self",
",",
"world_state",
",",
"agent_host",
",",
"current_r",
")",
":",
"obs_text",
"=",
"world_state",
".",
"observations",
"[",
"-",
"1",
"]",
".",
"text",
"obs",
"=",
"json",
".",
"loads",
"(",
"obs_text",
")",
"# most recent obs... | 41.391304 | 0.008722 |
def drop(self, labels=None, axis=0, index=None, columns=None,
level=None, inplace=False, errors='raise'):
"""
Drop specified labels from rows or columns.
Remove rows or columns by specifying label names and corresponding
axis, or by specifying directly index or column names... | [
"def",
"drop",
"(",
"self",
",",
"labels",
"=",
"None",
",",
"axis",
"=",
"0",
",",
"index",
"=",
"None",
",",
"columns",
"=",
"None",
",",
"level",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"errors",
"=",
"'raise'",
")",
":",
"return",
"su... | 34.566929 | 0.000664 |
def find_by_project(self, project, params={}, **options):
"""Returns the compact records for all sections in the specified project.
Parameters
----------
project : {Id} The project to get sections from.
[params] : {Object} Parameters for the request
"""
path = "... | [
"def",
"find_by_project",
"(",
"self",
",",
"project",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/projects/%s/sections\"",
"%",
"(",
"project",
")",
"return",
"self",
".",
"client",
".",
"get",
"(",
"path",
",",
... | 40.1 | 0.009756 |
def expand_annotations(src_dir, dst_dir):
"""Expand annotations in user code.
Return dst_dir if annotation detected; return src_dir if not.
src_dir: directory path of user code (str)
dst_dir: directory to place generated files (str)
"""
if src_dir[-1] == slash:
src_dir = src_dir[:-1]
... | [
"def",
"expand_annotations",
"(",
"src_dir",
",",
"dst_dir",
")",
":",
"if",
"src_dir",
"[",
"-",
"1",
"]",
"==",
"slash",
":",
"src_dir",
"=",
"src_dir",
"[",
":",
"-",
"1",
"]",
"if",
"dst_dir",
"[",
"-",
"1",
"]",
"==",
"slash",
":",
"dst_dir",
... | 34.548387 | 0.001817 |
def deploy_file(source, dest):
"""Deploy a file"""
date = datetime.utcnow().strftime('%Y-%m-%d')
shandle = open(source)
with open(dest, 'w') as handle:
for line in shandle:
if line == '# Updated: %date%\n':
newline = '# Updated: %s\n' % date
else:
... | [
"def",
"deploy_file",
"(",
"source",
",",
"dest",
")",
":",
"date",
"=",
"datetime",
".",
"utcnow",
"(",
")",
".",
"strftime",
"(",
"'%Y-%m-%d'",
")",
"shandle",
"=",
"open",
"(",
"source",
")",
"with",
"open",
"(",
"dest",
",",
"'w'",
")",
"as",
"... | 31.615385 | 0.002364 |
def group_members_retrieve(self, device_group_id, **kwargs): # noqa: E501
"""Get a page of devices # noqa: E501
Get a page of device # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> t... | [
"def",
"group_members_retrieve",
"(",
"self",
",",
"device_group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",... | 156.230769 | 0.000489 |
def codonInformation(codons1, codons2):
"""
Take two C{list} of codons, and returns information about the min and
max distance between them.
@param codon1: a C{list} of codons.
@param codon2: a C{list} of codons.
@return: a dict whose keys are C{int} distances and whose values are lists
... | [
"def",
"codonInformation",
"(",
"codons1",
",",
"codons2",
")",
":",
"result",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"c1",
"in",
"codons1",
":",
"for",
"c2",
"in",
"codons2",
":",
"distance",
"=",
"findDistance",
"(",
"c1",
",",
"c2",
")",
"resu... | 29 | 0.001855 |
def function(minargs, maxargs, implicit=False, first=False, convert=None):
"""Function decorator.
minargs -- Minimum number of arguments taken by the function.
maxargs -- Maximum number of arguments taken by the function.
implicit -- True for functions which operate on a nodeset consist... | [
"def",
"function",
"(",
"minargs",
",",
"maxargs",
",",
"implicit",
"=",
"False",
",",
"first",
"=",
"False",
",",
"convert",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"def",
"new_f",
"(",
"self",
",",
"node",
",",
"pos",
",",
... | 42.272727 | 0.001402 |
def isIn(val, schema, name = None): # pylint: disable-msg=W0613
"""
!~~isIn(data)
"""
if name is None:
name = schema
if not _lists.has_key(name):
return False
try:
return val in _lists[name]
except TypeError:
return False | [
"def",
"isIn",
"(",
"val",
",",
"schema",
",",
"name",
"=",
"None",
")",
":",
"# pylint: disable-msg=W0613",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"schema",
"if",
"not",
"_lists",
".",
"has_key",
"(",
"name",
")",
":",
"return",
"False",
"try",... | 19.285714 | 0.017668 |
def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):
'''
Function to offset the "center" of a colormap. Useful for
data with a negative min and positive max and you want the
middle of the colormap's dynamic range to be at zero
Parameters
----------
cmap:
T... | [
"def",
"shiftedColorMap",
"(",
"cmap",
",",
"start",
"=",
"0",
",",
"midpoint",
"=",
"0.5",
",",
"stop",
"=",
"1.0",
",",
"name",
"=",
"'shiftedcmap'",
")",
":",
"cdict",
"=",
"{",
"'red'",
":",
"[",
"]",
",",
"'green'",
":",
"[",
"]",
",",
"'blu... | 33.45098 | 0.000569 |
def remote_addr(self):
"""Attempt to return the original client ip based on X-Forwarded-For
or X-Real-IP. If HTTP headers are unavailable or untrusted, returns
an empty string.
:return: original client ip.
"""
if not hasattr(self, "_remote_addr"):
if self.app... | [
"def",
"remote_addr",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_remote_addr\"",
")",
":",
"if",
"self",
".",
"app",
".",
"config",
".",
"PROXIES_COUNT",
"==",
"0",
":",
"self",
".",
"_remote_addr",
"=",
"\"\"",
"elif",
"self"... | 40.138889 | 0.001351 |
def create(type_dict, *type_parameters):
"""
EnumFactory.create(*type_parameters) expects:
enumeration name, (enumeration values)
"""
name, values = type_parameters
assert isinstance(values, (list, tuple))
for value in values:
assert isinstance(value, Compatibility.stringy)
r... | [
"def",
"create",
"(",
"type_dict",
",",
"*",
"type_parameters",
")",
":",
"name",
",",
"values",
"=",
"type_parameters",
"assert",
"isinstance",
"(",
"values",
",",
"(",
"list",
",",
"tuple",
")",
")",
"for",
"value",
"in",
"values",
":",
"assert",
"isin... | 38.1 | 0.010256 |
def readerForMemory(buffer, size, URL, encoding, options):
"""Create an xmltextReader for an XML in-memory document. The
parsing flags @options are a combination of xmlParserOption. """
ret = libxml2mod.xmlReaderForMemory(buffer, size, URL, encoding, options)
if ret is None:raise treeError('xmlReaderF... | [
"def",
"readerForMemory",
"(",
"buffer",
",",
"size",
",",
"URL",
",",
"encoding",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlReaderForMemory",
"(",
"buffer",
",",
"size",
",",
"URL",
",",
"encoding",
",",
"options",
")",
"if",
"ret",
... | 61.5 | 0.008021 |
def build_parser(self, options=None, permissive=False, **override_kwargs):
"""Construct an argparser from supplied options.
:keyword override_kwargs: keyword arguments to override when calling
parser constructor.
:keyword permissive: when true, build a parser that does not validate
... | [
"def",
"build_parser",
"(",
"self",
",",
"options",
"=",
"None",
",",
"permissive",
"=",
"False",
",",
"*",
"*",
"override_kwargs",
")",
":",
"kwargs",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_parser_kwargs",
")",
"kwargs",
".",
"setdefault",
"(",
... | 43.68 | 0.001792 |
def info(self, channel_name):
""" https://api.slack.com/methods/channels.info
"""
channel_id = self.get_channel_id(channel_name)
self.params.update({'channel': channel_id})
return FromUrl('https://slack.com/api/channels.info', self._requests)(data=self.params).get() | [
"def",
"info",
"(",
"self",
",",
"channel_name",
")",
":",
"channel_id",
"=",
"self",
".",
"get_channel_id",
"(",
"channel_name",
")",
"self",
".",
"params",
".",
"update",
"(",
"{",
"'channel'",
":",
"channel_id",
"}",
")",
"return",
"FromUrl",
"(",
"'h... | 50.166667 | 0.009804 |
def load_skel(self, file_name):
"""
Loads an ASF file into a skeleton structure.
:param file_name: The file name to load in.
"""
fid = open(file_name, 'r')
self.read_skel(fid)
fid.close()
self.name = file_name | [
"def",
"load_skel",
"(",
"self",
",",
"file_name",
")",
":",
"fid",
"=",
"open",
"(",
"file_name",
",",
"'r'",
")",
"self",
".",
"read_skel",
"(",
"fid",
")",
"fid",
".",
"close",
"(",
")",
"self",
".",
"name",
"=",
"file_name"
] | 21.153846 | 0.010453 |
def BreachDepressions(
dem,
in_place = False,
topology = 'D8'
):
"""Breaches all depressions in a DEM.
Args:
dem (rdarray): An elevation model
in_place (bool): If True, the DEM is modified in place and there is
no return; otherwise, a new, altered DEM is... | [
"def",
"BreachDepressions",
"(",
"dem",
",",
"in_place",
"=",
"False",
",",
"topology",
"=",
"'D8'",
")",
":",
"if",
"type",
"(",
"dem",
")",
"is",
"not",
"rdarray",
":",
"raise",
"Exception",
"(",
"\"A richdem.rdarray or numpy.ndarray is required!\"",
")",
"i... | 24 | 0.021075 |
def parse_environ(name, parse_class=ParseResult, **defaults):
"""
same as parse() but you pass in an environment variable name that will be used
to fetch the dsn
:param name: string, the environment variable name that contains the dsn to parse
:param parse_class: ParseResult, the class that will be... | [
"def",
"parse_environ",
"(",
"name",
",",
"parse_class",
"=",
"ParseResult",
",",
"*",
"*",
"defaults",
")",
":",
"return",
"parse",
"(",
"os",
".",
"environ",
"[",
"name",
"]",
",",
"parse_class",
",",
"*",
"*",
"defaults",
")"
] | 48.636364 | 0.009174 |
def get_urls(self):
"""
Adds a url to move nodes to this admin
"""
urls = super(TreeAdmin, self).get_urls()
if django.VERSION < (1, 10):
from django.views.i18n import javascript_catalog
jsi18n_url = url(r'^jsi18n/$', javascript_catalog, {'packages': ('tre... | [
"def",
"get_urls",
"(",
"self",
")",
":",
"urls",
"=",
"super",
"(",
"TreeAdmin",
",",
"self",
")",
".",
"get_urls",
"(",
")",
"if",
"django",
".",
"VERSION",
"<",
"(",
"1",
",",
"10",
")",
":",
"from",
"django",
".",
"views",
".",
"i18n",
"impor... | 32.363636 | 0.008186 |
def to_unicode(value):
"""Converts bytes, unicode, and C char arrays to unicode strings.
Bytes and C char arrays are decoded from UTF-8.
"""
if isinstance(value, ffi.CData):
return ffi.string(value).decode('utf-8')
elif isinstance(value, binary_type):
return value.decode('utf-8')
... | [
"def",
"to_unicode",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"ffi",
".",
"CData",
")",
":",
"return",
"ffi",
".",
"string",
"(",
"value",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"elif",
"isinstance",
"(",
"value",
",",
"binary... | 33.846154 | 0.002212 |
def get_all_launch_configurations(self, **kwargs):
"""
Returns a full description of the launch configurations given the
specified names.
If no names are specified, then the full details of all launch
configurations are returned.
:type names: list
:param names: ... | [
"def",
"get_all_launch_configurations",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"}",
"max_records",
"=",
"kwargs",
".",
"get",
"(",
"'max_records'",
",",
"None",
")",
"names",
"=",
"kwargs",
".",
"get",
"(",
"'names'",
",",
... | 37.8 | 0.001474 |
def package_maven():
""" Run maven package lifecycle """
if not os.getenv('JAVA_HOME'):
# make sure Maven uses the same JDK which we have used to compile
# and link the C-code
os.environ['JAVA_HOME'] = jdk_home_dir
mvn_goal = 'package'
log.info("Executing Maven goal '" + mvn_goa... | [
"def",
"package_maven",
"(",
")",
":",
"if",
"not",
"os",
".",
"getenv",
"(",
"'JAVA_HOME'",
")",
":",
"# make sure Maven uses the same JDK which we have used to compile",
"# and link the C-code",
"os",
".",
"environ",
"[",
"'JAVA_HOME'",
"]",
"=",
"jdk_home_dir",
"mv... | 34.53125 | 0.00088 |
def risk_metric_period(cls,
start_session,
end_session,
algorithm_returns,
benchmark_returns,
algorithm_leverages):
"""
Creates a dictionary representing the state of th... | [
"def",
"risk_metric_period",
"(",
"cls",
",",
"start_session",
",",
"end_session",
",",
"algorithm_returns",
",",
"benchmark_returns",
",",
"algorithm_leverages",
")",
":",
"algorithm_returns",
"=",
"algorithm_returns",
"[",
"(",
"algorithm_returns",
".",
"index",
">=... | 38.046296 | 0.00166 |
def errorBand(x, yAvg, yStd, yDensity, plt, n_colors=None):
"""
plot error-band around avg
where colour equals to point density
"""
dmn = yDensity.min()
dmx = yDensity.max()
if n_colors is None:
n_colors = dmx - dmn + 1
print(n_colors)
cm = plt.cm.get_cmap('Blues', lut=n_co... | [
"def",
"errorBand",
"(",
"x",
",",
"yAvg",
",",
"yStd",
",",
"yDensity",
",",
"plt",
",",
"n_colors",
"=",
"None",
")",
":",
"dmn",
"=",
"yDensity",
".",
"min",
"(",
")",
"dmx",
"=",
"yDensity",
".",
"max",
"(",
")",
"if",
"n_colors",
"is",
"None... | 28.862745 | 0.000657 |
def getoutput(self, cmd, split=True, depth=0):
"""Get output (possibly including stderr) from a subprocess.
Parameters
----------
cmd : str
Command to execute (can not end in '&', as background processes are
not supported.
split : bool, optional
If ... | [
"def",
"getoutput",
"(",
"self",
",",
"cmd",
",",
"split",
"=",
"True",
",",
"depth",
"=",
"0",
")",
":",
"if",
"cmd",
".",
"rstrip",
"(",
")",
".",
"endswith",
"(",
"'&'",
")",
":",
"# this is *far* from a rigorous test",
"raise",
"OSError",
"(",
"\"B... | 43.285714 | 0.001614 |
def es_version_check(f):
"""Decorator to check Elasticsearch version."""
@wraps(f)
def inner(*args, **kwargs):
cluster_ver = current_search.cluster_version[0]
client_ver = ES_VERSION[0]
if cluster_ver != client_ver:
raise click.ClickException(
'Elasticsear... | [
"def",
"es_version_check",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cluster_ver",
"=",
"current_search",
".",
"cluster_version",
"[",
"0",
"]",
"client_ver",
"=",
"ES_VERSION... | 40.5625 | 0.001506 |
def show_partitioning(rdd, show=True):
"""Seems to be significantly more expensive on cluster than locally"""
if show:
partitionCount = rdd.getNumPartitions()
try:
valueCount = rdd.countApprox(1000, confidence=0.50)
except:
valueCount = -1
try:
... | [
"def",
"show_partitioning",
"(",
"rdd",
",",
"show",
"=",
"True",
")",
":",
"if",
"show",
":",
"partitionCount",
"=",
"rdd",
".",
"getNumPartitions",
"(",
")",
"try",
":",
"valueCount",
"=",
"rdd",
".",
"countApprox",
"(",
"1000",
",",
"confidence",
"=",... | 38.133333 | 0.010239 |
def validate_network(roles=None,
inventory_path=None,
output_dir=None,
extra_vars=None):
"""Validate the network parameters (latency, bandwidth ...)
Performs flent, ping tests to validate the constraints set by
:py:func:`emulate_network`. Repor... | [
"def",
"validate_network",
"(",
"roles",
"=",
"None",
",",
"inventory_path",
"=",
"None",
",",
"output_dir",
"=",
"None",
",",
"extra_vars",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Checking the constraints'",
")",
"if",
"not",
"output_dir",
":"... | 35.657143 | 0.00078 |
def download_icon_font(icon_font, directory):
"""Download given (implemented) icon font into passed directory"""
try:
downloader = AVAILABLE_ICON_FONTS[icon_font]['downloader'](directory)
downloader.download_files()
return downloader
except KeyError: # pragma: no cover
raise... | [
"def",
"download_icon_font",
"(",
"icon_font",
",",
"directory",
")",
":",
"try",
":",
"downloader",
"=",
"AVAILABLE_ICON_FONTS",
"[",
"icon_font",
"]",
"[",
"'downloader'",
"]",
"(",
"directory",
")",
"downloader",
".",
"download_files",
"(",
")",
"return",
"... | 41.2 | 0.002375 |
def get_hardware(self, hardware_id, **kwargs):
"""Get details about a hardware device.
:param integer id: the hardware ID
:returns: A dictionary containing a large amount of information about
the specified server.
Example::
object_mask = "mask[id,networkV... | [
"def",
"get_hardware",
"(",
"self",
",",
"hardware_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mask'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'mask'",
"]",
"=",
"(",
"'id,'",
"'globalIdentifier,'",
"'fullyQualifiedDomainName,'",
"'hostname,'",
"'domai... | 43.096774 | 0.000732 |
def get(self, sid):
"""
Constructs a EnvironmentContext
:param sid: The sid
:returns: twilio.rest.serverless.v1.service.environment.EnvironmentContext
:rtype: twilio.rest.serverless.v1.service.environment.EnvironmentContext
"""
return EnvironmentContext(self._ve... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"EnvironmentContext",
"(",
"self",
".",
"_version",
",",
"service_sid",
"=",
"self",
".",
"_solution",
"[",
"'service_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 37.1 | 0.013158 |
def save_gmf_data(dstore, sitecol, gmfs, imts, events=()):
"""
:param dstore: a :class:`openquake.baselib.datastore.DataStore` instance
:param sitecol: a :class:`openquake.hazardlib.site.SiteCollection` instance
:param gmfs: an array of shape (N, E, M)
:param imts: a list of IMT strings
:param e... | [
"def",
"save_gmf_data",
"(",
"dstore",
",",
"sitecol",
",",
"gmfs",
",",
"imts",
",",
"events",
"=",
"(",
")",
")",
":",
"if",
"len",
"(",
"events",
")",
"==",
"0",
":",
"E",
"=",
"gmfs",
".",
"shape",
"[",
"1",
"]",
"events",
"=",
"numpy",
"."... | 36.846154 | 0.001017 |
def get_pk_value_on_save(self, instance):
"""Generate ID if required."""
value = super(AleaIdField, self).get_pk_value_on_save(instance)
if not value:
value = self.get_seeded_value(instance)
return value | [
"def",
"get_pk_value_on_save",
"(",
"self",
",",
"instance",
")",
":",
"value",
"=",
"super",
"(",
"AleaIdField",
",",
"self",
")",
".",
"get_pk_value_on_save",
"(",
"instance",
")",
"if",
"not",
"value",
":",
"value",
"=",
"self",
".",
"get_seeded_value",
... | 40.333333 | 0.008097 |
def init_app(
self,
app,
feature_policy=DEFAULT_FEATURE_POLICY,
force_https=True,
force_https_permanent=False,
force_file_save=False,
frame_options=SAMEORIGIN,
frame_options_allow_from=None,
strict_transport_secu... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"feature_policy",
"=",
"DEFAULT_FEATURE_POLICY",
",",
"force_https",
"=",
"True",
",",
"force_https_permanent",
"=",
"False",
",",
"force_file_save",
"=",
"False",
",",
"frame_options",
"=",
"SAMEORIGIN",
",",
"fr... | 44.561404 | 0.000385 |
def set_coords(self, value):
"""Set all the images contained in the animation to the specified value."""
self.__coords = value
for image in self.images:
image.coords = value | [
"def",
"set_coords",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"__coords",
"=",
"value",
"for",
"image",
"in",
"self",
".",
"images",
":",
"image",
".",
"coords",
"=",
"value"
] | 41 | 0.014354 |
def _wait_until_good_ticks(game_interface: GameInterface, required_new_ticks: int=3):
"""Blocks until we're getting new packets, indicating that the match is ready."""
rate_limit = rate_limiter.RateLimiter(120)
last_tick_game_time = None # What the tick time of the last observed tick was
packet = GameT... | [
"def",
"_wait_until_good_ticks",
"(",
"game_interface",
":",
"GameInterface",
",",
"required_new_ticks",
":",
"int",
"=",
"3",
")",
":",
"rate_limit",
"=",
"rate_limiter",
".",
"RateLimiter",
"(",
"120",
")",
"last_tick_game_time",
"=",
"None",
"# What the tick time... | 52 | 0.012592 |
def coarse_grain_transition_matrix(P, M):
""" Coarse grain transition matrix P using memberships M
Computes
.. math:
Pc = (M' M)^-1 M' P M
Parameters
----------
P : ndarray(n, n)
microstate transition matrix
M : ndarray(n, m)
membership matrix. Membership to macros... | [
"def",
"coarse_grain_transition_matrix",
"(",
"P",
",",
"M",
")",
":",
"# coarse-grain matrix: Pc = (M' M)^-1 M' P M",
"W",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"np",
".",
"dot",
"(",
"M",
".",
"T",
",",
"M",
")",
")",
"A",
"=",
"np",
".",
"dot",... | 24.3125 | 0.002472 |
def resolve_extensions(bot: commands.Bot, name: str) -> list:
"""
Tries to resolve extension queries into a list of extension names.
"""
if name.endswith('.*'):
module_parts = name[:-2].split('.')
path = pathlib.Path(module_parts.pop(0))
for part in module_parts:
pa... | [
"def",
"resolve_extensions",
"(",
"bot",
":",
"commands",
".",
"Bot",
",",
"name",
":",
"str",
")",
"->",
"list",
":",
"if",
"name",
".",
"endswith",
"(",
"'.*'",
")",
":",
"module_parts",
"=",
"name",
"[",
":",
"-",
"2",
"]",
".",
"split",
"(",
... | 24.611111 | 0.002174 |
async def fetchone(self):
"""Fetch single row from the cursor.
"""
row = await self._cursor.fetchone()
if not row:
raise GeneratorExit
self._rows.append(row) | [
"async",
"def",
"fetchone",
"(",
"self",
")",
":",
"row",
"=",
"await",
"self",
".",
"_cursor",
".",
"fetchone",
"(",
")",
"if",
"not",
"row",
":",
"raise",
"GeneratorExit",
"self",
".",
"_rows",
".",
"append",
"(",
"row",
")"
] | 29 | 0.009569 |
def load_fs_mrf_to_syntax_mrf_translation_rules( rulesFile ):
''' Loads rules that can be used to convert from Filosoft's mrf format to
syntactic analyzer's format. Returns a dict containing rules.
Expects that each line in the input file contains a single rule, and that
different parts o... | [
"def",
"load_fs_mrf_to_syntax_mrf_translation_rules",
"(",
"rulesFile",
")",
":",
"rules",
"=",
"{",
"}",
"in_f",
"=",
"codecs",
".",
"open",
"(",
"rulesFile",
",",
"mode",
"=",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"for",
"line",
"in",
"in_f",
":",... | 42.914286 | 0.011719 |
def _tsv2json(in_tsv, out_json, index_column, additional_metadata=None,
drop_columns=None, enforce_case=True):
"""
Convert metadata from TSV format to JSON format.
Parameters
----------
in_tsv: str
Path to the metadata in TSV format.
out_json: str
Path where the me... | [
"def",
"_tsv2json",
"(",
"in_tsv",
",",
"out_json",
",",
"index_column",
",",
"additional_metadata",
"=",
"None",
",",
"drop_columns",
"=",
"None",
",",
"enforce_case",
"=",
"True",
")",
":",
"import",
"pandas",
"as",
"pd",
"# Adapted from https://dev.to/rrampage/... | 37.583333 | 0.00036 |
def write_grid_local(tiles, params):
"""
Write a file for each tile
"""
# TODO: this isn't being used right now, will need to be
# ported to gfile if we want to keep it
for ti,tj,tile in enumerate_tiles(tiles):
filename = "{directory}/{name}/tile_{n_layer}_{n_tile}_{ti}_{tj}".format(ti=ti, tj=tj, **para... | [
"def",
"write_grid_local",
"(",
"tiles",
",",
"params",
")",
":",
"# TODO: this isn't being used right now, will need to be",
"# ported to gfile if we want to keep it",
"for",
"ti",
",",
"tj",
",",
"tile",
"in",
"enumerate_tiles",
"(",
"tiles",
")",
":",
"filename",
"="... | 43.066667 | 0.016667 |
def list_domains_by_service(self, service_id):
"""List the domains within a service."""
content = self._fetch("/service/%s/domain" % service_id, method="GET")
return map(lambda x: FastlyDomain(self, x), content) | [
"def",
"list_domains_by_service",
"(",
"self",
",",
"service_id",
")",
":",
"content",
"=",
"self",
".",
"_fetch",
"(",
"\"/service/%s/domain\"",
"%",
"service_id",
",",
"method",
"=",
"\"GET\"",
")",
"return",
"map",
"(",
"lambda",
"x",
":",
"FastlyDomain",
... | 53.5 | 0.023041 |
def btnstate(self, item= None):
""" Function to handle difficult examples
Update on each object """
if not self.canvas.editing():
return
item = self.currentItem()
if not item: # If not selected Item, take the first one
item = self.labelList.item(self.labe... | [
"def",
"btnstate",
"(",
"self",
",",
"item",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"canvas",
".",
"editing",
"(",
")",
":",
"return",
"item",
"=",
"self",
".",
"currentItem",
"(",
")",
"if",
"not",
"item",
":",
"# If not selected Item, take ... | 31.72 | 0.008568 |
def draw(self, img, pixmapper, bounds):
'''draw a polygon on the image'''
if self.hidden:
return
(x,y,w,h) = bounds
spacing = 1000
while True:
start = mp_util.latlon_round((x,y), spacing)
dist = mp_util.gps_distance(x,y,x+w,y+h)
cou... | [
"def",
"draw",
"(",
"self",
",",
"img",
",",
"pixmapper",
",",
"bounds",
")",
":",
"if",
"self",
".",
"hidden",
":",
"return",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
"=",
"bounds",
"spacing",
"=",
"1000",
"while",
"True",
":",
"start",
"=... | 39.12 | 0.010978 |
def sanity_check(
state: MediatorTransferState,
channelidentifiers_to_channels: ChannelMap,
) -> None:
""" Check invariants that must hold. """
# if a transfer is paid we must know the secret
all_transfers_states = itertools.chain(
(pair.payee_state for pair in state.transfers_pair)... | [
"def",
"sanity_check",
"(",
"state",
":",
"MediatorTransferState",
",",
"channelidentifiers_to_channels",
":",
"ChannelMap",
",",
")",
"->",
"None",
":",
"# if a transfer is paid we must know the secret",
"all_transfers_states",
"=",
"itertools",
".",
"chain",
"(",
"(",
... | 35.712329 | 0.000747 |
def clean(self, *args, **kwargs):
""" from_user and to_user must differ """
if self.from_user and self.from_user_id == self.to_user_id:
raise ValidationError(_('A user cannot send a notification to herself/himself')) | [
"def",
"clean",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"from_user",
"and",
"self",
".",
"from_user_id",
"==",
"self",
".",
"to_user_id",
":",
"raise",
"ValidationError",
"(",
"_",
"(",
"'A user cannot send a ... | 60.25 | 0.012295 |
def get_user_permissions(self, user_id):
"""Returns a sorted list of a users permissions"""
permissions = self.user_service.getPermissions(id=user_id)
return sorted(permissions, key=itemgetter('keyName')) | [
"def",
"get_user_permissions",
"(",
"self",
",",
"user_id",
")",
":",
"permissions",
"=",
"self",
".",
"user_service",
".",
"getPermissions",
"(",
"id",
"=",
"user_id",
")",
"return",
"sorted",
"(",
"permissions",
",",
"key",
"=",
"itemgetter",
"(",
"'keyNam... | 56.25 | 0.008772 |
def color(self, key=None):
"""
Returns the color for this data set.
:return <QColor>
"""
if key is not None:
return self._colorMap.get(nativestring(key), self._color)
return self._color | [
"def",
"color",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_colorMap",
".",
"get",
"(",
"nativestring",
"(",
"key",
")",
",",
"self",
".",
"_color",
")",
"return",
"self",
".",
"... | 28.666667 | 0.011278 |
def connect_options_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_options_namespaced_pod_proxy # noqa: E501
connect OPTIONS requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP req... | [
"def",
"connect_options_namespaced_pod_proxy",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",... | 53.826087 | 0.001587 |
def decode_int(tag, bits_per_char=6):
"""Decode string into int assuming encoding with `encode_int()`
It is using 2, 4 or 6 bits per coding character (default 6).
Parameters:
tag: str Encoded integer.
bits_per_char: int The number of bits per coding character.
Returns:
... | [
"def",
"decode_int",
"(",
"tag",
",",
"bits_per_char",
"=",
"6",
")",
":",
"if",
"bits_per_char",
"==",
"6",
":",
"return",
"_decode_int64",
"(",
"tag",
")",
"if",
"bits_per_char",
"==",
"4",
":",
"return",
"_decode_int16",
"(",
"tag",
")",
"if",
"bits_p... | 29 | 0.001669 |
def save_graph(graphdef):
'''save a graph as XML'''
if graphdef.filename is None:
if 'HOME' in os.environ:
dname = os.path.join(os.environ['HOME'], '.mavproxy')
mp_util.mkdir_p(dname)
graphdef.filename = os.path.join(dname, 'mavgraphs.xml')
else:
g... | [
"def",
"save_graph",
"(",
"graphdef",
")",
":",
"if",
"graphdef",
".",
"filename",
"is",
"None",
":",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
":",
"dname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
",",... | 38.735294 | 0.002222 |
def copy(self, newdoc=None, idsuffix=""):
"""Make a deep copy of this element and all its children.
Parameters:
newdoc (:class:`Document`): The document the copy should be associated with.
idsuffix (str or bool): If set to a string, the ID of the copy will be append with this (p... | [
"def",
"copy",
"(",
"self",
",",
"newdoc",
"=",
"None",
",",
"idsuffix",
"=",
"\"\"",
")",
":",
"if",
"idsuffix",
"is",
"True",
":",
"idsuffix",
"=",
"\".copy.\"",
"+",
"\"%08x\"",
"%",
"random",
".",
"getrandbits",
"(",
"32",
")",
"#random 32-bit hash f... | 46.764706 | 0.009864 |
def put(self, rank, val):
"""
Args:
rank(int): rank of th element. All elements must have different ranks.
val: an object
"""
idx = bisect.bisect(self.ranks, rank)
self.ranks.insert(idx, rank)
self.data.insert(idx, val) | [
"def",
"put",
"(",
"self",
",",
"rank",
",",
"val",
")",
":",
"idx",
"=",
"bisect",
".",
"bisect",
"(",
"self",
".",
"ranks",
",",
"rank",
")",
"self",
".",
"ranks",
".",
"insert",
"(",
"idx",
",",
"rank",
")",
"self",
".",
"data",
".",
"insert... | 31.444444 | 0.010309 |
def repertoire(self, direction, mechanism, purview):
"""Return the cause or effect repertoire function based on a direction.
Args:
direction (str): The temporal direction, specifiying the cause or
effect repertoire.
"""
system = self.system[direction]
... | [
"def",
"repertoire",
"(",
"self",
",",
"direction",
",",
"mechanism",
",",
"purview",
")",
":",
"system",
"=",
"self",
".",
"system",
"[",
"direction",
"]",
"node_labels",
"=",
"system",
".",
"node_labels",
"if",
"not",
"set",
"(",
"purview",
")",
".",
... | 44.052632 | 0.002339 |
def snpflow(args):
"""
%prog snpflow trimmed reference.fasta
Run SNP calling pipeline until allele_counts are generated. This includes
generation of native files, SNP_Het file. Speedup for fragmented genomes
are also supported.
"""
p = OptionParser(snpflow.__doc__)
p.set_fastq_names()
... | [
"def",
"snpflow",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"snpflow",
".",
"__doc__",
")",
"p",
".",
"set_fastq_names",
"(",
")",
"p",
".",
"set_cpus",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",... | 38.561151 | 0.000182 |
def synchronized(func):
'''Decorator to synchronize function.'''
func.__lock__ = threading.Lock()
def synced_func(*args, **kargs):
with func.__lock__:
return func(*args, **kargs)
return synced_func | [
"def",
"synchronized",
"(",
"func",
")",
":",
"func",
".",
"__lock__",
"=",
"threading",
".",
"Lock",
"(",
")",
"def",
"synced_func",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"with",
"func",
".",
"__lock__",
":",
"return",
"func",
"(",
"... | 29.857143 | 0.032558 |
def exists(self, primary_key):
'''
a method to determine if record exists
:param primary_key: string with primary key of record
:return: boolean to indicate existence of record
'''
select_statement = self.table.select(self.table).where(... | [
"def",
"exists",
"(",
"self",
",",
"primary_key",
")",
":",
"select_statement",
"=",
"self",
".",
"table",
".",
"select",
"(",
"self",
".",
"table",
")",
".",
"where",
"(",
"self",
".",
"table",
".",
"c",
".",
"id",
"==",
"primary_key",
")",
"record_... | 34.142857 | 0.016293 |
def arrow(self, JOIN, _id):
"""Removes all previous assignments from JOIN that have the same left hand side.
This represents the arrow id definition from Schwartzbach."""
r = JOIN
for node in self.lattice.get_elements(JOIN):
if node.left_hand_side == _id:
r = ... | [
"def",
"arrow",
"(",
"self",
",",
"JOIN",
",",
"_id",
")",
":",
"r",
"=",
"JOIN",
"for",
"node",
"in",
"self",
".",
"lattice",
".",
"get_elements",
"(",
"JOIN",
")",
":",
"if",
"node",
".",
"left_hand_side",
"==",
"_id",
":",
"r",
"=",
"r",
"^",
... | 44.75 | 0.008219 |
def create(cls, infile, config=None, params=None, mask=None):
"""Create a new instance of GTAnalysis from an analysis output file
generated with `~fermipy.GTAnalysis.write_roi`. By default
the new instance will inherit the configuration of the saved
analysis instance. The configuration... | [
"def",
"create",
"(",
"cls",
",",
"infile",
",",
"config",
"=",
"None",
",",
"params",
"=",
"None",
",",
"mask",
"=",
"None",
")",
":",
"infile",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"infile",
")",
"roi_file",
",",
"roi_data",
"=",
"utils",... | 30.615385 | 0.002435 |
def is_permitted_by_robots(site, url, proxy=None):
'''
Checks if `url` is permitted by robots.txt.
Treats any kind of error fetching robots.txt as "allow all". See
http://builds.archive.org/javadoc/heritrix-3.x-snapshot/org/archive/modules/net/CrawlServer.html#updateRobots(org.archive.modules.CrawlURI)... | [
"def",
"is_permitted_by_robots",
"(",
"site",
",",
"url",
",",
"proxy",
"=",
"None",
")",
":",
"if",
"site",
".",
"ignore_robots",
":",
"return",
"True",
"try",
":",
"result",
"=",
"_robots_cache",
"(",
"site",
",",
"proxy",
")",
".",
"allowed",
"(",
"... | 38.638889 | 0.000701 |
def arg_props(self):
"""Return the value and scalar properties as a dictionary. Returns only argumnet properties,
properties declared on the same row as a term. It will return an entry for all of the args declared by the
term's section. Use props to get values of all children and
arg pr... | [
"def",
"arg_props",
"(",
"self",
")",
":",
"d",
"=",
"dict",
"(",
"zip",
"(",
"[",
"str",
"(",
"e",
")",
".",
"lower",
"(",
")",
"for",
"e",
"in",
"self",
".",
"section",
".",
"property_names",
"]",
",",
"self",
".",
"args",
")",
")",
"# print(... | 46.083333 | 0.008865 |
def run(self):
"""Run the thread."""
while True:
try:
try:
name, value, valueType, stamp = self.queue.get()
except TypeError:
break
self.log(name, value, valueType, stamp)
finally:
self.queue.task_done() | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"try",
":",
"name",
",",
"value",
",",
"valueType",
",",
"stamp",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"except",
"TypeError",
":",
"break",
"self",
".",
"log",
"("... | 24.090909 | 0.018182 |
def add_function_to(self, to, func, name, ctypes, signature):
"""
Add a function to be exposed. *func* is expected to be a
:class:`cgen.FunctionBody`.
Because a function can have several signatures exported,
this method actually creates a wrapper for each specialization
... | [
"def",
"add_function_to",
"(",
"self",
",",
"to",
",",
"func",
",",
"name",
",",
"ctypes",
",",
"signature",
")",
":",
"to",
".",
"append",
"(",
"func",
")",
"args_unboxing",
"=",
"[",
"]",
"# turns PyObject to c++ object",
"args_checks",
"=",
"[",
"]",
... | 42.163934 | 0.00076 |
def gpg_verify( path_to_verify, sigdata, sender_key_info, config_dir=None ):
"""
Verify a file on disk was signed by the given sender.
@sender_key_info should be a dict with
{
'key_id': ...
'key_data': ...
'app_name'; ...
}
Return {'status': True} on success
Return {'... | [
"def",
"gpg_verify",
"(",
"path_to_verify",
",",
"sigdata",
",",
"sender_key_info",
",",
"config_dir",
"=",
"None",
")",
":",
"if",
"config_dir",
"is",
"None",
":",
"config_dir",
"=",
"get_config_dir",
"(",
")",
"# ingest keys ",
"tmpdir",
"=",
"make_gpg_tmphome... | 27.591837 | 0.014286 |
def compute_qwerty_distance(c1, c2):
'''
Provides a score representing the distance between two characters on a
QWERTY keyboard, utilizing a simple matrix to represent the keyboard:
| 0 1 2 3 4 5 6 7 8 9 10 11 12 13
--+---+---+---+---+---+---+---+---+---+---+---+---+---... | [
"def",
"compute_qwerty_distance",
"(",
"c1",
",",
"c2",
")",
":",
"# build table",
"keyboard",
"=",
"[",
"[",
"'`'",
",",
"'1'",
",",
"'2'",
",",
"'3'",
",",
"'4'",
",",
"'5'",
",",
"'6'",
",",
"'7'",
",",
"'8'",
",",
"'9'",
",",
"'0'",
",",
"'-'... | 40.204545 | 0.001104 |
def channel_L(self):
"""
The channel length of the flocculator. If ha.HUMAN_W_MIN or W_min_HS_ratio
is the defining constraint for the flocculator width, then the flocculator
volume will be greater than necessary. Bring the volume back to the design
volume by shortening the flocc... | [
"def",
"channel_L",
"(",
"self",
")",
":",
"channel_L",
"=",
"(",
"(",
"self",
".",
"vol",
"/",
"(",
"self",
".",
"channel_W",
"*",
"self",
".",
"downstream_H",
")",
"+",
"self",
".",
"ent_tank_L",
")",
"/",
"self",
".",
"channel_n",
")",
".",
"to"... | 58.133333 | 0.009029 |
def get_attached_pipettes(self):
"""
Gets model names of attached pipettes
:return: :dict with keys 'left' and 'right' and a model string for each
mount, or 'uncommissioned' if no model string available
"""
left_data = {
'mount_axis': 'z',
... | [
"def",
"get_attached_pipettes",
"(",
"self",
")",
":",
"left_data",
"=",
"{",
"'mount_axis'",
":",
"'z'",
",",
"'plunger_axis'",
":",
"'b'",
",",
"'model'",
":",
"self",
".",
"model_by_mount",
"[",
"'left'",
"]",
"[",
"'model'",
"]",
",",
"'id'",
":",
"s... | 34.971429 | 0.00159 |
def calc_variances(params):
'''
This function calculates the variance of the sum signal and all population-resolved signals
'''
depth = params.electrodeParams['z']
############################
### CSD ###
############################
for i, data_type in enumerate(['C... | [
"def",
"calc_variances",
"(",
"params",
")",
":",
"depth",
"=",
"params",
".",
"electrodeParams",
"[",
"'z'",
"]",
"############################",
"### CSD ###",
"############################",
"for",
"i",
",",
"data_type",
"in",
"enumerate",
"(",
"["... | 35.787879 | 0.016488 |
def create_task(function, *args, **kwargs):
"""
Create a task object
name: The name of the task.
function: The actual task function. It should take no arguments,
and return a False-y value if it fails.
dependencies: (optional, ()) Any dependencies that this task relies
on.
"""
... | [
"def",
"create_task",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"\"{}\"",
".",
"format",
"(",
"uuid4",
"(",
")",
")",
"handler",
"=",
"None",
"deps",
"=",
"set",
"(",
")",
"if",
"'name'",
"in",
"kwargs",
"... | 27.459459 | 0.000951 |
def start(self, request=None):
"""Starts processing the request for this protocol consumer.
There is no need to override this method,
implement :meth:`start_request` instead.
If either :attr:`connection` or :attr:`transport` are missing, a
:class:`RuntimeError` occurs.
... | [
"def",
"start",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"self",
".",
"connection",
".",
"processed",
"+=",
"1",
"self",
".",
"producer",
".",
"requests_processed",
"+=",
"1",
"self",
".",
"event",
"(",
"'post_request'",
")",
".",
"bind",
"(... | 38.227273 | 0.00232 |
def _to_bytes(value, encoding="ascii"):
"""Converts a string value to bytes, if necessary.
Unfortunately, ``six.b`` is insufficient for this task since in
Python2 it does not modify ``unicode`` objects.
:type value: str / bytes or unicode
:param value: The string/bytes value to be converted.
... | [
"def",
"_to_bytes",
"(",
"value",
",",
"encoding",
"=",
"\"ascii\"",
")",
":",
"result",
"=",
"value",
".",
"encode",
"(",
"encoding",
")",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"text_type",
")",
"else",
"value",
"if",
"isinstance",
"(",
"... | 43.851852 | 0.001653 |
def list(self):
"""
List the contents of the directory.
"""
return [File(f, parent=self) for f in os.listdir(self.path)] | [
"def",
"list",
"(",
"self",
")",
":",
"return",
"[",
"File",
"(",
"f",
",",
"parent",
"=",
"self",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"path",
")",
"]"
] | 29.6 | 0.013158 |
def flatten_dict(self, d, delimiter="-", intermediates=False, parent_key=None):
"""
Flatten a dictionary.
Values that are dictionaries are flattened using delimiter in between
(eg. parent-child)
Values that are lists are flattened using delimiter
followed by the index (... | [
"def",
"flatten_dict",
"(",
"self",
",",
"d",
",",
"delimiter",
"=",
"\"-\"",
",",
"intermediates",
"=",
"False",
",",
"parent_key",
"=",
"None",
")",
":",
"items",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"d",
"=",
"dict... | 33 | 0.001298 |
def remove_pointer(type_):
"""removes pointer from the type definition
If type is not pointer type, it will be returned as is.
"""
nake_type = remove_alias(type_)
if not is_pointer(nake_type):
return type_
elif isinstance(nake_type, cpptypes.volatile_t) and \
isinstance(nake... | [
"def",
"remove_pointer",
"(",
"type_",
")",
":",
"nake_type",
"=",
"remove_alias",
"(",
"type_",
")",
"if",
"not",
"is_pointer",
"(",
"nake_type",
")",
":",
"return",
"type_",
"elif",
"isinstance",
"(",
"nake_type",
",",
"cpptypes",
".",
"volatile_t",
")",
... | 39.590909 | 0.001121 |
def pkgPath(root, path, rpath="/"):
"""
Package up a path recursively
"""
global data_files
if not os.path.exists(path):
return
files = []
for spath in os.listdir(path):
# Ignore test directories
if spath == 'test':
continue
subpath = os.path.j... | [
"def",
"pkgPath",
"(",
"root",
",",
"path",
",",
"rpath",
"=",
"\"/\"",
")",
":",
"global",
"data_files",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"files",
"=",
"[",
"]",
"for",
"spath",
"in",
"os",
".",
"li... | 29.105263 | 0.001751 |
def open_text(fn:PathOrStr, enc='utf-8'):
"Read the text in `fn`."
with open(fn,'r', encoding = enc) as f: return ''.join(f.readlines()) | [
"def",
"open_text",
"(",
"fn",
":",
"PathOrStr",
",",
"enc",
"=",
"'utf-8'",
")",
":",
"with",
"open",
"(",
"fn",
",",
"'r'",
",",
"encoding",
"=",
"enc",
")",
"as",
"f",
":",
"return",
"''",
".",
"join",
"(",
"f",
".",
"readlines",
"(",
")",
"... | 47.333333 | 0.041667 |
def chunks_generator(iterable, count_items_in_chunk):
"""
Очень внимательно! Не дает обходить дважды
:param iterable:
:param count_items_in_chunk:
:return:
"""
iterator = iter(iterable)
for first in iterator: # stops when iterator is depleted
def chunk(): # construct generator... | [
"def",
"chunks_generator",
"(",
"iterable",
",",
"count_items_in_chunk",
")",
":",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"for",
"first",
"in",
"iterator",
":",
"# stops when iterator is depleted",
"def",
"chunk",
"(",
")",
":",
"# construct generator for ne... | 33.375 | 0.001821 |
def parse_compartments(self):
"""Parse compartment information from model.
Return tuple of: 1) iterator of
:class:`psamm.datasource.entry.CompartmentEntry`; 2) Set of pairs
defining the compartment boundaries of the model.
"""
compartments = OrderedDict()
bounda... | [
"def",
"parse_compartments",
"(",
"self",
")",
":",
"compartments",
"=",
"OrderedDict",
"(",
")",
"boundaries",
"=",
"set",
"(",
")",
"if",
"'compartments'",
"in",
"self",
".",
"_model",
":",
"boundary_map",
"=",
"{",
"}",
"for",
"compartment_def",
"in",
"... | 41.886364 | 0.00106 |
def dedup_alignment_plot (self):
""" Make the HighCharts HTML to plot the duplication rates """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['not_removed'] = { 'name': 'Not Removed' }
keys['reverse_removed'] = { 'name': 'Reverse Removed' }
... | [
"def",
"dedup_alignment_plot",
"(",
"self",
")",
":",
"# Specify the order of the different possible categories",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'not_removed'",
"]",
"=",
"{",
"'name'",
":",
"'Not Removed'",
"}",
"keys",
"[",
"'reverse_removed'",
... | 37.8 | 0.016774 |
def _tpl_possibilities(self):
"""
Construct a list of possible paths to templates.
"""
tpl_possibilities = [
os.path.realpath(self.tpl)
]
for tpl_dir in self.tpl_dirs:
tpl_possibilities.append(os.path.realpath(os.path.join(tpl_dir, "{0}.tpl".format... | [
"def",
"_tpl_possibilities",
"(",
"self",
")",
":",
"tpl_possibilities",
"=",
"[",
"os",
".",
"path",
".",
"realpath",
"(",
"self",
".",
"tpl",
")",
"]",
"for",
"tpl_dir",
"in",
"self",
".",
"tpl_dirs",
":",
"tpl_possibilities",
".",
"append",
"(",
"os",... | 38.416667 | 0.008475 |
def _create_sample_list(in_bams, vcf_file):
"""Pull sample names from input BAMs and create input sample list.
"""
out_file = "%s-sample_list.txt" % os.path.splitext(vcf_file)[0]
with open(out_file, "w") as out_handle:
for in_bam in in_bams:
with pysam.Samfile(in_bam, "rb") as work_b... | [
"def",
"_create_sample_list",
"(",
"in_bams",
",",
"vcf_file",
")",
":",
"out_file",
"=",
"\"%s-sample_list.txt\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"vcf_file",
")",
"[",
"0",
"]",
"with",
"open",
"(",
"out_file",
",",
"\"w\"",
")",
"as",
"o... | 44.7 | 0.002193 |
def iter_ROOT_classes():
"""
Iterator over all available ROOT classes
"""
class_index = "http://root.cern.ch/root/html/ClassIndex.html"
for s in minidom.parse(urlopen(class_index)).getElementsByTagName("span"):
if ("class", "typename") in s.attributes.items():
class_name = s.chil... | [
"def",
"iter_ROOT_classes",
"(",
")",
":",
"class_index",
"=",
"\"http://root.cern.ch/root/html/ClassIndex.html\"",
"for",
"s",
"in",
"minidom",
".",
"parse",
"(",
"urlopen",
"(",
"class_index",
")",
")",
".",
"getElementsByTagName",
"(",
"\"span\"",
")",
":",
"if... | 37.5 | 0.002169 |
def login(self, oauth_filename="oauth", uploader_id=None):
"""Authenticate the gmusicapi Musicmanager instance.
Parameters:
oauth_filename (str): The filename of the oauth credentials file to use/create for login.
Default: ``oauth``
uploader_id (str): A unique id as a MAC address (e.g. ``'00:11:22:33:AA... | [
"def",
"login",
"(",
"self",
",",
"oauth_filename",
"=",
"\"oauth\"",
",",
"uploader_id",
"=",
"None",
")",
":",
"cls_name",
"=",
"type",
"(",
"self",
")",
".",
"__name__",
"oauth_cred",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".... | 31.641026 | 0.025943 |
def render_twitter(text, **kwargs):
"""
Strict template block for rendering twitter embeds.
"""
author = render_author(**kwargs['author'])
metadata = render_metadata(**kwargs['metadata'])
image = render_image(**kwargs['image'])
html = """
<div class="attachment attachment-twitter">
... | [
"def",
"render_twitter",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"author",
"=",
"render_author",
"(",
"*",
"*",
"kwargs",
"[",
"'author'",
"]",
")",
"metadata",
"=",
"render_metadata",
"(",
"*",
"*",
"kwargs",
"[",
"'metadata'",
"]",
")",
"imag... | 24.434783 | 0.001712 |
def handle_error(program_name, cmd, log=None):
"""Subprocess program error handling
Args:
program_name (str): name of the subprocess program
Returns:
break_now (bool): indicate whether calling program should break out of loop
"""
print('\nHouston, we have a problem.',
'\... | [
"def",
"handle_error",
"(",
"program_name",
",",
"cmd",
",",
"log",
"=",
"None",
")",
":",
"print",
"(",
"'\\nHouston, we have a problem.'",
",",
"'\\n%s did not finish successfully. Review the log'",
"%",
"program_name",
",",
"'file and the input file(s) to see what went wro... | 35.234043 | 0.00235 |
def paths_to_str(paths, format_kwargs={}, delimiter=os.pathsep, asset_paths=False,
check_paths=False):
"""Convert ``paths`` to a single string.
Args:
paths (str|list): A string like "/a/path:/another/path" or
a list of paths; may include absolute paths and/or asset
... | [
"def",
"paths_to_str",
"(",
"paths",
",",
"format_kwargs",
"=",
"{",
"}",
",",
"delimiter",
"=",
"os",
".",
"pathsep",
",",
"asset_paths",
"=",
"False",
",",
"check_paths",
"=",
"False",
")",
":",
"if",
"not",
"paths",
":",
"return",
"''",
"if",
"isins... | 38.777778 | 0.002096 |
def romanized(locale: str = '') -> Callable:
"""Romanize the Cyrillic text.
Transliterate the Cyrillic language from the Cyrillic
script into the Latin alphabet.
.. note:: At this moment it works only for `ru`, `uk`, `kk`.
:param locale: Locale code.
:return: Latinized text.
"""
def r... | [
"def",
"romanized",
"(",
"locale",
":",
"str",
"=",
"''",
")",
"->",
"Callable",
":",
"def",
"romanized_deco",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"... | 33.258065 | 0.000943 |
def to_grayscale(cv2im):
"""Convert gradients to grayscale. This gives a saliency map."""
# How strongly does each position activate the output
grayscale_im = np.sum(np.abs(cv2im), axis=0)
# Normalize between min and 99th percentile
im_max = np.percentile(grayscale_im, 99)
im_min = np.min(grays... | [
"def",
"to_grayscale",
"(",
"cv2im",
")",
":",
"# How strongly does each position activate the output",
"grayscale_im",
"=",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"cv2im",
")",
",",
"axis",
"=",
"0",
")",
"# Normalize between min and 99th percentile",
"im_ma... | 39.666667 | 0.002053 |
def _extract_path_parameters_from_paths(paths):
"""
from a list of paths, return back a list of the
arguments present in those paths.
the arguments available in all of the paths must match: if not,
an exception will be raised.
"""
params = set()
for path in paths:
parts = PART_R... | [
"def",
"_extract_path_parameters_from_paths",
"(",
"paths",
")",
":",
"params",
"=",
"set",
"(",
")",
"for",
"path",
"in",
"paths",
":",
"parts",
"=",
"PART_REGEX",
".",
"split",
"(",
"path",
")",
"for",
"p",
"in",
"parts",
":",
"match",
"=",
"PARAM_REGE... | 29.625 | 0.002045 |
def disc_benchmarks(root, ignore_import_errors=False):
"""
Discover all benchmarks in a given directory tree, yielding Benchmark
objects
For each class definition, looks for any methods with a
special name.
For each free function, yields all functions with a special
name.
"""
root... | [
"def",
"disc_benchmarks",
"(",
"root",
",",
"ignore_import_errors",
"=",
"False",
")",
":",
"root_name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"root",
")",
"for",
"module",
"in",
"disc_modules",
"(",
"root_name",
",",
"ignore_import_errors",
"=",
"ig... | 39.645161 | 0.002383 |
def wave_vectors(obj):
r"""
Validate if an object is a :ref:`WaveVectors` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by the name of the argument the
contract is atta... | [
"def",
"wave_vectors",
"(",
"obj",
")",
":",
"exdesc",
"=",
"pexdoc",
".",
"pcontracts",
".",
"get_exdesc",
"(",
")",
"if",
"not",
"isinstance",
"(",
"obj",
",",
"list",
")",
"or",
"(",
"isinstance",
"(",
"obj",
",",
"list",
")",
"and",
"not",
"obj",... | 35.826087 | 0.001182 |
def set_frame_parameters(self, profile_index: int, frame_parameters) -> None:
"""Set the frame parameters with the settings index and fire the frame parameters changed event.
If the settings index matches the current settings index, call set current frame parameters.
If the settings index matc... | [
"def",
"set_frame_parameters",
"(",
"self",
",",
"profile_index",
":",
"int",
",",
"frame_parameters",
")",
"->",
"None",
":",
"self",
".",
"frame_parameters_changed_event",
".",
"fire",
"(",
"profile_index",
",",
"frame_parameters",
")"
] | 58.875 | 0.012552 |
def sort(self, *args, **kwargs):
"""Sort the MultiMap.
Takes the same arguments as list.sort, and operates on tuples of
(key, value) pairs.
>>> m = MutableMultiMap()
>>> m['c'] = 1
>>> m['b'] = 3
>>> m['a'] = 2
>>> m.sort()
>>> m.... | [
"def",
"sort",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_pairs",
".",
"sort",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_rebuild_key_ids",
"(",
")"
] | 25.5 | 0.009452 |
def get(self, request, pk=None):
"""
GET request
"""
obj = self.get_object()
return Response(IdentitySerializer(obj).data) | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
")",
":",
"obj",
"=",
"self",
".",
"get_object",
"(",
")",
"return",
"Response",
"(",
"IdentitySerializer",
"(",
"obj",
")",
".",
"data",
")"
] | 26.166667 | 0.012346 |
def update_lxc_conf(name, lxc_conf, lxc_conf_unset, path=None):
'''
Edit LXC configuration options
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion lxc.update_lxc_c... | [
"def",
"update_lxc_conf",
"(",
"name",
",",
"lxc_conf",
",",
"lxc_conf_unset",
",",
"path",
"=",
"None",
")",
":",
"_ensure_exists",
"(",
"name",
",",
"path",
"=",
"path",
")",
"cpath",
"=",
"get_root_path",
"(",
"path",
")",
"lxc_conf_p",
"=",
"os",
"."... | 36.762376 | 0.000525 |
def calc_qbb_v1(self):
"""Calculate the amount of base flow released from the soil.
Required control parameters:
|NHRU|
|Lnk|
|Beta|
|FBeta|
Required derived parameter:
|WB|
|WZ|
Required state sequence:
|BoWa|
Calculated flux sequence:
|QBB|
... | [
"def",
"calc_qbb_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"der",
"=",
"self",
".",
"parameters",
".",
"derived",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"... | 35.079208 | 0.000274 |
def write_ping(self, data: bytes) -> None:
"""Send ping frame."""
assert isinstance(data, bytes)
self._write_frame(True, 0x9, data) | [
"def",
"write_ping",
"(",
"self",
",",
"data",
":",
"bytes",
")",
"->",
"None",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"_write_frame",
"(",
"True",
",",
"0x9",
",",
"data",
")"
] | 38 | 0.012903 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.