text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def show_guiref(self):
"""Show qtconsole help"""
from qtconsole.usage import gui_reference
self.main.help.show_rich_text(gui_reference, collapse=True) | [
"def",
"show_guiref",
"(",
"self",
")",
":",
"from",
"qtconsole",
".",
"usage",
"import",
"gui_reference",
"self",
".",
"main",
".",
"help",
".",
"show_rich_text",
"(",
"gui_reference",
",",
"collapse",
"=",
"True",
")"
] | 43.5 | 13.5 |
def nearly_unique(arr, rel_tol=1e-4, verbose=0):
'''Heuristic method to return the uniques within some precision in a numpy array'''
results = np.array([arr[0]])
for x in arr:
if np.abs(results - x).min() > rel_tol:
results = np.append(results, x)
return results | [
"def",
"nearly_unique",
"(",
"arr",
",",
"rel_tol",
"=",
"1e-4",
",",
"verbose",
"=",
"0",
")",
":",
"results",
"=",
"np",
".",
"array",
"(",
"[",
"arr",
"[",
"0",
"]",
"]",
")",
"for",
"x",
"in",
"arr",
":",
"if",
"np",
".",
"abs",
"(",
"res... | 41.714286 | 16.857143 |
def format(self, record):
'''
Format the log record to include exc_info if the handler is enabled for a specific log level
'''
formatted_record = super(ExcInfoOnLogLevelFormatMixIn, self).format(record)
exc_info_on_loglevel = getattr(record, 'exc_info_on_loglevel', None)
... | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"formatted_record",
"=",
"super",
"(",
"ExcInfoOnLogLevelFormatMixIn",
",",
"self",
")",
".",
"format",
"(",
"record",
")",
"exc_info_on_loglevel",
"=",
"getattr",
"(",
"record",
",",
"'exc_info_on_loglevel'... | 54.134615 | 29.711538 |
async def sendPhoto(self, chat_id, photo,
caption=None,
parse_mode=None,
disable_notification=None,
reply_to_message_id=None,
reply_markup=None):
"""
See: https://core.telegram.org/bot... | [
"async",
"def",
"sendPhoto",
"(",
"self",
",",
"chat_id",
",",
"photo",
",",
"caption",
"=",
"None",
",",
"parse_mode",
"=",
"None",
",",
"disable_notification",
"=",
"None",
",",
"reply_to_message_id",
"=",
"None",
",",
"reply_markup",
"=",
"None",
")",
"... | 46.684211 | 16.263158 |
def apply2parser(cmd_proxy, parser):
"""
Apply a CmdProxy's arguments and options
to a parser of argparse.
:type cmd_proxy: callable or CmdProxy
:type parser: cmdtree.parser.AParser
:rtype: cmdtree.parser.AParser
"""
if isinstance(cmd_proxy, CmdProxy):
parser_proxy = cmd_proxy.me... | [
"def",
"apply2parser",
"(",
"cmd_proxy",
",",
"parser",
")",
":",
"if",
"isinstance",
"(",
"cmd_proxy",
",",
"CmdProxy",
")",
":",
"parser_proxy",
"=",
"cmd_proxy",
".",
"meta",
".",
"parser",
"_apply2parser",
"(",
"parser_proxy",
".",
"arguments",
",",
"par... | 28.4375 | 8.5625 |
def parse_query(query_str):
"""
Drives the whole logic, by parsing, restructuring and finally, generating an ElasticSearch query.
Args:
query_str (six.text_types): the given query to be translated to an ElasticSearch query
Returns:
six.text_types: Return an ElasticSearch query.
No... | [
"def",
"parse_query",
"(",
"query_str",
")",
":",
"def",
"_generate_match_all_fields_query",
"(",
")",
":",
"# Strip colon character (special character for ES)",
"stripped_query_str",
"=",
"' '",
".",
"join",
"(",
"query_str",
".",
"replace",
"(",
"':'",
",",
"' '",
... | 39.027778 | 28.805556 |
def labels_to_indices(self, labels: Sequence[str]) -> List[int]:
""" Converts a sequence of labels into their corresponding indices."""
return [self.LABEL_TO_INDEX[label] for label in labels] | [
"def",
"labels_to_indices",
"(",
"self",
",",
"labels",
":",
"Sequence",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"int",
"]",
":",
"return",
"[",
"self",
".",
"LABEL_TO_INDEX",
"[",
"label",
"]",
"for",
"label",
"in",
"labels",
"]"
] | 51.25 | 21.75 |
def filter_uuid_list(stmts_in, uuids, **kwargs):
"""Filter to Statements corresponding to given UUIDs
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements to filter.
uuids : list[str]
A list of UUIDs to filter for.
save : Optional[str]
T... | [
"def",
"filter_uuid_list",
"(",
"stmts_in",
",",
"uuids",
",",
"*",
"*",
"kwargs",
")",
":",
"invert",
"=",
"kwargs",
".",
"get",
"(",
"'invert'",
",",
"False",
")",
"logger",
".",
"info",
"(",
"'Filtering %d statements for %d UUID%s...'",
"%",
"(",
"len",
... | 31.72973 | 17.27027 |
def on_notify_load_status(self, webkitView, *args, **kwargs):
"""Callback function when the page was loaded completely
FYI, this function will be called after $(document).ready()
in jQuery
"""
status = webkitView.get_load_status()
if status == status.FINISHED:
... | [
"def",
"on_notify_load_status",
"(",
"self",
",",
"webkitView",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"status",
"=",
"webkitView",
".",
"get_load_status",
"(",
")",
"if",
"status",
"==",
"status",
".",
"FINISHED",
":",
"if",
"self",
".",
... | 41.444444 | 9.777778 |
def _aside_from_xml(self, node, block_def_id, block_usage_id, id_generator):
"""
Create an aside from the xml and attach it to the given block
"""
id_generator = id_generator or self.id_generator
aside_type = node.tag
aside_class = self.load_aside_type(aside_type)
... | [
"def",
"_aside_from_xml",
"(",
"self",
",",
"node",
",",
"block_def_id",
",",
"block_usage_id",
",",
"id_generator",
")",
":",
"id_generator",
"=",
"id_generator",
"or",
"self",
".",
"id_generator",
"aside_type",
"=",
"node",
".",
"tag",
"aside_class",
"=",
"s... | 47.666667 | 24.333333 |
def create(self, chat_id=None, name=None, owner=None, user_list=None):
"""
创建群聊会话
详情请参考
https://work.weixin.qq.com/api/doc#90000/90135/90245
限制说明:
只允许企业自建应用调用,且应用的可见范围必须是根部门;
群成员人数不可超过管理端配置的“群成员人数上限”,且最大不可超过500人;
每企业创建群数不可超过1000/天;
:param chat_i... | [
"def",
"create",
"(",
"self",
",",
"chat_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"user_list",
"=",
"None",
")",
":",
"data",
"=",
"optionaldict",
"(",
"chatid",
"=",
"chat_id",
",",
"name",
"=",
"name",
",",
"own... | 30.72 | 19.36 |
def hello(environ, start_response):
'''The WSGI_ application handler which returns an iterable
over the "Hello World!" message.'''
if environ['REQUEST_METHOD'] == 'GET':
data = b'Hello World!\n'
status = '200 OK'
response_headers = [
('Content-type', 'text/plain'),
... | [
"def",
"hello",
"(",
"environ",
",",
"start_response",
")",
":",
"if",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"==",
"'GET'",
":",
"data",
"=",
"b'Hello World!\\n'",
"status",
"=",
"'200 OK'",
"response_headers",
"=",
"[",
"(",
"'Content-type'",
",",
"'text/p... | 33.928571 | 11.928571 |
def getQueryParams(url):
"""Get URL query parameters."""
query = urlsplit(url)[3]
out.debug(u'Extracting query parameters from %r (%r)...' % (url, query))
return cgi.parse_qs(query) | [
"def",
"getQueryParams",
"(",
"url",
")",
":",
"query",
"=",
"urlsplit",
"(",
"url",
")",
"[",
"3",
"]",
"out",
".",
"debug",
"(",
"u'Extracting query parameters from %r (%r)...'",
"%",
"(",
"url",
",",
"query",
")",
")",
"return",
"cgi",
".",
"parse_qs",
... | 38.6 | 14.8 |
def paginate_results(self, results, options):
"Return a django.core.paginator.Page of results."
limit = options.get('limit', settings.SELECTABLE_MAX_LIMIT)
paginator = Paginator(results, limit)
page = options.get('page', 1)
try:
results = paginator.page(page)
... | [
"def",
"paginate_results",
"(",
"self",
",",
"results",
",",
"options",
")",
":",
"limit",
"=",
"options",
".",
"get",
"(",
"'limit'",
",",
"settings",
".",
"SELECTABLE_MAX_LIMIT",
")",
"paginator",
"=",
"Paginator",
"(",
"results",
",",
"limit",
")",
"pag... | 42.4 | 12.2 |
def to_json(self):
"""
Returns a json string containing all relevant data to recreate this pyalveo.Client.
"""
data = dict(self.__dict__)
data.pop('context',None)
data['oauth'] = self.oauth.to_dict()
data['cache'] = self.cache.to_dict()
return json.dum... | [
"def",
"to_json",
"(",
"self",
")",
":",
"data",
"=",
"dict",
"(",
"self",
".",
"__dict__",
")",
"data",
".",
"pop",
"(",
"'context'",
",",
"None",
")",
"data",
"[",
"'oauth'",
"]",
"=",
"self",
".",
"oauth",
".",
"to_dict",
"(",
")",
"data",
"["... | 35.555556 | 12 |
def _connect(self):
"""Connect to the server."""
assert get_thread_ident() == self.ioloop_thread_id
if self._stream:
self._logger.warn('Disconnecting existing connection to {0!r} '
'to create a new connection')
self._disconnect()
... | [
"def",
"_connect",
"(",
"self",
")",
":",
"assert",
"get_thread_ident",
"(",
")",
"==",
"self",
".",
"ioloop_thread_id",
"if",
"self",
".",
"_stream",
":",
"self",
".",
"_logger",
".",
"warn",
"(",
"'Disconnecting existing connection to {0!r} '",
"'to create a new... | 46.689655 | 20.310345 |
def set_schema(self, schema_name, include_public=True):
"""
Main API method to current database schema,
but it does not actually modify the db connection.
"""
self.tenant = FakeTenant(schema_name=schema_name)
self.schema_name = schema_name
self.include_public_sche... | [
"def",
"set_schema",
"(",
"self",
",",
"schema_name",
",",
"include_public",
"=",
"True",
")",
":",
"self",
".",
"tenant",
"=",
"FakeTenant",
"(",
"schema_name",
"=",
"schema_name",
")",
"self",
".",
"schema_name",
"=",
"schema_name",
"self",
".",
"include_p... | 52.555556 | 16.666667 |
async def takewhile(source, func):
"""Forward an asynchronous sequence while a condition is met.
The given function takes the item as an argument and returns a boolean
corresponding to the condition to meet. The function can either be
synchronous or asynchronous.
"""
iscorofunc = asyncio.iscoro... | [
"async",
"def",
"takewhile",
"(",
"source",
",",
"func",
")",
":",
"iscorofunc",
"=",
"asyncio",
".",
"iscoroutinefunction",
"(",
"func",
")",
"async",
"with",
"streamcontext",
"(",
"source",
")",
"as",
"streamer",
":",
"async",
"for",
"item",
"in",
"strea... | 36.25 | 13.625 |
def init_discrete_hmm_spectral(C_full, nstates, reversible=True, stationary=True, active_set=None, P=None,
eps_A=None, eps_B=None, separate=None):
"""Initializes discrete HMM using spectral clustering of observation counts
Initializes HMM as described in [1]_. First estimates a M... | [
"def",
"init_discrete_hmm_spectral",
"(",
"C_full",
",",
"nstates",
",",
"reversible",
"=",
"True",
",",
"stationary",
"=",
"True",
",",
"active_set",
"=",
"None",
",",
"P",
"=",
"None",
",",
"eps_A",
"=",
"None",
",",
"eps_B",
"=",
"None",
",",
"separat... | 42.668605 | 24.540698 |
def _format_evidence_text(stmt):
"""Returns evidence metadata with highlighted evidence text.
Parameters
----------
stmt : indra.Statement
The Statement with Evidence to be formatted.
Returns
-------
list of dicts
List of dictionaries cor... | [
"def",
"_format_evidence_text",
"(",
"stmt",
")",
":",
"def",
"get_role",
"(",
"ag_ix",
")",
":",
"if",
"isinstance",
"(",
"stmt",
",",
"Complex",
")",
"or",
"isinstance",
"(",
"stmt",
",",
"SelfModification",
")",
"or",
"isinstance",
"(",
"stmt",
",",
"... | 43.8 | 18 |
def set_secure_boot_mode(self, secure_boot_enable):
"""Enable/Disable secure boot on the server.
:param secure_boot_enable: True, if secure boot needs to be
enabled for next boot, else False.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, i... | [
"def",
"set_secure_boot_mode",
"(",
"self",
",",
"secure_boot_enable",
")",
":",
"if",
"self",
".",
"_is_boot_mode_uefi",
"(",
")",
":",
"self",
".",
"_change_secure_boot_settings",
"(",
"'SecureBootEnable'",
",",
"secure_boot_enable",
")",
"else",
":",
"msg",
"="... | 47.3125 | 18.25 |
def _bias_scale(x, b, data_format):
"""The multiplication counter part of tf.nn.bias_add."""
if data_format == 'NHWC':
return x * b
elif data_format == 'NCHW':
return x * _to_channel_first_bias(b)
else:
raise ValueError('invalid data_format: %s' % data_format) | [
"def",
"_bias_scale",
"(",
"x",
",",
"b",
",",
"data_format",
")",
":",
"if",
"data_format",
"==",
"'NHWC'",
":",
"return",
"x",
"*",
"b",
"elif",
"data_format",
"==",
"'NCHW'",
":",
"return",
"x",
"*",
"_to_channel_first_bias",
"(",
"b",
")",
"else",
... | 36.625 | 13.125 |
def hicpro_mapping_chart (self):
""" Generate the HiC-Pro Aligned reads plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['Full_Alignments_Read'] = { 'color': '#005ce6', 'name': 'Full reads Alignments' }
keys['Trimmed_Alignments_Read']... | [
"def",
"hicpro_mapping_chart",
"(",
"self",
")",
":",
"# Specify the order of the different possible categories",
"keys",
"=",
"OrderedDict",
"(",
")",
"keys",
"[",
"'Full_Alignments_Read'",
"]",
"=",
"{",
"'color'",
":",
"'#005ce6'",
",",
"'name'",
":",
"'Full reads ... | 46.806452 | 26.387097 |
def send_keys(self, value, **kwargs):
self.debug_log("Sending keys")
highlight = kwargs.get(
'highlight',
BROME_CONFIG['highlight']['highlight_when_element_receive_keys'] # noqa
)
"""
wait_until_clickable = kwargs.get(
'wait_until_clickable',... | [
"def",
"send_keys",
"(",
"self",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"debug_log",
"(",
"\"Sending keys\"",
")",
"highlight",
"=",
"kwargs",
".",
"get",
"(",
"'highlight'",
",",
"BROME_CONFIG",
"[",
"'highlight'",
"]",
"[",
"'hig... | 30.509091 | 19.090909 |
def select(self, table, columns=None, join=None, where=None, group=None, having=None, order=None, limit=None,
iterator=False, fetch=True):
"""
:type table: string
:type columns: list
:type join: dict
:param join: {'[>]table1(t1)': {'user.id': 't1.user_id'}} -> "LEF... | [
"def",
"select",
"(",
"self",
",",
"table",
",",
"columns",
"=",
"None",
",",
"join",
"=",
"None",
",",
"where",
"=",
"None",
",",
"group",
"=",
"None",
",",
"having",
"=",
"None",
",",
"order",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"itera... | 39.918367 | 24.081633 |
def svm_predict(y, x, m, options=""):
"""
svm_predict(y, x, m [, options]) -> (p_labels, p_acc, p_vals)
y: a list/tuple/ndarray of l true labels (type must be int/double).
It is used for calculating the accuracy. Use [] if true labels are
unavailable.
x: 1. a list/tuple of l training instances. Feature ve... | [
"def",
"svm_predict",
"(",
"y",
",",
"x",
",",
"m",
",",
"options",
"=",
"\"\"",
")",
":",
"def",
"info",
"(",
"s",
")",
":",
"print",
"(",
"s",
")",
"if",
"scipy",
"and",
"isinstance",
"(",
"x",
",",
"scipy",
".",
"ndarray",
")",
":",
"x",
"... | 35.327869 | 23.688525 |
def build_image_in_privileged_container(build_image, source, image, parent_registry=None,
target_registries=None, push_buildroot_to=None,
parent_registry_insecure=False,
target_registries_insecure=Fal... | [
"def",
"build_image_in_privileged_container",
"(",
"build_image",
",",
"source",
",",
"image",
",",
"parent_registry",
"=",
"None",
",",
"target_registries",
"=",
"None",
",",
"push_buildroot_to",
"=",
"None",
",",
"parent_registry_insecure",
"=",
"False",
",",
"tar... | 58.258065 | 30.064516 |
def get_help_msg(self,
dotspace_ending=False, # type: bool
**kwargs):
# type: (...) -> str
"""
The method used to get the formatted help message according to kwargs. By default it returns the 'help_msg'
attribute, whether it is defined at the in... | [
"def",
"get_help_msg",
"(",
"self",
",",
"dotspace_ending",
"=",
"False",
",",
"# type: bool",
"*",
"*",
"kwargs",
")",
":",
"# type: (...) -> str",
"context",
"=",
"self",
".",
"get_context_for_help_msgs",
"(",
"kwargs",
")",
"if",
"self",
".",
"help_msg",
"i... | 42.717391 | 24.108696 |
def doTranslate(option, urlOrPaths, serverEndpoint=ServerEndpoint, verbose=Verbose, tikaServerJar=TikaServerJar,
responseMimeType='text/plain',
services={'all': '/translate/all'}):
'''
Translate the file from source language to destination language.
:param option:
:param... | [
"def",
"doTranslate",
"(",
"option",
",",
"urlOrPaths",
",",
"serverEndpoint",
"=",
"ServerEndpoint",
",",
"verbose",
"=",
"Verbose",
",",
"tikaServerJar",
"=",
"TikaServerJar",
",",
"responseMimeType",
"=",
"'text/plain'",
",",
"services",
"=",
"{",
"'all'",
":... | 37.117647 | 24.647059 |
def set_range_y(self,val):
""" Set visible range of y data.
Note: Padding must be 0 or it will create an infinite loop
"""
d = self.declaration
if d.auto_range[1]:
return
self.widget.setYRange(*val,padding=0) | [
"def",
"set_range_y",
"(",
"self",
",",
"val",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"if",
"d",
".",
"auto_range",
"[",
"1",
"]",
":",
"return",
"self",
".",
"widget",
".",
"setYRange",
"(",
"*",
"val",
",",
"padding",
"=",
"0",
")"
] | 27.8 | 15.6 |
def generate_output(self, writer):
"""
Generates the sitemap file and the stylesheet file and puts them into the content dir.
:param writer: the writer instance
:type writer: pelican.writers.Writer
"""
# write xml stylesheet
with codecs_open(os.path.join(os.path.d... | [
"def",
"generate_output",
"(",
"self",
",",
"writer",
")",
":",
"# write xml stylesheet",
"with",
"codecs_open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'sitemap-stylesheet.xsl'",
")",
",",
"... | 42.712871 | 24.49505 |
def parseEC2Json2List(jsontext, region):
"""
Takes a JSON and returns a list of InstanceType objects representing EC2 instance params.
:param jsontext:
:param region:
:return:
"""
currentList = json.loads(jsontext)
ec2InstanceList = []
for k, v in iteritems(currentList["products"]):... | [
"def",
"parseEC2Json2List",
"(",
"jsontext",
",",
"region",
")",
":",
"currentList",
"=",
"json",
".",
"loads",
"(",
"jsontext",
")",
"ec2InstanceList",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"currentList",
"[",
"\"products\"",
"]",
... | 55.885714 | 26.971429 |
def register_entity(self, entity_value, entity_type, alias_of=None, domain=0):
"""
Register an entity to be tagged in potential parse results.
Args:
entity_value(str): the value/proper name of an entity instance
(Ex: "The Big Bang Theory")
entity_type(str... | [
"def",
"register_entity",
"(",
"self",
",",
"entity_value",
",",
"entity_type",
",",
"alias_of",
"=",
"None",
",",
"domain",
"=",
"0",
")",
":",
"if",
"domain",
"not",
"in",
"self",
".",
"domains",
":",
"self",
".",
"register_domain",
"(",
"domain",
"=",... | 50.666667 | 23.733333 |
def write_byte(self, cmd, value):
"""
Writes an 8-bit byte to the specified command register
"""
self.bus.write_byte_data(self.address, cmd, value)
self.log.debug(
"write_byte: Wrote 0x%02X to command register 0x%02X" % (
value, cmd
)
... | [
"def",
"write_byte",
"(",
"self",
",",
"cmd",
",",
"value",
")",
":",
"self",
".",
"bus",
".",
"write_byte_data",
"(",
"self",
".",
"address",
",",
"cmd",
",",
"value",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"write_byte: Wrote 0x%02X to command regi... | 31.5 | 16.5 |
def plot_ellipse_matplotlib(cov, pos, ax, nstd=2, **kwargs):
"""
Plot 2d ellipse in 3d using matplotlib backend
"""
from matplotlib.patches import Ellipse
from mpl_toolkits.mplot3d import art3d, Axes3D
ellipse_param, normal = calc_2d_ellipse_properties(cov,nstd)
ellipse_kwds = merge_keywords... | [
"def",
"plot_ellipse_matplotlib",
"(",
"cov",
",",
"pos",
",",
"ax",
",",
"nstd",
"=",
"2",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"matplotlib",
".",
"patches",
"import",
"Ellipse",
"from",
"mpl_toolkits",
".",
"mplot3d",
"import",
"art3d",
",",
"Axe... | 36.714286 | 13 |
def quaternion_rotate(X, Y):
"""
Calculate the rotation
Parameters
----------
X : array
(N,D) matrix, where N is points and D is dimension.
Y: array
(N,D) matrix, where N is points and D is dimension.
Returns
-------
rot : matrix
Rotation matrix (D,D)
""... | [
"def",
"quaternion_rotate",
"(",
"X",
",",
"Y",
")",
":",
"N",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"W",
"=",
"np",
".",
"asarray",
"(",
"[",
"makeW",
"(",
"*",
"Y",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"range",
"(",
"N",
")",
"]",
")"... | 26.923077 | 18.846154 |
def createRecordSensor(network, name, dataSource):
"""
Creates a RecordSensor region that allows us to specify a file record
stream as the input source.
"""
# Specific type of region. Possible options can be found in /nupic/regions/
regionType = "py.RecordSensor"
# Creates a json from specified dictiona... | [
"def",
"createRecordSensor",
"(",
"network",
",",
"name",
",",
"dataSource",
")",
":",
"# Specific type of region. Possible options can be found in /nupic/regions/",
"regionType",
"=",
"\"py.RecordSensor\"",
"# Creates a json from specified dictionary.",
"regionParams",
"=",
"json"... | 34.84 | 20.04 |
def init_localization():
'''prepare l10n'''
locale.setlocale(locale.LC_ALL, '') # User's preferred locale, according to environment
# Use first two characters of country code, defaulting to 'en' in the absence of a preference
loc = locale.getlocale()
lang = loc[0][0:2] if loc[0] else 'en'
filen... | [
"def",
"init_localization",
"(",
")",
":",
"locale",
".",
"setlocale",
"(",
"locale",
".",
"LC_ALL",
",",
"''",
")",
"# User's preferred locale, according to environment",
"# Use first two characters of country code, defaulting to 'en' in the absence of a preference",
"loc",
"=",... | 38.058824 | 26.294118 |
def delete_record_set(self, record_set):
"""Append a record set to the 'deletions' for the change set.
:type record_set:
:class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:param record_set: the record set to append.
:raises: ``ValueError`` if ``record_set`` is... | [
"def",
"delete_record_set",
"(",
"self",
",",
"record_set",
")",
":",
"if",
"not",
"isinstance",
"(",
"record_set",
",",
"ResourceRecordSet",
")",
":",
"raise",
"ValueError",
"(",
"\"Pass a ResourceRecordSet\"",
")",
"self",
".",
"_deletions",
"+=",
"(",
"record... | 41.916667 | 17.75 |
def list(cls, params=None):
"""
Retrieves a list of the model
:param params: params as dictionary
:type params: dict
:return: the list of the parsed xml objects
:rtype: list
"""
return fields.ListField(name=cls.ENDPOINT, init_class=cls).decode(
... | [
"def",
"list",
"(",
"cls",
",",
"params",
"=",
"None",
")",
":",
"return",
"fields",
".",
"ListField",
"(",
"name",
"=",
"cls",
".",
"ENDPOINT",
",",
"init_class",
"=",
"cls",
")",
".",
"decode",
"(",
"cls",
".",
"element_from_string",
"(",
"cls",
".... | 31.833333 | 16.833333 |
def handle(self, env, start_response):
"""WSGI entry point for auth requests (ones that match the
self.auth_prefix).
Wraps env in swob.Request object and passes it down.
:param env: WSGI environment dictionary
:param start_response: WSGI callable
"""
try:
... | [
"def",
"handle",
"(",
"self",
",",
"env",
",",
"start_response",
")",
":",
"try",
":",
"req",
"=",
"Request",
"(",
"env",
")",
"if",
"self",
".",
"auth_prefix",
":",
"req",
".",
"path_info_pop",
"(",
")",
"req",
".",
"bytes_transferred",
"=",
"'-'",
... | 46.470588 | 14.794118 |
def or_fault(a, b, out, fault):
"""Returns True if OR(a, b) == out and fault == 0 or OR(a, b) != out and fault == 1."""
if (a or b) == out:
return fault == 0
else:
return fault == 1 | [
"def",
"or_fault",
"(",
"a",
",",
"b",
",",
"out",
",",
"fault",
")",
":",
"if",
"(",
"a",
"or",
"b",
")",
"==",
"out",
":",
"return",
"fault",
"==",
"0",
"else",
":",
"return",
"fault",
"==",
"1"
] | 34 | 14.5 |
def guess_payload_class(self, payload):
"""
Handles NTPv4 extensions and MAC part (when authentication is used.)
"""
plen = len(payload)
if plen > _NTP_AUTH_MD5_TAIL_SIZE:
return NTPExtensions
elif plen == _NTP_AUTH_MD5_TAIL_SIZE:
return NTPAuthen... | [
"def",
"guess_payload_class",
"(",
"self",
",",
"payload",
")",
":",
"plen",
"=",
"len",
"(",
"payload",
")",
"if",
"plen",
">",
"_NTP_AUTH_MD5_TAIL_SIZE",
":",
"return",
"NTPExtensions",
"elif",
"plen",
"==",
"_NTP_AUTH_MD5_TAIL_SIZE",
":",
"return",
"NTPAuthen... | 31.166667 | 13.833333 |
def gpio_interrupts_enable(self):
"""Enables GPIO interrupts."""
try:
bring_gpio_interrupt_into_userspace()
set_gpio_interrupt_edge()
except Timeout as e:
raise InterruptEnableException(
"There was an error bringing gpio%d into userspace. %s" %... | [
"def",
"gpio_interrupts_enable",
"(",
"self",
")",
":",
"try",
":",
"bring_gpio_interrupt_into_userspace",
"(",
")",
"set_gpio_interrupt_edge",
"(",
")",
"except",
"Timeout",
"as",
"e",
":",
"raise",
"InterruptEnableException",
"(",
"\"There was an error bringing gpio%d i... | 37.3 | 12.9 |
def utcnow(cls):
"""Return a new datetime representing UTC day and time."""
obj = datetime.datetime.utcnow()
obj = cls(obj, tzinfo=pytz.utc)
return obj | [
"def",
"utcnow",
"(",
"cls",
")",
":",
"obj",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
"obj",
"=",
"cls",
"(",
"obj",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"return",
"obj"
] | 32.6 | 11.8 |
def view_hmap(token, dstore):
"""
Display the highest 20 points of the mean hazard map. Called as
$ oq show hmap:0.1 # 10% PoE
"""
try:
poe = valid.probability(token.split(':')[1])
except IndexError:
poe = 0.1
mean = dict(extract(dstore, 'hcurves?kind=mean'))['mean']
oq ... | [
"def",
"view_hmap",
"(",
"token",
",",
"dstore",
")",
":",
"try",
":",
"poe",
"=",
"valid",
".",
"probability",
"(",
"token",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
")",
"except",
"IndexError",
":",
"poe",
"=",
"0.1",
"mean",
"=",
"dict",
... | 35.944444 | 13.277778 |
def _derive_namespaces(self):
'''
Small method to loop through three graphs in self.diffs, identify unique namespace URIs.
Then, loop through provided dictionary of prefixes and pin one to another.
Args:
None: uses self.prefixes and self.diffs
Returns:
None: sets self.update_namespaces and self.updat... | [
"def",
"_derive_namespaces",
"(",
"self",
")",
":",
"# iterate through graphs and get unique namespace uris",
"for",
"graph",
"in",
"[",
"self",
".",
"diffs",
".",
"overlap",
",",
"self",
".",
"diffs",
".",
"removed",
",",
"self",
".",
"diffs",
".",
"added",
"... | 36.457143 | 24.914286 |
def all_connected_components(i,j):
'''Associate each label in i with a component #
This function finds all connected components given an array of
associations between labels i and j using a depth-first search.
i & j give the edges of the graph. The first step of the algorithm makes
bidirec... | [
"def",
"all_connected_components",
"(",
"i",
",",
"j",
")",
":",
"if",
"len",
"(",
"i",
")",
"==",
"0",
":",
"return",
"i",
"i1",
"=",
"np",
".",
"hstack",
"(",
"(",
"i",
",",
"j",
")",
")",
"j1",
"=",
"np",
".",
"hstack",
"(",
"(",
"j",
",... | 38.419355 | 23.83871 |
def get_help(command):
"""
Get the Cmd help function from the click command
:param command: The click Command object
:return: the help_* method for Cmd
:rtype: function
"""
assert isinstance(command, click.Command)
def help_(self): # pylint: disable=unused-argument
extra = {}
... | [
"def",
"get_help",
"(",
"command",
")",
":",
"assert",
"isinstance",
"(",
"command",
",",
"click",
".",
"Command",
")",
"def",
"help_",
"(",
"self",
")",
":",
"# pylint: disable=unused-argument",
"extra",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
... | 32.285714 | 16.761905 |
def _pyxb_from_perm_dict(self, perm_dict):
"""Return an AccessPolicy PyXB representation of ``perm_dict``
- If ``norm_perm_list`` is empty, None is returned. The schema does not allow
AccessPolicy to be empty, but in SystemMetadata, it can be left out
altogether. So returning None inste... | [
"def",
"_pyxb_from_perm_dict",
"(",
"self",
",",
"perm_dict",
")",
":",
"norm_perm_list",
"=",
"self",
".",
"_norm_perm_list_from_perm_dict",
"(",
"perm_dict",
")",
"return",
"self",
".",
"_pyxb_from_norm_perm_list",
"(",
"norm_perm_list",
")"
] | 51.727273 | 26.181818 |
def load_facts(self, facts):
"""Load a set of facts into the CLIPS data base.
The C equivalent of the CLIPS load-facts command.
Facts can be loaded from a string or from a text file.
"""
facts = facts.encode()
if os.path.exists(facts):
ret = lib.EnvLoadFac... | [
"def",
"load_facts",
"(",
"self",
",",
"facts",
")",
":",
"facts",
"=",
"facts",
".",
"encode",
"(",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"facts",
")",
":",
"ret",
"=",
"lib",
".",
"EnvLoadFacts",
"(",
"self",
".",
"_env",
",",
"fact... | 28.1 | 19.55 |
def humanize_dates(p_due=None, p_start=None, p_creation=None):
"""
Returns string with humanized versions of p_due, p_start and p_creation.
Examples:
- all dates: "16 days ago, due in a month, started 2 days ago"
- p_due and p_start: "due in a month, started 2 days ago"
- p_creation and p_due: "... | [
"def",
"humanize_dates",
"(",
"p_due",
"=",
"None",
",",
"p_start",
"=",
"None",
",",
"p_creation",
"=",
"None",
")",
":",
"dates_list",
"=",
"[",
"]",
"if",
"p_creation",
":",
"dates_list",
".",
"append",
"(",
"humanize_date",
"(",
"p_creation",
")",
")... | 34.52381 | 18.047619 |
def get_short_uid_dict(self, query=None):
"""Create a dictionary of shortend UIDs for all contacts.
All arguments are only used if the address book is not yet initialized
and will just be handed to self.load().
:param query: see self.load()
:type query: str
:returns: th... | [
"def",
"get_short_uid_dict",
"(",
"self",
",",
"query",
"=",
"None",
")",
":",
"if",
"self",
".",
"_short_uids",
"is",
"None",
":",
"if",
"not",
"self",
".",
"_loaded",
":",
"self",
".",
"load",
"(",
"query",
")",
"if",
"not",
"self",
".",
"contacts"... | 46.621622 | 16.405405 |
def set_framebuffer_size_callback(window, cbfun):
"""
Sets the framebuffer resize callback for the specified window.
Wrapper for:
GLFWframebuffersizefun glfwSetFramebufferSizeCallback(GLFWwindow* window, GLFWframebuffersizefun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
... | [
"def",
"set_framebuffer_size_callback",
"(",
"window",
",",
"cbfun",
")",
":",
"window_addr",
"=",
"ctypes",
".",
"cast",
"(",
"ctypes",
".",
"pointer",
"(",
"window",
")",
",",
"ctypes",
".",
"POINTER",
"(",
"ctypes",
".",
"c_long",
")",
")",
".",
"cont... | 42.619048 | 22.047619 |
def from_series(cls, series, offset=0):
"""
Creates and return a Series from a Series
:param series: raccoon Series
:param offset: offset value must be provided as there is no equivalent for a DataFrame
:return: Series
"""
return cls(data=series.data, index=serie... | [
"def",
"from_series",
"(",
"cls",
",",
"series",
",",
"offset",
"=",
"0",
")",
":",
"return",
"cls",
"(",
"data",
"=",
"series",
".",
"data",
",",
"index",
"=",
"series",
".",
"index",
",",
"data_name",
"=",
"series",
".",
"data_name",
",",
"index_na... | 42.9 | 20.9 |
def parse_data_writer(self, node):
"""
Parses <DataWriter>
@param node: Node containing the <DataWriter> element
@type node: xml.etree.Element
"""
if 'path' in node.lattrib:
path = node.lattrib['path']
else:
self.raise_error('<DataWriter>... | [
"def",
"parse_data_writer",
"(",
"self",
",",
"node",
")",
":",
"if",
"'path'",
"in",
"node",
".",
"lattrib",
":",
"path",
"=",
"node",
".",
"lattrib",
"[",
"'path'",
"]",
"else",
":",
"self",
".",
"raise_error",
"(",
"'<DataWriter> must specify a path.'",
... | 30.95 | 18.95 |
def setup_logging(self, defaults=None):
"""
Set up logging via :func:`logging.config.fileConfig`.
Defaults are specified for the special ``__file__`` and ``here``
variables, similar to PasteDeploy config loading. Extra defaults can
optionally be specified as a dict in ``defaults... | [
"def",
"setup_logging",
"(",
"self",
",",
"defaults",
"=",
"None",
")",
":",
"if",
"\"loggers\"",
"in",
"self",
".",
"get_sections",
"(",
")",
":",
"defaults",
"=",
"self",
".",
"_get_defaults",
"(",
"defaults",
")",
"fileConfig",
"(",
"self",
".",
"uri"... | 36.315789 | 21.368421 |
def init_app(self, app, entry_point_group='invenio_oauth2server.scopes',
**kwargs):
"""Flask application initialization.
:param app: An instance of :class:`flask.Flask`.
:param entry_point_group: The entrypoint group name to load plugins.
(Default: ``'invenio_oauth2... | [
"def",
"init_app",
"(",
"self",
",",
"app",
",",
"entry_point_group",
"=",
"'invenio_oauth2server.scopes'",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"init_config",
"(",
"app",
")",
"state",
"=",
"_OAuth2ServerState",
"(",
"app",
",",
"entry_point_group"... | 37.214286 | 22.428571 |
def Enter(self, n = 1, dl = 0):
"""回车键/换行键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.enter_key, n) | [
"def",
"Enter",
"(",
"self",
",",
"n",
"=",
"1",
",",
"dl",
"=",
"0",
")",
":",
"self",
".",
"Delay",
"(",
"dl",
")",
"self",
".",
"keyboard",
".",
"tap_key",
"(",
"self",
".",
"keyboard",
".",
"enter_key",
",",
"n",
")"
] | 28.2 | 8.8 |
def gen_elem_array(size, elem_type=None):
"""
Generates element array of given size and initializes with given type.
Supports container type, used for pre-allocation before deserialization.
:param size:
:param elem_type:
:return:
"""
if elem_type is None or not callable(elem_type):
... | [
"def",
"gen_elem_array",
"(",
"size",
",",
"elem_type",
"=",
"None",
")",
":",
"if",
"elem_type",
"is",
"None",
"or",
"not",
"callable",
"(",
"elem_type",
")",
":",
"return",
"[",
"elem_type",
"]",
"*",
"size",
"if",
"is_type",
"(",
"elem_type",
",",
"... | 26.684211 | 18.684211 |
def BFS(G, start):
"""
Algorithm for breadth-first searching the vertices of a graph.
"""
if start not in G.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (start,))
color = {}
pred = {}
dist = {}
queue = Queue()
queue.put(start)
for vertex in G.v... | [
"def",
"BFS",
"(",
"G",
",",
"start",
")",
":",
"if",
"start",
"not",
"in",
"G",
".",
"vertices",
":",
"raise",
"GraphInsertError",
"(",
"\"Vertex %s doesn't exist.\"",
"%",
"(",
"start",
",",
")",
")",
"color",
"=",
"{",
"}",
"pred",
"=",
"{",
"}",
... | 30.68 | 13 |
def get_host(name):
"""
Prints the public dns name of `name`, if it exists.
:param name: The instance name.
:type name: ``str``
"""
f = {'instance-state-name': 'running', 'tag:Name': name}
ec2 = boto.connect_ec2(region=get_region())
rs = ec2.get_all_instances(filters=f)
if len(rs) =... | [
"def",
"get_host",
"(",
"name",
")",
":",
"f",
"=",
"{",
"'instance-state-name'",
":",
"'running'",
",",
"'tag:Name'",
":",
"name",
"}",
"ec2",
"=",
"boto",
".",
"connect_ec2",
"(",
"region",
"=",
"get_region",
"(",
")",
")",
"rs",
"=",
"ec2",
".",
"... | 31.692308 | 12.615385 |
def get_login_failed_count(name):
'''
Get the the number of failed login attempts
:param str name: The username of the account
:return: The number of failed login attempts
:rtype: int
:raises: CommandExecutionError on user not found or any other unknown error
CLI Example:
.. code-bl... | [
"def",
"get_login_failed_count",
"(",
"name",
")",
":",
"ret",
"=",
"_get_account_policy_data_value",
"(",
"name",
",",
"'failedLoginCount'",
")",
"return",
"salt",
".",
"utils",
".",
"mac_utils",
".",
"parse_return",
"(",
"ret",
")"
] | 24.55 | 26.35 |
def _generate_div_id_chart(prefix="chart_id", digits=8):
"""Generate a random id for div chart.
"""
choices = (random.randrange(0, 52) for _ in range(digits))
return prefix + "".join((string.ascii_letters[x] for x in choices)) | [
"def",
"_generate_div_id_chart",
"(",
"prefix",
"=",
"\"chart_id\"",
",",
"digits",
"=",
"8",
")",
":",
"choices",
"=",
"(",
"random",
".",
"randrange",
"(",
"0",
",",
"52",
")",
"for",
"_",
"in",
"range",
"(",
"digits",
")",
")",
"return",
"prefix",
... | 47.6 | 13.8 |
def add_spectrum(self, label, spectrum, color=None):
"""
Adds a Spectrum for plotting.
Args:
label (str): Label for the Spectrum. Must be unique.
spectrum: Spectrum object
color (str): This is passed on to matplotlib. E.g., "k--" indicates
a d... | [
"def",
"add_spectrum",
"(",
"self",
",",
"label",
",",
"spectrum",
",",
"color",
"=",
"None",
")",
":",
"self",
".",
"_spectra",
"[",
"label",
"]",
"=",
"spectrum",
"self",
".",
"colors",
".",
"append",
"(",
"color",
"or",
"self",
".",
"colors_cycle",
... | 38.8 | 16.933333 |
def rfc2822_format(val):
"""
Takes either a date, a datetime, or a string, and returns a string that
represents the value in RFC 2822 format. If a string is passed it is
returned unchanged.
"""
if isinstance(val, six.string_types):
return val
elif isinstance(val, (datetime.datetime, ... | [
"def",
"rfc2822_format",
"(",
"val",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"six",
".",
"string_types",
")",
":",
"return",
"val",
"elif",
"isinstance",
"(",
"val",
",",
"(",
"datetime",
".",
"datetime",
",",
"datetime",
".",
"date",
")",
")",
... | 32.75 | 14.75 |
def repair_broken_bonds(self, slab, bonds):
"""
This method will find undercoordinated atoms due to slab
cleaving specified by the bonds parameter and move them
to the other surface to make sure the bond is kept intact.
In a future release of surface.py, the ghost_sites will be
... | [
"def",
"repair_broken_bonds",
"(",
"self",
",",
"slab",
",",
"bonds",
")",
":",
"for",
"pair",
"in",
"bonds",
".",
"keys",
"(",
")",
":",
"blength",
"=",
"bonds",
"[",
"pair",
"]",
"# First lets determine which element should be the",
"# reference (center element)... | 46.042254 | 22.492958 |
def insert_strain_option_group_multi_ifo(parser):
"""
Adds the options used to call the pycbc.strain.from_cli function to an
optparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
OptionParser instance.
... | [
"def",
"insert_strain_option_group_multi_ifo",
"(",
"parser",
")",
":",
"data_reading_group_multi",
"=",
"parser",
".",
"add_argument_group",
"(",
"\"Options for obtaining\"",
"\" h(t)\"",
",",
"\"These options are used for generating h(t) either by \"",
"\"reading from a file or by ... | 56.48 | 27.234286 |
def data_filler_detailed_registration(self, number_of_rows, pipe):
'''creates keys with detailed regis. information
'''
try:
for i in range(number_of_rows):
pipe.hmset('detailed_registration:%s' % i, {
'id': rnd_id_generator(self),
... | [
"def",
"data_filler_detailed_registration",
"(",
"self",
",",
"number_of_rows",
",",
"pipe",
")",
":",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"number_of_rows",
")",
":",
"pipe",
".",
"hmset",
"(",
"'detailed_registration:%s'",
"%",
"i",
",",
"{",
"'id'"... | 41.9 | 20.6 |
def database(
state, host, name,
# Desired database settings
present=True,
collate=None, charset=None,
user=None, user_hostname='localhost', user_privileges='ALL',
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
... | [
"def",
"database",
"(",
"state",
",",
"host",
",",
"name",
",",
"# Desired database settings",
"present",
"=",
"True",
",",
"collate",
"=",
"None",
",",
"charset",
"=",
"None",
",",
"user",
"=",
"None",
",",
"user_hostname",
"=",
"'localhost'",
",",
"user_... | 30.71831 | 18.830986 |
def exactly_equal(self, other):
'''
Comparison between VariantCollection instances that takes into account
the info field of Variant instances.
Returns
----------
True if the variants in this collection equal the variants in the other
collection. The Variant.info... | [
"def",
"exactly_equal",
"(",
"self",
",",
"other",
")",
":",
"return",
"(",
"self",
".",
"__class__",
"==",
"other",
".",
"__class__",
"and",
"len",
"(",
"self",
")",
"==",
"len",
"(",
"other",
")",
"and",
"all",
"(",
"x",
".",
"exactly_equal",
"(",
... | 38.071429 | 23.642857 |
def delete_shard(self, project_name, logstore_name, shardId):
""" delete a readonly shard
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:param logstore_name: the ... | [
"def",
"delete_shard",
"(",
"self",
",",
"project_name",
",",
"logstore_name",
",",
"shardId",
")",
":",
"headers",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"resource",
"=",
"\"/logstores/\"",
"+",
"logstore_name",
"+",
"\"/shards/\"",
"+",
"str",
"(",
"sha... | 34.272727 | 18.954545 |
def license_present(name):
'''
Ensures that the specified PowerPath license key is present
on the host.
name
The license key to ensure is present
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if not __salt__['powerpath.has_... | [
"def",
"license_present",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"if",
"not",
"__salt__",
"[",
"'powerpath.has_powerpath'",
"]",
"... | 26.775 | 21.075 |
def _add_tasks(config, tasks_file, tasks_type, priority, redundancy):
"""Add tasks to a project."""
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
config.all)
data ... | [
"def",
"_add_tasks",
"(",
"config",
",",
"tasks_file",
",",
"tasks_type",
",",
"priority",
",",
"redundancy",
")",
":",
"try",
":",
"project",
"=",
"find_project_by_short_name",
"(",
"config",
".",
"project",
"[",
"'short_name'",
"]",
",",
"config",
".",
"pb... | 49.794118 | 19.588235 |
def next(self):
"""Return a column one by one
:raises: StopIteration
"""
if self._cur_col >= len(self._rec):
self._cur_col = 0
raise StopIteration
col = self._rec[self._cur_col]
self._cur_col += 1
return col | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cur_col",
">=",
"len",
"(",
"self",
".",
"_rec",
")",
":",
"self",
".",
"_cur_col",
"=",
"0",
"raise",
"StopIteration",
"col",
"=",
"self",
".",
"_rec",
"[",
"self",
".",
"_cur_col",
"]",
... | 25.272727 | 12.363636 |
def valUserCert(self, byts, cacerts=None):
'''
Validate the PEM encoded x509 user certificate bytes and return it.
Args:
byts (bytes): The bytes for the User Certificate.
cacerts (tuple): A tuple of OpenSSL.crypto.X509 CA Certificates.
Raises:
OpenSS... | [
"def",
"valUserCert",
"(",
"self",
",",
"byts",
",",
"cacerts",
"=",
"None",
")",
":",
"cert",
"=",
"crypto",
".",
"load_certificate",
"(",
"crypto",
".",
"FILETYPE_PEM",
",",
"byts",
")",
"if",
"cacerts",
"is",
"None",
":",
"cacerts",
"=",
"self",
"."... | 32.269231 | 27.269231 |
def process_ndex_neighborhood(gene_names, network_id=None,
rdf_out='bel_output.rdf', print_output=True):
"""Return a BelRdfProcessor for an NDEx network neighborhood.
Parameters
----------
gene_names : list
A list of HGNC gene symbols to search the neighborhood of.... | [
"def",
"process_ndex_neighborhood",
"(",
"gene_names",
",",
"network_id",
"=",
"None",
",",
"rdf_out",
"=",
"'bel_output.rdf'",
",",
"print_output",
"=",
"True",
")",
":",
"logger",
".",
"warning",
"(",
"'This method is deprecated and the results are not '",
"'guarantee... | 38.403846 | 22.057692 |
def delete_user_from_group(self, GroupID, UserID):
"""Delete a user from a group."""
# http://teampasswordmanager.com/docs/api-groups/#del_user
log.info('Delete user %s from group %s' % (UserID, GroupID))
self.put('groups/%s/delete_user/%s.json' % (GroupID, UserID)) | [
"def",
"delete_user_from_group",
"(",
"self",
",",
"GroupID",
",",
"UserID",
")",
":",
"# http://teampasswordmanager.com/docs/api-groups/#del_user",
"log",
".",
"info",
"(",
"'Delete user %s from group %s'",
"%",
"(",
"UserID",
",",
"GroupID",
")",
")",
"self",
".",
... | 58.8 | 18.6 |
def simplex_iterator(scale, boundary=True):
"""
Systematically iterates through a lattice of points on the 2-simplex.
Parameters
----------
scale: Int
The normalized scale of the simplex, i.e. N such that points (x,y,z)
satisify x + y + z == N
boundary: bool, True
Inclu... | [
"def",
"simplex_iterator",
"(",
"scale",
",",
"boundary",
"=",
"True",
")",
":",
"start",
"=",
"0",
"if",
"not",
"boundary",
":",
"start",
"=",
"1",
"for",
"i",
"in",
"range",
"(",
"start",
",",
"scale",
"+",
"(",
"1",
"-",
"start",
")",
")",
":"... | 27.407407 | 21.703704 |
def is_bare_exception(self, node):
"""
Checks if the node is a bare exception name from an except block.
"""
return isinstance(node, Name) and node.id in self.current_except_names | [
"def",
"is_bare_exception",
"(",
"self",
",",
"node",
")",
":",
"return",
"isinstance",
"(",
"node",
",",
"Name",
")",
"and",
"node",
".",
"id",
"in",
"self",
".",
"current_except_names"
] | 34.5 | 19.5 |
def summary(self):
"""Summary by packages and dependencies
"""
print("\nStatus summary")
print("=" * 79)
print("{0}found {1} dependencies in {2} packages.{3}\n".format(
self.grey, self.count_dep, self.count_pkg, self.endc)) | [
"def",
"summary",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nStatus summary\"",
")",
"print",
"(",
"\"=\"",
"*",
"79",
")",
"print",
"(",
"\"{0}found {1} dependencies in {2} packages.{3}\\n\"",
".",
"format",
"(",
"self",
".",
"grey",
",",
"self",
".",
"count_... | 38.428571 | 14.714286 |
def get_chunk(self,x,z):
"""
Return a chunk specified by the chunk coordinates x,z. Raise InconceivedChunk
if the chunk is not yet generated. To get the raw NBT data, use get_nbt.
"""
return self.chunkclass(self.get_nbt(x, z)) | [
"def",
"get_chunk",
"(",
"self",
",",
"x",
",",
"z",
")",
":",
"return",
"self",
".",
"chunkclass",
"(",
"self",
".",
"get_nbt",
"(",
"x",
",",
"z",
")",
")"
] | 43.5 | 18.5 |
def save(self, path):
"""Save the specification of this MLPipeline in a JSON file.
The content of the JSON file is the dict returned by the `to_dict` method.
Args:
path (str): Path to the JSON file to write.
"""
with open(path, 'w') as out_file:
json.dum... | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"out_file",
":",
"json",
".",
"dump",
"(",
"self",
".",
"to_dict",
"(",
")",
",",
"out_file",
",",
"indent",
"=",
"4",
")"
] | 34.8 | 20.1 |
def get_template_sources(self, template_name, template_dirs=None):
"""
Return the absolute paths to "template_name" in the specified app
If the name does not contain an app name (no colon), an empty list
is returned.
The parent FilesystemLoader.load_template_source() will take ca... | [
"def",
"get_template_sources",
"(",
"self",
",",
"template_name",
",",
"template_dirs",
"=",
"None",
")",
":",
"if",
"':'",
"not",
"in",
"template_name",
":",
"return",
"[",
"]",
"app_name",
",",
"template_name",
"=",
"template_name",
".",
"split",
"(",
"\":... | 43.333333 | 18.533333 |
def docker_fabric(*args, **kwargs):
"""
:param args: Positional arguments to Docker client.
:param kwargs: Keyword arguments to Docker client.
:return: Docker client.
:rtype: dockerfabric.apiclient.DockerFabricClient | dockerfabric.cli.DockerCliClient
"""
ci = kwargs.get('client_implementati... | [
"def",
"docker_fabric",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ci",
"=",
"kwargs",
".",
"get",
"(",
"'client_implementation'",
")",
"or",
"env",
".",
"get",
"(",
"'docker_fabric_implementation'",
")",
"or",
"CLIENT_API",
"if",
"ci",
"==",
... | 43.538462 | 16 |
def indexed_sum_over_const(cls, ops, kwargs):
r'''Execute an indexed sum over a term that does not depend on the
summation indices
.. math::
\sum_{j=1}^{N} a = N a
>>> a = symbols('a')
>>> i, j = (IdxSym(s) for s in ('i', 'j'))
>>> unicode(Sum(i, 1, 2)(a))
'2 a'
>>> unicode(S... | [
"def",
"indexed_sum_over_const",
"(",
"cls",
",",
"ops",
",",
"kwargs",
")",
":",
"term",
",",
"",
"*",
"ranges",
"=",
"ops",
"new_ranges",
"=",
"[",
"]",
"new_term",
"=",
"term",
"for",
"r",
"in",
"ranges",
":",
"if",
"r",
".",
"index_symbol",
"not"... | 25.933333 | 19.266667 |
def data_and_labels(self):
"""
Dataset features and labels in a matrix form for learning.
Also returns sample_ids in the same order.
Returns
-------
data_matrix : ndarray
2D array of shape [num_samples, num_features]
with features corresponding r... | [
"def",
"data_and_labels",
"(",
"self",
")",
":",
"sample_ids",
"=",
"np",
".",
"array",
"(",
"self",
".",
"keys",
")",
"label_dict",
"=",
"self",
".",
"labels",
"matrix",
"=",
"np",
".",
"full",
"(",
"[",
"self",
".",
"num_samples",
",",
"self",
".",... | 33.185185 | 19.333333 |
def write(self, message):
"""
(coroutine)
Write a single message into the pipe.
"""
if self.done_f.done():
raise BrokenPipeError
try:
yield From(write_message_to_pipe(self.pipe_instance.pipe_handle, message))
except BrokenPipeError:
... | [
"def",
"write",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"done_f",
".",
"done",
"(",
")",
":",
"raise",
"BrokenPipeError",
"try",
":",
"yield",
"From",
"(",
"write_message_to_pipe",
"(",
"self",
".",
"pipe_instance",
".",
"pipe_handle",
... | 27.692308 | 15.692308 |
def is_job_complete(job_id, conn=None):
"""
is_job_done function checks to if Brain.Jobs Status is Completed
Completed is defined in statics as Done|Stopped|Error
:param job_id: <str> id for the job
:param conn: (optional)<connection> to run on
:return: <dict> if job is done <false> if
"""... | [
"def",
"is_job_complete",
"(",
"job_id",
",",
"conn",
"=",
"None",
")",
":",
"result",
"=",
"False",
"job",
"=",
"RBJ",
".",
"get",
"(",
"job_id",
")",
".",
"run",
"(",
"conn",
")",
"if",
"job",
"and",
"job",
".",
"get",
"(",
"STATUS_FIELD",
")",
... | 30.066667 | 14.733333 |
def _createTimeSeriesObjects(self, timeSeries, filename):
"""
Create GSSHAPY TimeSeries and TimeSeriesValue Objects Method
"""
try:
# Determine number of value columns
valColumns = len(timeSeries[0]['values'])
# Create List of GSSHAPY TimeSeries objec... | [
"def",
"_createTimeSeriesObjects",
"(",
"self",
",",
"timeSeries",
",",
"filename",
")",
":",
"try",
":",
"# Determine number of value columns",
"valColumns",
"=",
"len",
"(",
"timeSeries",
"[",
"0",
"]",
"[",
"'values'",
"]",
")",
"# Create List of GSSHAPY TimeSeri... | 40.071429 | 19.571429 |
def _get_index(self):
"""
Get the guideline's index.
This must return an ``int``.
Subclasses may override this method.
"""
glyph = self.glyph
if glyph is not None:
parent = glyph
else:
parent = self.font
if parent is None:
... | [
"def",
"_get_index",
"(",
"self",
")",
":",
"glyph",
"=",
"self",
".",
"glyph",
"if",
"glyph",
"is",
"not",
"None",
":",
"parent",
"=",
"glyph",
"else",
":",
"parent",
"=",
"self",
".",
"font",
"if",
"parent",
"is",
"None",
":",
"return",
"None",
"... | 24.933333 | 12.266667 |
def build_global(self, global_node):
"""parse `global` section, and return the config.Global
Args:
global_node (TreeNode): `global` section treenode
Returns:
config.Global: an object
"""
config_block_lines = self.__build_config_block(
globa... | [
"def",
"build_global",
"(",
"self",
",",
"global_node",
")",
":",
"config_block_lines",
"=",
"self",
".",
"__build_config_block",
"(",
"global_node",
".",
"config_block",
")",
"return",
"config",
".",
"Global",
"(",
"config_block",
"=",
"config_block_lines",
")"
] | 30 | 18.461538 |
def BytesDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a bytes field."""
local_DecodeVarint = _DecodeVarint
assert not is_packed
if is_repeated:
tag_bytes = encoder.TagBytes(field_number,
wire_format.WIRETYPE_LENGTH_DELIMITED)
... | [
"def",
"BytesDecoder",
"(",
"field_number",
",",
"is_repeated",
",",
"is_packed",
",",
"key",
",",
"new_default",
")",
":",
"local_DecodeVarint",
"=",
"_DecodeVarint",
"assert",
"not",
"is_packed",
"if",
"is_repeated",
":",
"tag_bytes",
"=",
"encoder",
".",
"Tag... | 37.057143 | 17.057143 |
def data_request(self, payload, timeout=TIMEOUT):
"""Perform a data_request and return the result."""
request_url = self.base_url + "/data_request"
return requests.get(request_url, timeout=timeout, params=payload) | [
"def",
"data_request",
"(",
"self",
",",
"payload",
",",
"timeout",
"=",
"TIMEOUT",
")",
":",
"request_url",
"=",
"self",
".",
"base_url",
"+",
"\"/data_request\"",
"return",
"requests",
".",
"get",
"(",
"request_url",
",",
"timeout",
"=",
"timeout",
",",
... | 58.5 | 13.75 |
def map(self, callable):
""" Apply 'callable' function over all values. """
for k,v in self.iteritems():
self[k] = callable(v) | [
"def",
"map",
"(",
"self",
",",
"callable",
")",
":",
"for",
"k",
",",
"v",
"in",
"self",
".",
"iteritems",
"(",
")",
":",
"self",
"[",
"k",
"]",
"=",
"callable",
"(",
"v",
")"
] | 37.75 | 6.75 |
def p_static_scalar_unary_op(p):
'''static_scalar : PLUS static_scalar
| MINUS static_scalar'''
p[0] = ast.UnaryOp(p[1], p[2], lineno=p.lineno(1)) | [
"def",
"p_static_scalar_unary_op",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"UnaryOp",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 43 | 7 |
def getResponse(self, context=""):
""" Poll for finished block or first byte ACK.
Args:
context (str): internal serial call context.
Returns:
string: Response, implict cast from byte array.
"""
waits = 0 # allowed interval counter
response_str = ... | [
"def",
"getResponse",
"(",
"self",
",",
"context",
"=",
"\"\"",
")",
":",
"waits",
"=",
"0",
"# allowed interval counter",
"response_str",
"=",
"\"\"",
"# returned bytes in string default",
"try",
":",
"waits",
"=",
"0",
"# allowed interval counter",
"while",
"(",
... | 40.625 | 17.78125 |
def close(self):
"""
Mark the latch as closed, and cause every sleeping thread to be woken,
with :class:`mitogen.core.LatchError` raised in each thread.
"""
self._lock.acquire()
try:
self.closed = True
while self._waking < len(self._sleeping):
... | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"closed",
"=",
"True",
"while",
"self",
".",
"_waking",
"<",
"len",
"(",
"self",
".",
"_sleeping",
")",
":",
"wsock",
",",
"cookie",
"... | 34.928571 | 15.214286 |
def build_distribution():
"""Build distributions of the code."""
result = invoke.run('python setup.py sdist bdist_egg bdist_wheel',
warn=True, hide=True)
if result.ok:
print("[{}GOOD{}] Distribution built without errors."
.format(GOOD_COLOR, RESET_COLOR))
el... | [
"def",
"build_distribution",
"(",
")",
":",
"result",
"=",
"invoke",
".",
"run",
"(",
"'python setup.py sdist bdist_egg bdist_wheel'",
",",
"warn",
"=",
"True",
",",
"hide",
"=",
"True",
")",
"if",
"result",
".",
"ok",
":",
"print",
"(",
"\"[{}GOOD{}] Distribu... | 40.583333 | 17.416667 |
def generate_unique_key(master_key_path, url):
"""
Input1: Path to the BD2K Master Key (for S3 Encryption)
Input2: S3 URL (e.g. https://s3-us-west-2.amazonaws.com/cgl-driver-projects-encrypted/wcdt/exome_bams/DTB-111-N.bam)
Returns: 32-byte unique key generated for that URL
"""
with open(master... | [
"def",
"generate_unique_key",
"(",
"master_key_path",
",",
"url",
")",
":",
"with",
"open",
"(",
"master_key_path",
",",
"'r'",
")",
"as",
"f",
":",
"master_key",
"=",
"f",
".",
"read",
"(",
")",
"assert",
"len",
"(",
"master_key",
")",
"==",
"32",
","... | 49.785714 | 24.928571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.