text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def chrono(ctx, app_id, sentence_file,
json_flag, sentence, doc_time, request_id):
# type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA
"""Extract expression expressing date and time and normalize its value """
app_id = clean_app_id(app_id)
sentence = cle... | [
"def",
"chrono",
"(",
"ctx",
",",
"app_id",
",",
"sentence_file",
",",
"json_flag",
",",
"sentence",
",",
"doc_time",
",",
"request_id",
")",
":",
"# type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA",
"app_id",
"=",
"clean_app_id",
"... | 31.809524 | 20.952381 |
def _CreateCampaignGroup(client):
"""Create a campaign group.
Args:
client: an AdWordsClient instance.
Returns:
The integer ID of the created campaign group.
"""
# Get the CampaignGroupService.
campaign_group_service = client.GetService('CampaignGroupService',
... | [
"def",
"_CreateCampaignGroup",
"(",
"client",
")",
":",
"# Get the CampaignGroupService.",
"campaign_group_service",
"=",
"client",
".",
"GetService",
"(",
"'CampaignGroupService'",
",",
"version",
"=",
"'v201809'",
")",
"# Create the operation.",
"operations",
"=",
"[",
... | 26.733333 | 21.6 |
async def _check_subscriptions(self):
"""
Checks that all subscriptions are subscribed
"""
subscribed, url = await self._get_subscriptions()
expect = set(settings.FACEBOOK_SUBSCRIPTIONS)
if (expect - subscribed) or url != self.webhook_url:
await self._set_su... | [
"async",
"def",
"_check_subscriptions",
"(",
"self",
")",
":",
"subscribed",
",",
"url",
"=",
"await",
"self",
".",
"_get_subscriptions",
"(",
")",
"expect",
"=",
"set",
"(",
"settings",
".",
"FACEBOOK_SUBSCRIPTIONS",
")",
"if",
"(",
"expect",
"-",
"subscrib... | 36.769231 | 18.153846 |
def seek_read(path, size, offset):
'''
.. versionadded:: 2014.1.0
Seek to a position on a file and read it
path
path to file
seek
amount to read at once
offset
offset to start into the file
CLI Example:
.. code-block:: bash
salt '*' file.seek_read /... | [
"def",
"seek_read",
"(",
"path",
",",
"size",
",",
"offset",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"path",
")",
"seek_fh",
"=",
"os",
".",
"open",
"(",
"path",
",",
"os",
".",
"O_RDONLY",
")",
"try",
":",
"os",
".",
... | 18.793103 | 22.517241 |
def set_information(self, title=None, subject=None, author=None, keywords=None, creator=None):
""" Convenience function to add property info, can set any attribute and leave the others blank, it won't over-write
previously set items. """
info_dict = {"title": title, "subject": subject,
... | [
"def",
"set_information",
"(",
"self",
",",
"title",
"=",
"None",
",",
"subject",
"=",
"None",
",",
"author",
"=",
"None",
",",
"keywords",
"=",
"None",
",",
"creator",
"=",
"None",
")",
":",
"info_dict",
"=",
"{",
"\"title\"",
":",
"title",
",",
"\"... | 48.615385 | 14.538462 |
def _look_for_interface(self, network_backend):
"""
Look for an interface with a specific network backend.
:returns: interface number or -1 if none is found
"""
result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"])
interface = -1
f... | [
"def",
"_look_for_interface",
"(",
"self",
",",
"network_backend",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"_execute",
"(",
"\"showvminfo\"",
",",
"[",
"self",
".",
"_vmname",
",",
"\"--machinereadable\"",
"]",
")",
"interface",
"=",
"-",
"1",... | 36.578947 | 16.894737 |
def QPSK_rx(fc,N_symb,Rs,EsN0=100,fs=125,lfsr_len=10,phase=0,pulse='src'):
"""
This function generates
"""
Ns = int(np.round(fs/Rs))
print('Ns = ', Ns)
print('Rs = ', fs/float(Ns))
print('EsN0 = ', EsN0, 'dB')
print('phase = ', phase, 'degrees')
print('pulse = ', pulse)
x, b, dat... | [
"def",
"QPSK_rx",
"(",
"fc",
",",
"N_symb",
",",
"Rs",
",",
"EsN0",
"=",
"100",
",",
"fs",
"=",
"125",
",",
"lfsr_len",
"=",
"10",
",",
"phase",
"=",
"0",
",",
"pulse",
"=",
"'src'",
")",
":",
"Ns",
"=",
"int",
"(",
"np",
".",
"round",
"(",
... | 31.4375 | 12.8125 |
def _get_permission_description(permission_name):
""" Generate a descriptive string based on the permission name.
For example: 'resource_Order_get' -> 'Can GET order'
todo: add support for the resource name to have underscores
"""
parts = permission_name.split('_')
parts.pop(0)
method =... | [
"def",
"_get_permission_description",
"(",
"permission_name",
")",
":",
"parts",
"=",
"permission_name",
".",
"split",
"(",
"'_'",
")",
"parts",
".",
"pop",
"(",
"0",
")",
"method",
"=",
"parts",
".",
"pop",
"(",
")",
"resource",
"=",
"(",
"'_'",
".",
... | 31.769231 | 17.153846 |
def parse_column(column):
"""
Helper method for DataTable.fromcsvstring()
Given a list, parse_column tries to see if it should cast
everything in that list to a float, an int, or leave it as is.
Always returns a list.
"""
try:
float_attempt = [float(i) for i in column]
except V... | [
"def",
"parse_column",
"(",
"column",
")",
":",
"try",
":",
"float_attempt",
"=",
"[",
"float",
"(",
"i",
")",
"for",
"i",
"in",
"column",
"]",
"except",
"ValueError",
":",
"return",
"column",
"else",
":",
"try",
":",
"int_attempt",
"=",
"[",
"int",
... | 25.6 | 18.5 |
def detect_language(
self,
parent=None,
model=None,
content=None,
mime_type=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Detects the language of text within ... | [
"def",
"detect_language",
"(",
"self",
",",
"parent",
"=",
"None",
",",
"model",
"=",
"None",
",",
"content",
"=",
"None",
",",
"mime_type",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",... | 42.604651 | 25.093023 |
def snmp_server_view_viewname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp")
view = ET.SubElement(snmp_server, "view")
mibtree_key = ET.SubElement(view... | [
"def",
"snmp_server_view_viewname",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"snmp_server",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"snmp-server\"",
",",
"xmlns",
"=",
"\"urn:b... | 42.923077 | 13.923077 |
def _iparam_objectname(objectname, arg_name):
"""
Convert an object name (= class or instance name) specified in an
operation method into a CIM object that can be passed to
imethodcall().
"""
if isinstance(objectname, (CIMClassName, CIMInstanceName)):
objectn... | [
"def",
"_iparam_objectname",
"(",
"objectname",
",",
"arg_name",
")",
":",
"if",
"isinstance",
"(",
"objectname",
",",
"(",
"CIMClassName",
",",
"CIMInstanceName",
")",
")",
":",
"objectname",
"=",
"objectname",
".",
"copy",
"(",
")",
"objectname",
".",
"hos... | 40.454545 | 16.818182 |
def make_gpg_home(appname, config_dir=None):
"""
Make GPG keyring dir for a particular application.
Return the path.
"""
assert is_valid_appname(appname)
config_dir = get_config_dir( config_dir )
path = os.path.join( config_dir, "gpgkeys", appname )
if not os.path.exists(path):
... | [
"def",
"make_gpg_home",
"(",
"appname",
",",
"config_dir",
"=",
"None",
")",
":",
"assert",
"is_valid_appname",
"(",
"appname",
")",
"config_dir",
"=",
"get_config_dir",
"(",
"config_dir",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"config_dir",
... | 24.3125 | 16.5625 |
def on_recv_rsp(self, rsp_pb):
"""receive response callback function"""
ret_code, msg, conn_info_map = InitConnect.unpack_rsp(rsp_pb)
if self._notify_obj is not None:
self._notify_obj.on_async_init_connect(ret_code, msg, conn_info_map)
return ret_code, msg | [
"def",
"on_recv_rsp",
"(",
"self",
",",
"rsp_pb",
")",
":",
"ret_code",
",",
"msg",
",",
"conn_info_map",
"=",
"InitConnect",
".",
"unpack_rsp",
"(",
"rsp_pb",
")",
"if",
"self",
".",
"_notify_obj",
"is",
"not",
"None",
":",
"self",
".",
"_notify_obj",
"... | 36.875 | 21.375 |
def handle_error(self, error, req, schema, error_status_code, error_headers):
"""Handles errors during parsing. Raises a `tornado.web.HTTPError`
with a 400 error.
"""
status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS
if status_code == 422:
reason = "Un... | [
"def",
"handle_error",
"(",
"self",
",",
"error",
",",
"req",
",",
"schema",
",",
"error_status_code",
",",
"error_headers",
")",
":",
"status_code",
"=",
"error_status_code",
"or",
"self",
".",
"DEFAULT_VALIDATION_STATUS",
"if",
"status_code",
"==",
"422",
":",... | 35.5 | 14.4375 |
def plot(args):
"""
%prog plot workdir sample chr1,chr2
Plot some chromosomes for visual proof. Separate multiple chromosomes with
comma. Must contain folder workdir/sample-cn/.
"""
from jcvi.graphics.base import savefig
p = OptionParser(plot.__doc__)
opts, args, iopts = p.set_image_op... | [
"def",
"plot",
"(",
"args",
")",
":",
"from",
"jcvi",
".",
"graphics",
".",
"base",
"import",
"savefig",
"p",
"=",
"OptionParser",
"(",
"plot",
".",
"__doc__",
")",
"opts",
",",
"args",
",",
"iopts",
"=",
"p",
".",
"set_image_options",
"(",
"args",
"... | 29.409091 | 17.590909 |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the KeyWrappingData struct and decode it into
its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read... | [
"def",
"read",
"(",
"self",
",",
"input_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"KeyWrappingData",
",",
"self",
")",
".",
"read",
"(",
"input_stream",
",",
"kmip_version",
"=",
"kmip_version",
... | 35.691358 | 18.654321 |
def __parse_comments():
'''Gets and parses file'''
filename = get_file('comments.tsv')
with io.open(filename, 'r', encoding='cp1252') as textfile:
next(textfile)
for line in textfile:
tokens = line.strip().split('\t')
chebi_id = int(tokens[1])
if chebi_... | [
"def",
"__parse_comments",
"(",
")",
":",
"filename",
"=",
"get_file",
"(",
"'comments.tsv'",
")",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'r'",
",",
"encoding",
"=",
"'cp1252'",
")",
"as",
"textfile",
":",
"next",
"(",
"textfile",
")",
"for",
... | 29.904762 | 16.857143 |
def check_sets(self):
'''
Check grammar
'''
lhs_set = set()
rhs_set = set()
rhs_rules_set = {}
token_set = set()
right_recursive = set()
dup_rhs = {}
for lhs in self.rules:
rules_for_lhs = self.rules[lhs]... | [
"def",
"check_sets",
"(",
"self",
")",
":",
"lhs_set",
"=",
"set",
"(",
")",
"rhs_set",
"=",
"set",
"(",
")",
"rhs_rules_set",
"=",
"{",
"}",
"token_set",
"=",
"set",
"(",
")",
"right_recursive",
"=",
"set",
"(",
")",
"dup_rhs",
"=",
"{",
"}",
"for... | 34.581395 | 14.395349 |
def restore(self, state):
"""Restore the contents of this virtual stream walker.
Args:
state (dict): The previously serialized state.
Raises:
ArgumentError: If the serialized state does not have
a matching selector.
"""
reading = state.g... | [
"def",
"restore",
"(",
"self",
",",
"state",
")",
":",
"reading",
"=",
"state",
".",
"get",
"(",
"u'reading'",
")",
"if",
"reading",
"is",
"not",
"None",
":",
"reading",
"=",
"IOTileReading",
".",
"FromDict",
"(",
"reading",
")",
"selector",
"=",
"Data... | 34.619048 | 22.952381 |
def submission_successful(self, participant):
"""Run when a participant submits successfully."""
key = participant.uniqueid[0:5]
finished_participants = Participant.query.filter_by(status=101).all()
num_finished_participants = len(finished_participants)
current_generation = int(... | [
"def",
"submission_successful",
"(",
"self",
",",
"participant",
")",
":",
"key",
"=",
"participant",
".",
"uniqueid",
"[",
"0",
":",
"5",
"]",
"finished_participants",
"=",
"Participant",
".",
"query",
".",
"filter_by",
"(",
"status",
"=",
"101",
")",
"."... | 49.652174 | 21.478261 |
def _validate_instantiation_options(self, datafile, skip_json_validation):
""" Helper method to validate all instantiation parameters.
Args:
datafile: JSON string representing the project.
skip_json_validation: Boolean representing whether JSON schema validation needs to be skipped or not.
Rai... | [
"def",
"_validate_instantiation_options",
"(",
"self",
",",
"datafile",
",",
"skip_json_validation",
")",
":",
"if",
"not",
"skip_json_validation",
"and",
"not",
"validator",
".",
"is_datafile_valid",
"(",
"datafile",
")",
":",
"raise",
"exceptions",
".",
"InvalidIn... | 47.5 | 35.227273 |
def getWindow(self):
""" Returns the title of the main window of the currently open app.
Returns an empty string if no match could be found.
"""
if self.getPID() != -1:
return PlatformManager.getWindowTitle(PlatformManager.getWindowByPID(self.getPID()))
else:
... | [
"def",
"getWindow",
"(",
"self",
")",
":",
"if",
"self",
".",
"getPID",
"(",
")",
"!=",
"-",
"1",
":",
"return",
"PlatformManager",
".",
"getWindowTitle",
"(",
"PlatformManager",
".",
"getWindowByPID",
"(",
"self",
".",
"getPID",
"(",
")",
")",
")",
"e... | 36.222222 | 21.111111 |
def extend(self, elem_seq):
"""Extends by appending the given sequence of elements of the same type
as this one, copying each individual message.
"""
message_class = self._message_descriptor._concrete_class
listener = self._message_listener
values = self._values
for message in elem_seq:
... | [
"def",
"extend",
"(",
"self",
",",
"elem_seq",
")",
":",
"message_class",
"=",
"self",
".",
"_message_descriptor",
".",
"_concrete_class",
"listener",
"=",
"self",
".",
"_message_listener",
"values",
"=",
"self",
".",
"_values",
"for",
"message",
"in",
"elem_s... | 36.461538 | 8.153846 |
def commit():
""" Commit changes and release the write lock """
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return... | [
"def",
"commit",
"(",
")",
":",
"session_token",
"=",
"request",
".",
"headers",
"[",
"'session_token'",
"]",
"repository",
"=",
"request",
".",
"headers",
"[",
"'repository'",
"]",
"#===",
"current_user",
"=",
"have_authenticated_user",
"(",
"request",
".",
"... | 35.451613 | 26.193548 |
def configure(logstash_host=None, logstash_port=None, logdir=None):
'''Configuration settings.'''
if not (logstash_host or logstash_port or logdir):
raise ValueError('you must specify at least one parameter')
config.logstash.host = logstash_host or config.logstash.host
config.logstash.port = l... | [
"def",
"configure",
"(",
"logstash_host",
"=",
"None",
",",
"logstash_port",
"=",
"None",
",",
"logdir",
"=",
"None",
")",
":",
"if",
"not",
"(",
"logstash_host",
"or",
"logstash_port",
"or",
"logdir",
")",
":",
"raise",
"ValueError",
"(",
"'you must specify... | 38.545455 | 23.090909 |
def transformer_latent_decoder(x,
encoder_output,
ed_attention_bias,
hparams,
name=None):
"""Transformer decoder over latents using latent_attention_type.
Args:
x: Tensor of shape [batch,... | [
"def",
"transformer_latent_decoder",
"(",
"x",
",",
"encoder_output",
",",
"ed_attention_bias",
",",
"hparams",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"default_name",
"=",
"\"transformer_latent_dec\"",
")",
":"... | 43.666667 | 17.452381 |
def update_energy(self, bypass_check=False):
"""Fetch updated energy information about devices"""
for outlet in self.outlets:
outlet.update_energy(bypass_check) | [
"def",
"update_energy",
"(",
"self",
",",
"bypass_check",
"=",
"False",
")",
":",
"for",
"outlet",
"in",
"self",
".",
"outlets",
":",
"outlet",
".",
"update_energy",
"(",
"bypass_check",
")"
] | 46.25 | 3.75 |
def class_config_section(cls):
"""Get the config class config section"""
def c(s):
"""return a commented, wrapped block."""
s = '\n\n'.join(wrap_paragraphs(s, 78))
return '# ' + s.replace('\n', '\n# ')
# section header
breaker = '#' + '-'*78
... | [
"def",
"class_config_section",
"(",
"cls",
")",
":",
"def",
"c",
"(",
"s",
")",
":",
"\"\"\"return a commented, wrapped block.\"\"\"",
"s",
"=",
"'\\n\\n'",
".",
"join",
"(",
"wrap_paragraphs",
"(",
"s",
",",
"78",
")",
")",
"return",
"'# '",
"+",
"s",
"."... | 36.767442 | 17.302326 |
def format_diff_pyxb(a_pyxb, b_pyxb):
"""Create a diff between two PyXB objects.
Args:
a_pyxb: PyXB object
b_pyxb: PyXB object
Returns:
str : `Differ`-style delta
"""
return '\n'.join(
difflib.ndiff(
serialize_to_xml_str(a_pyxb).splitlines(),
seri... | [
"def",
"format_diff_pyxb",
"(",
"a_pyxb",
",",
"b_pyxb",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"difflib",
".",
"ndiff",
"(",
"serialize_to_xml_str",
"(",
"a_pyxb",
")",
".",
"splitlines",
"(",
")",
",",
"serialize_to_xml_str",
"(",
"b_pyxb",
")",
... | 21.058824 | 20.647059 |
def _read_opt_jumbo(self, code, *, desc):
"""Read HOPOPT Jumbo Payload option.
Structure of HOPOPT Jumbo Payload option [RFC 2675]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Option Type | Opt Data Len |
+-+... | [
"def",
"_read_opt_jumbo",
"(",
"self",
",",
"code",
",",
"*",
",",
"desc",
")",
":",
"_type",
"=",
"self",
".",
"_read_opt_type",
"(",
"code",
")",
"_size",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"if",
"_size",
"!=",
"4",
":",
"raise",
"P... | 43.363636 | 25.69697 |
def _ensure_arguments_are_provided(expected_types, arguments):
"""Ensure that all arguments expected by the query were actually provided."""
# This function only checks that the arguments were specified,
# and does not check types. Type checking is done as part of the actual formatting step.
expected_ar... | [
"def",
"_ensure_arguments_are_provided",
"(",
"expected_types",
",",
"arguments",
")",
":",
"# This function only checks that the arguments were specified,",
"# and does not check types. Type checking is done as part of the actual formatting step.",
"expected_arg_names",
"=",
"set",
"(",
... | 63.461538 | 26.461538 |
def make_dataframe(table, clean=True, verbose=False, **kwargs):
"""Coerce a provided table (QuerySet, list of lists, list of Series)
>>> dt = datetime.datetime
>>> make_dataframe([[1,2,3],[4,5,6]])
0 1 2
0 1 2 3
1 4 5 6
>>> make_dataframe([])
Empty DataFrame
Columns: []
... | [
"def",
"make_dataframe",
"(",
"table",
",",
"clean",
"=",
"True",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"table",
",",
"'objects'",
")",
"and",
"not",
"callable",
"(",
"table",
".",
"objects",
")",
":",... | 43.634146 | 21.365854 |
def extend_is_dir(value, minimum=None, maximum=None):
u"""
This function is extended is_dir().
This function was able to take ListType or StringType as argument.
"""
if isinstance(value, list):
return [is_dir(member)
for member in validate.is_list(value, minimum, maximum)]
... | [
"def",
"extend_is_dir",
"(",
"value",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"is_dir",
"(",
"member",
")",
"for",
"member",
"in",
"validate",
".",
"i... | 28.916667 | 18.166667 |
def approximate_density(
dist,
xloc,
parameters=None,
cache=None,
eps=1.e-7
):
"""
Approximate the probability density function.
Args:
dist : Dist
Distribution in question. May not be an advanced variable.
xloc : numpy.ndarray
... | [
"def",
"approximate_density",
"(",
"dist",
",",
"xloc",
",",
"parameters",
"=",
"None",
",",
"cache",
"=",
"None",
",",
"eps",
"=",
"1.e-7",
")",
":",
"if",
"parameters",
"is",
"None",
":",
"parameters",
"=",
"dist",
".",
"prm",
".",
"copy",
"(",
")"... | 30.854545 | 20.272727 |
def fillup_layer(layer, first_clbit):
"""
Given a layer, replace the Nones in it with EmptyWire elements.
Args:
layer (list): The layer that contains Nones.
first_clbit (int): The first wire that is classic.
Returns:
list: The new layer, with no Nones... | [
"def",
"fillup_layer",
"(",
"layer",
",",
"first_clbit",
")",
":",
"for",
"nones",
"in",
"[",
"i",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"layer",
")",
"if",
"x",
"is",
"None",
"]",
":",
"layer",
"[",
"nones",
"]",
"=",
"EmptyWire",
"(",
"... | 38.153846 | 20.153846 |
def _prepdata(self):
"""Adds potentially missing items to the geojson dictionary"""
# if missing, compute and add bbox
if not self._data.get("bbox"):
self.update_bbox()
# if missing, set crs to default crs (WGS84), see http://geojson.org/geojson-spec.html
if... | [
"def",
"_prepdata",
"(",
"self",
")",
":",
"# if missing, compute and add bbox",
"if",
"not",
"self",
".",
"_data",
".",
"get",
"(",
"\"bbox\"",
")",
":",
"self",
".",
"update_bbox",
"(",
")",
"# if missing, set crs to default crs (WGS84), see http://geojson.org/geojson... | 42.363636 | 19.090909 |
def hilbert_array(xint):
"""Compute Hilbert indices.
Parameters
----------
xint: (N, d) int numpy.ndarray
Returns
-------
h: (N,) int numpy.ndarray
Hilbert indices
"""
N, d = xint.shape
h = np.zeros(N, int64)
for n in range(N):
h[n] = Hilbert_to_int(xint[n... | [
"def",
"hilbert_array",
"(",
"xint",
")",
":",
"N",
",",
"d",
"=",
"xint",
".",
"shape",
"h",
"=",
"np",
".",
"zeros",
"(",
"N",
",",
"int64",
")",
"for",
"n",
"in",
"range",
"(",
"N",
")",
":",
"h",
"[",
"n",
"]",
"=",
"Hilbert_to_int",
"(",... | 18.941176 | 18.764706 |
def initialize(config):
"""
Initialize a connection to the Redis database.
"""
# Determine the client class to use
if 'redis_client' in config:
client = utils.find_entrypoint('turnstile.redis_client',
config['redis_client'], required=True)
else:
... | [
"def",
"initialize",
"(",
"config",
")",
":",
"# Determine the client class to use",
"if",
"'redis_client'",
"in",
"config",
":",
"client",
"=",
"utils",
".",
"find_entrypoint",
"(",
"'turnstile.redis_client'",
",",
"config",
"[",
"'redis_client'",
"]",
",",
"requir... | 37.051948 | 17.909091 |
def get_permission(parser, token):
"""
Performs a permission check with the given signature, user and objects
and assigns the result to a context variable.
Syntax::
{% get_permission PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %}
{% get_permission "poll_permission.chan... | [
"def",
"get_permission",
"(",
"parser",
",",
"token",
")",
":",
"return",
"PermissionForObjectNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
",",
"approved",
"=",
"True",
",",
"name",
"=",
"'\"permission\"'",
")"
] | 35.958333 | 23.125 |
def namePush(ctxt, value):
"""Pushes a new element name on top of the name stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.namePush(ctxt__o, value)
return ret | [
"def",
"namePush",
"(",
"ctxt",
",",
"value",
")",
":",
"if",
"ctxt",
"is",
"None",
":",
"ctxt__o",
"=",
"None",
"else",
":",
"ctxt__o",
"=",
"ctxt",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"namePush",
"(",
"ctxt__o",
",",
"value",
")",
"return",
... | 34.666667 | 10.5 |
def _translators(attr, kwargs):
"""
Decorator which associates a set of translators (serializers or
deserializers) with a given method. The `attr` parameter
identifies which attribute is being updated.
"""
# Add translators to a function or class
def decorator(func):
# Make sure we... | [
"def",
"_translators",
"(",
"attr",
",",
"kwargs",
")",
":",
"# Add translators to a function or class",
"def",
"decorator",
"(",
"func",
")",
":",
"# Make sure we have the attribute",
"try",
":",
"xlators",
"=",
"getattr",
"(",
"func",
",",
"attr",
")",
"except",... | 28.736842 | 14.315789 |
def find(model, rid):
""" Find a model from the store by resource id """
validate_rid(model, rid)
rid_field = model.rid_field
model = goldman.sess.store.find(model.RTYPE, rid_field, rid)
if not model:
abort(exceptions.DocumentNotFound)
return model | [
"def",
"find",
"(",
"model",
",",
"rid",
")",
":",
"validate_rid",
"(",
"model",
",",
"rid",
")",
"rid_field",
"=",
"model",
".",
"rid_field",
"model",
"=",
"goldman",
".",
"sess",
".",
"store",
".",
"find",
"(",
"model",
".",
"RTYPE",
",",
"rid_fiel... | 22.75 | 22.75 |
def display_movements_stats(ct, base_assignment):
"""Display how the amount of movement between two assignments.
:param ct: The cluster's ClusterTopology.
:param base_assignment: The cluster assignment to compare against.
"""
movement_count, movement_size, leader_changes = \
stats.get_parti... | [
"def",
"display_movements_stats",
"(",
"ct",
",",
"base_assignment",
")",
":",
"movement_count",
",",
"movement_size",
",",
"leader_changes",
"=",
"stats",
".",
"get_partition_movement_stats",
"(",
"ct",
",",
"base_assignment",
")",
"print",
"(",
"'Total partition mov... | 37.666667 | 15.833333 |
def convertstr2format(col,form):
"""
Convert input string to input regex (`form`).
:param col: input string.
:param form: eg. for hdf5: `"^[a-zA-Z_][a-zA-Z0-9_]*$"`
"""
if not isstrallowed(col,form):
col=col.replace(" ","_")
if not isstrallowed(col,form):
chars_... | [
"def",
"convertstr2format",
"(",
"col",
",",
"form",
")",
":",
"if",
"not",
"isstrallowed",
"(",
"col",
",",
"form",
")",
":",
"col",
"=",
"col",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"if",
"not",
"isstrallowed",
"(",
"col",
",",
"form",
... | 33.571429 | 12 |
def compute_followup_snr_series(data_reader, htilde, trig_time,
duration=0.095, check_state=True,
coinc_window=0.05):
"""Given a StrainBuffer, a template frequency series and a trigger time,
compute a portion of the SNR time series centered on the ... | [
"def",
"compute_followup_snr_series",
"(",
"data_reader",
",",
"htilde",
",",
"trig_time",
",",
"duration",
"=",
"0.095",
",",
"check_state",
"=",
"True",
",",
"coinc_window",
"=",
"0.05",
")",
":",
"if",
"check_state",
":",
"# was the detector observing for the ful... | 44.164557 | 23.746835 |
def uptime():
"""Returns uptime in seconds if even remotely possible, or None if not."""
if __boottime is not None:
return time.time() - __boottime
return {'amiga': _uptime_amiga,
'aros12': _uptime_amiga,
'beos5': _uptime_beos,
'cygwin': _uptime_linux,
... | [
"def",
"uptime",
"(",
")",
":",
"if",
"__boottime",
"is",
"not",
"None",
":",
"return",
"time",
".",
"time",
"(",
")",
"-",
"__boottime",
"return",
"{",
"'amiga'",
":",
"_uptime_amiga",
",",
"'aros12'",
":",
"_uptime_amiga",
",",
"'beos5'",
":",
"_uptime... | 42 | 11.52 |
def get_vm_list(self):
"""Get the list of guests that are created by SDK
return userid list"""
action = "list all guests in database"
with zvmutils.log_and_reraise_sdkbase_error(action):
guests_in_db = self._GuestDbOperator.get_guest_list()
guests_migrated = self.... | [
"def",
"get_vm_list",
"(",
"self",
")",
":",
"action",
"=",
"\"list all guests in database\"",
"with",
"zvmutils",
".",
"log_and_reraise_sdkbase_error",
"(",
"action",
")",
":",
"guests_in_db",
"=",
"self",
".",
"_GuestDbOperator",
".",
"get_guest_list",
"(",
")",
... | 46.642857 | 22.214286 |
def get_conn():
'''
Return a conn object for the passed VM data
'''
return ProfitBricksService(
username=config.get_cloud_config_value(
'username',
get_configured_provider(),
__opts__,
search_global=False
),
password=config.get_clou... | [
"def",
"get_conn",
"(",
")",
":",
"return",
"ProfitBricksService",
"(",
"username",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'username'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
",",
"passwor... | 25.055556 | 17.277778 |
def extract_scheduler_location(self, topology):
"""
Returns the representation of scheduler location that will
be returned from Tracker.
"""
schedulerLocation = {
"name": None,
"http_endpoint": None,
"job_page_link": None,
}
if topology.scheduler_location:
sche... | [
"def",
"extract_scheduler_location",
"(",
"self",
",",
"topology",
")",
":",
"schedulerLocation",
"=",
"{",
"\"name\"",
":",
"None",
",",
"\"http_endpoint\"",
":",
"None",
",",
"\"job_page_link\"",
":",
"None",
",",
"}",
"if",
"topology",
".",
"scheduler_locatio... | 34.526316 | 18.736842 |
def get_cube(self, name):
""" Given a cube name, construct that cube and return it. Do not
overwrite this method unless you need to. """
return Cube(self.get_engine(), name, self.get_cube_model(name)) | [
"def",
"get_cube",
"(",
"self",
",",
"name",
")",
":",
"return",
"Cube",
"(",
"self",
".",
"get_engine",
"(",
")",
",",
"name",
",",
"self",
".",
"get_cube_model",
"(",
"name",
")",
")"
] | 55.25 | 11.5 |
def time_range(self,flag=None):
'''
time range of the current dataset
:keyword flag: use a flag array to know the time range of an indexed slice of the object
'''
if self.count==0: return [[None,None],[None,None]]
if flag is None : return cnes_co... | [
"def",
"time_range",
"(",
"self",
",",
"flag",
"=",
"None",
")",
":",
"if",
"self",
".",
"count",
"==",
"0",
":",
"return",
"[",
"[",
"None",
",",
"None",
"]",
",",
"[",
"None",
",",
"None",
"]",
"]",
"if",
"flag",
"is",
"None",
":",
"return",
... | 45.2 | 30.4 |
async def unset_lock(self, resource, lock_identifier):
"""
Unlock this instance
:param resource: redis key to set
:param lock_identifier: uniquie id of lock
:raises: LockError if the lock resource acquired with different lock_identifier
"""
try:
with a... | [
"async",
"def",
"unset_lock",
"(",
"self",
",",
"resource",
",",
"lock_identifier",
")",
":",
"try",
":",
"with",
"await",
"self",
".",
"connect",
"(",
")",
"as",
"redis",
":",
"await",
"redis",
".",
"eval",
"(",
"self",
".",
"unset_lock_script",
",",
... | 43.75 | 15.375 |
async def check_permission(request, permission, context=None):
"""Checker that passes only to authoraised users with given permission.
If user is not authorized - raises HTTPUnauthorized,
if user is authorized and does not have permission -
raises HTTPForbidden.
"""
await check_authorized(requ... | [
"async",
"def",
"check_permission",
"(",
"request",
",",
"permission",
",",
"context",
"=",
"None",
")",
":",
"await",
"check_authorized",
"(",
"request",
")",
"allowed",
"=",
"await",
"permits",
"(",
"request",
",",
"permission",
",",
"context",
")",
"if",
... | 35.416667 | 16.583333 |
def delete_replication(Bucket,
region=None, key=None, keyid=None, profile=None):
'''
Delete the replication config from the given bucket
Returns {deleted: true} if replication configuration was deleted and returns
{deleted: False} if replication configuration was not deleted.
CLI Exampl... | [
"def",
"delete_replication",
"(",
"Bucket",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | 31.818182 | 28.181818 |
def _get_project_id(self):
"""
Get our projectId from the ``GOOGLE_APPLICATION_CREDENTIALS`` creds
JSON file.
:return: project ID
:rtype: str
"""
fpath = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', None)
if fpath is None:
raise Exception(... | [
"def",
"_get_project_id",
"(",
"self",
")",
":",
"fpath",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'GOOGLE_APPLICATION_CREDENTIALS'",
",",
"None",
")",
"if",
"fpath",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'ERROR: No project ID specified, and '",
"'G... | 40.235294 | 19.058824 |
def incver(self):
"""Increment all of the version numbers"""
d = {}
for p in self.__mapper__.attrs:
if p.key in ['vid','vname','fqname', 'version', 'cache_key']:
continue
if p.key == 'revision':
d[p.key] = self.revision + 1
else... | [
"def",
"incver",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"p",
"in",
"self",
".",
"__mapper__",
".",
"attrs",
":",
"if",
"p",
".",
"key",
"in",
"[",
"'vid'",
",",
"'vname'",
",",
"'fqname'",
",",
"'version'",
",",
"'cache_key'",
"]",
":"... | 28.642857 | 18.357143 |
def get_asset_spatial_assignment_session(self, proxy):
"""Gets the session for assigning spatial coverage to an asset.
arg proxy (osid.proxy.Proxy): a proxy
return: (osid.repository.AssetSpatialAssignmentSession) - an
AssetSpatialAssignmentSession
raise: OperationFa... | [
"def",
"get_asset_spatial_assignment_session",
"(",
"self",
",",
"proxy",
")",
":",
"if",
"not",
"self",
".",
"supports_asset_spatial_assignment",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"Import... | 40.48 | 17.44 |
def start_stream(self):
"""Starts a stream with teh current tracking terms"""
tracking_terms = self.term_checker.tracking_terms()
if len(tracking_terms) > 0 or self.unfiltered:
# we have terms to track, so build a new stream
self.stream = tweepy.Stream(self.auth, self.l... | [
"def",
"start_stream",
"(",
"self",
")",
":",
"tracking_terms",
"=",
"self",
".",
"term_checker",
".",
"tracking_terms",
"(",
")",
"if",
"len",
"(",
"tracking_terms",
")",
">",
"0",
"or",
"self",
".",
"unfiltered",
":",
"# we have terms to track, so build a new ... | 47.333333 | 23.952381 |
def _update_proxy(self, change):
""" An observer which sends the state change to the proxy.
"""
if change['type'] == 'event':
name = 'do_'+change['name']
if hasattr(self.proxy, name):
handler = getattr(self.proxy, name)
handler()
e... | [
"def",
"_update_proxy",
"(",
"self",
",",
"change",
")",
":",
"if",
"change",
"[",
"'type'",
"]",
"==",
"'event'",
":",
"name",
"=",
"'do_'",
"+",
"change",
"[",
"'name'",
"]",
"if",
"hasattr",
"(",
"self",
".",
"proxy",
",",
"name",
")",
":",
"han... | 33.545455 | 10.909091 |
def collapse( self, direction ):
"""
Collapses this splitter handle before or after other widgets based on \
the inputed CollapseDirection.
:param direction | <XSplitterHandle.CollapseDirection>
:return <bool> | success
"""
if ( self.isC... | [
"def",
"collapse",
"(",
"self",
",",
"direction",
")",
":",
"if",
"(",
"self",
".",
"isCollapsed",
"(",
")",
")",
":",
"return",
"False",
"splitter",
"=",
"self",
".",
"parent",
"(",
")",
"if",
"(",
"not",
"splitter",
")",
":",
"return",
"False",
"... | 32.133333 | 18.133333 |
def update(self, unique_name=values.unset, callback_method=values.unset,
callback_url=values.unset, friendly_name=values.unset,
rate_plan=values.unset, status=values.unset,
commands_callback_method=values.unset,
commands_callback_url=values.unset, sms_fallback... | [
"def",
"update",
"(",
"self",
",",
"unique_name",
"=",
"values",
".",
"unset",
",",
"callback_method",
"=",
"values",
".",
"unset",
",",
"callback_url",
"=",
"values",
".",
"unset",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"rate_plan",
"=",
... | 47.28 | 15.92 |
def rhochange(self):
"""Updated cached c array when rho changes."""
if self.opt['HighMemSolve'] and self.cri.Cd == 1:
self.c = sl.solvedbd_sm_c(
self.Df, np.conj(self.Df),
(self.mu / self.rho) * self.GHGf + 1.0, self.cri.axisM) | [
"def",
"rhochange",
"(",
"self",
")",
":",
"if",
"self",
".",
"opt",
"[",
"'HighMemSolve'",
"]",
"and",
"self",
".",
"cri",
".",
"Cd",
"==",
"1",
":",
"self",
".",
"c",
"=",
"sl",
".",
"solvedbd_sm_c",
"(",
"self",
".",
"Df",
",",
"np",
".",
"c... | 40.285714 | 16 |
def print_table(data, title=None):
"""Print data in table format.
data (dict or list of tuples): Label/value pairs.
title (unicode or None): Title, will be printed above.
"""
if isinstance(data, dict):
data = list(data.items())
tpl_row = ' {:<15}' * len(data[0])
table = '\n'.join... | [
"def",
"print_table",
"(",
"data",
",",
"title",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"data",
"=",
"list",
"(",
"data",
".",
"items",
"(",
")",
")",
"tpl_row",
"=",
"' {:<15}'",
"*",
"len",
"(",
"data",
... | 35.538462 | 13.461538 |
def wsgi_app(self, environ, start_response):
"""
将原始的app,包装为包括websocket的app
"""
path = environ['PATH_INFO']
if re.match(self.path_pattern, path):
ws = environ['wsgi.websocket']
address = (environ.get('REMOTE_ADDR'), environ.get('REMOTE_PORT'))
... | [
"def",
"wsgi_app",
"(",
"self",
",",
"environ",
",",
"start_response",
")",
":",
"path",
"=",
"environ",
"[",
"'PATH_INFO'",
"]",
"if",
"re",
".",
"match",
"(",
"self",
".",
"path_pattern",
",",
"path",
")",
":",
"ws",
"=",
"environ",
"[",
"'wsgi.webso... | 33.588235 | 14.176471 |
def _get_fix_info(fbfid):
"""Return the fix screen info from the framebuffer file descriptor."""
fix_info = FbMem.FixScreenInfo()
fcntl.ioctl(fbfid, FbMem.FBIOGET_FSCREENINFO, fix_info)
return fix_info | [
"def",
"_get_fix_info",
"(",
"fbfid",
")",
":",
"fix_info",
"=",
"FbMem",
".",
"FixScreenInfo",
"(",
")",
"fcntl",
".",
"ioctl",
"(",
"fbfid",
",",
"FbMem",
".",
"FBIOGET_FSCREENINFO",
",",
"fix_info",
")",
"return",
"fix_info"
] | 45.8 | 11 |
def _find_form_xobject_images(pdf, container, contentsinfo):
"""Find any images that are in Form XObjects in the container
The container may be a page, or a parent Form XObject.
"""
if '/Resources' not in container:
return
resources = container['/Resources']
if '/XObject' not in resour... | [
"def",
"_find_form_xobject_images",
"(",
"pdf",
",",
"container",
",",
"contentsinfo",
")",
":",
"if",
"'/Resources'",
"not",
"in",
"container",
":",
"return",
"resources",
"=",
"container",
"[",
"'/Resources'",
"]",
"if",
"'/XObject'",
"not",
"in",
"resources",... | 36.066667 | 17.8 |
def instantiate(self):
""" Write lines for instantiation """
# e.g. model_name_35 = Model()
code_lines = []
if not self.instantiated:
code_lines.append("%s = %s()" % (self.variable_name, self.model.__name__))
self.instantiated = True
# Store our vari... | [
"def",
"instantiate",
"(",
"self",
")",
":",
"# e.g. model_name_35 = Model()",
"code_lines",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"instantiated",
":",
"code_lines",
".",
"append",
"(",
"\"%s = %s()\"",
"%",
"(",
"self",
".",
"variable_name",
",",
"self",
... | 37.333333 | 21.4 |
def universal_transformer_highway(layer_inputs,
step, hparams,
ffn_unit,
attention_unit,
pad_remover=None):
"""Universal Transformer with highway connection.
It transforms the st... | [
"def",
"universal_transformer_highway",
"(",
"layer_inputs",
",",
"step",
",",
"hparams",
",",
"ffn_unit",
",",
"attention_unit",
",",
"pad_remover",
"=",
"None",
")",
":",
"state",
",",
"inputs",
",",
"memory",
"=",
"layer_inputs",
"new_state",
"=",
"step_prepr... | 30.866667 | 20.666667 |
def create_validating_webhook_configuration(self, body, **kwargs):
"""
create a ValidatingWebhookConfiguration
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_validating_webhook_conf... | [
"def",
"create_validating_webhook_configuration",
"(",
"self",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"crea... | 68.086957 | 39.913043 |
def createCFileBuilders(env):
"""This is a utility function that creates the CFile/CXXFile
Builders in an Environment if they
are not there already.
If they are there already, we return the existing ones.
This is a separate function because soooo many Tools
use this functionality.
The ret... | [
"def",
"createCFileBuilders",
"(",
"env",
")",
":",
"try",
":",
"c_file",
"=",
"env",
"[",
"'BUILDERS'",
"]",
"[",
"'CFile'",
"]",
"except",
"KeyError",
":",
"c_file",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"(",
"action",
"=",
"{",
"}",
",",
"... | 31.848485 | 18.484848 |
def hex2rgb(hexvalue):
"""Converts a given hex color to
its respective rgb color."""
# Make sure a possible '#' char is eliminated
# before processing the color.
if ('#' in hexvalue):
hexcolor = hexvalue.replace('#', '')
else:
hexcolor = hexvalue
# Hex colors have a fixed l... | [
"def",
"hex2rgb",
"(",
"hexvalue",
")",
":",
"# Make sure a possible '#' char is eliminated",
"# before processing the color.",
"if",
"(",
"'#'",
"in",
"hexvalue",
")",
":",
"hexcolor",
"=",
"hexvalue",
".",
"replace",
"(",
"'#'",
",",
"''",
")",
"else",
":",
"h... | 31.708333 | 18.958333 |
def _on_report_error(self, code, message, connection_id):
"""Callback function called if an error occured while parsing a report"""
self._logger.critical(
"Error receiving reports, no more reports will be processed on this adapter, code=%d, msg=%s", code, message
) | [
"def",
"_on_report_error",
"(",
"self",
",",
"code",
",",
"message",
",",
"connection_id",
")",
":",
"self",
".",
"_logger",
".",
"critical",
"(",
"\"Error receiving reports, no more reports will be processed on this adapter, code=%d, msg=%s\"",
",",
"code",
",",
"message... | 59.4 | 27.6 |
def _green_worker(self):
"""
A worker that does actual jobs
"""
while not self.quit.is_set():
try:
task = self.green_queue.get(timeout=1)
timestamp, missile, marker = task
planned_time = self.start_time + (timestamp / 1000.0)
... | [
"def",
"_green_worker",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"quit",
".",
"is_set",
"(",
")",
":",
"try",
":",
"task",
"=",
"self",
".",
"green_queue",
".",
"get",
"(",
"timeout",
"=",
"1",
")",
"timestamp",
",",
"missile",
",",
"mar... | 32.529412 | 18.470588 |
def display_markers(self):
"""Add markers on top of first plot."""
for item in self.idx_markers:
self.scene.removeItem(item)
self.idx_markers = []
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
window_end =... | [
"def",
"display_markers",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"idx_markers",
":",
"self",
".",
"scene",
".",
"removeItem",
"(",
"item",
")",
"self",
".",
"idx_markers",
"=",
"[",
"]",
"window_start",
"=",
"self",
".",
"parent",
"."... | 40.35 | 16.225 |
def _log_response(response):
"""Log out information about a ``Request`` object.
After calling ``requests.request`` or one of its convenience methods, the
object returned can be passed to this method. If done, information about
the object returned is logged.
:return: Nothing is returned.
"""
... | [
"def",
"_log_response",
"(",
"response",
")",
":",
"message",
"=",
"u'Received HTTP {0} response: {1}'",
".",
"format",
"(",
"response",
".",
"status_code",
",",
"response",
".",
"text",
")",
"if",
"response",
".",
"status_code",
">=",
"400",
":",
"# pragma: no ... | 30.222222 | 20.277778 |
def build_engine_session(connection, echo=False, autoflush=None, autocommit=None, expire_on_commit=None,
scopefunc=None):
"""Build an engine and a session.
:param str connection: An RFC-1738 database connection string
:param bool echo: Turn on echoing SQL
:param Optional[bool] ... | [
"def",
"build_engine_session",
"(",
"connection",
",",
"echo",
"=",
"False",
",",
"autoflush",
"=",
"None",
",",
"autocommit",
"=",
"None",
",",
"expire_on_commit",
"=",
"None",
",",
"scopefunc",
"=",
"None",
")",
":",
"if",
"connection",
"is",
"None",
":"... | 40.543478 | 27.021739 |
def _to_bz2file(self, file_generator):
"""Convert file to bz2-compressed file.
:return: None
:rtype: :py:obj:`None`
"""
with bz2.BZ2File(file_generator.to_path, mode="wb") as outfile:
for f in file_generator:
outfile.write(f.writestr(file_generator.to_... | [
"def",
"_to_bz2file",
"(",
"self",
",",
"file_generator",
")",
":",
"with",
"bz2",
".",
"BZ2File",
"(",
"file_generator",
".",
"to_path",
",",
"mode",
"=",
"\"wb\"",
")",
"as",
"outfile",
":",
"for",
"f",
"in",
"file_generator",
":",
"outfile",
".",
"wri... | 41.25 | 12.75 |
def arnoldi_res(A, V, H, ip_B=None):
"""Measure Arnoldi residual.
:param A: a linear operator that can be used with scipy's aslinearoperator
with ``shape==(N,N)``.
:param V: Arnoldi basis matrix with ``shape==(N,n)``.
:param H: Hessenberg matrix: either :math:`\\underline{H}_{n-1}` with
``s... | [
"def",
"arnoldi_res",
"(",
"A",
",",
"V",
",",
"H",
",",
"ip_B",
"=",
"None",
")",
":",
"N",
"=",
"V",
".",
"shape",
"[",
"0",
"]",
"invariant",
"=",
"H",
".",
"shape",
"[",
"0",
"]",
"==",
"H",
".",
"shape",
"[",
"1",
"]",
"A",
"=",
"get... | 39.5 | 18.545455 |
def bpmn_diagram_to_png(bpmn_diagram, file_name):
"""
Create a png picture for given diagram
:param bpmn_diagram: an instance of BPMNDiagramGraph class,
:param file_name: name of generated file.
"""
g = bpmn_diagram.diagram_graph
graph = pydotplus.Dot()
for node in g.nodes(data=True):
... | [
"def",
"bpmn_diagram_to_png",
"(",
"bpmn_diagram",
",",
"file_name",
")",
":",
"g",
"=",
"bpmn_diagram",
".",
"diagram_graph",
"graph",
"=",
"pydotplus",
".",
"Dot",
"(",
")",
"for",
"node",
"in",
"g",
".",
"nodes",
"(",
"data",
"=",
"True",
")",
":",
... | 40.12 | 25.64 |
def iterbyscore(self, min='-inf', max='+inf', start=None, num=None,
withscores=False, reverse=None):
""" Return a range of values from the sorted set name with scores
between @min and @max.
If @start and @num are specified, then return a slice
of the rang... | [
"def",
"iterbyscore",
"(",
"self",
",",
"min",
"=",
"'-inf'",
",",
"max",
"=",
"'+inf'",
",",
"start",
"=",
"None",
",",
"num",
"=",
"None",
",",
"withscores",
"=",
"False",
",",
"reverse",
"=",
"None",
")",
":",
"reverse",
"=",
"reverse",
"if",
"r... | 45 | 19.068966 |
def update_metadata_for_node(self, node, metadata):
"""
Updates the existing metadata for the specified node with
the supplied dictionary.
"""
return self.manager.update_metadata(self, metadata, node=node) | [
"def",
"update_metadata_for_node",
"(",
"self",
",",
"node",
",",
"metadata",
")",
":",
"return",
"self",
".",
"manager",
".",
"update_metadata",
"(",
"self",
",",
"metadata",
",",
"node",
"=",
"node",
")"
] | 40 | 12.333333 |
def plot_compare_four(data_a, data_b, data_c, data_d, disply_kwargs=None,
plotter_kwargs=None, show_kwargs=None, screenshot=None,
camera_position=None, outline=None, outline_color='k',
labels=('A', 'B', 'C', 'D')):
"""Plot a 2 by 2 comparison of data... | [
"def",
"plot_compare_four",
"(",
"data_a",
",",
"data_b",
",",
"data_c",
",",
"data_d",
",",
"disply_kwargs",
"=",
"None",
",",
"plotter_kwargs",
"=",
"None",
",",
"show_kwargs",
"=",
"None",
",",
"screenshot",
"=",
"None",
",",
"camera_position",
"=",
"None... | 36.966667 | 16.5 |
def particle_clusters(
particle_locations, particle_weights=None,
eps=0.5, min_particles=5, metric='euclidean',
weighted=False, w_pow=0.5,
quiet=True
):
"""
Yields an iterator onto tuples ``(cluster_label, cluster_particles)``,
where ``cluster_label`` is an `int` identify... | [
"def",
"particle_clusters",
"(",
"particle_locations",
",",
"particle_weights",
"=",
"None",
",",
"eps",
"=",
"0.5",
",",
"min_particles",
"=",
"5",
",",
"metric",
"=",
"'euclidean'",
",",
"weighted",
"=",
"False",
",",
"w_pow",
"=",
"0.5",
",",
"quiet",
"... | 39.8 | 23.228571 |
def view_isometric(self):
"""
Resets the camera to a default isometric view showing all the
actors in the scene.
"""
self.camera_position = self.get_default_cam_pos()
self.camera_set = False
return self.reset_camera() | [
"def",
"view_isometric",
"(",
"self",
")",
":",
"self",
".",
"camera_position",
"=",
"self",
".",
"get_default_cam_pos",
"(",
")",
"self",
".",
"camera_set",
"=",
"False",
"return",
"self",
".",
"reset_camera",
"(",
")"
] | 33.25 | 11 |
def __train(self, n_clusters=4):
"""
Calculate cluster's centroids and standard deviations. If there are at least the number of threshold rows \
then:
* Observations will be normalised.
* Standard deviations will be returned.
* Clusters will be retu... | [
"def",
"__train",
"(",
"self",
",",
"n_clusters",
"=",
"4",
")",
":",
"try",
":",
"for",
"obs",
"in",
"self",
".",
"observations",
":",
"features",
",",
"ids",
"=",
"self",
".",
"__get_features_for_observation",
"(",
"observation",
"=",
"obs",
",",
"last... | 42.82 | 30.7 |
def get_queryset(self):
"""
Returns a queryset of models for the month requested
"""
qs = super(BaseCalendarMonthView, self).get_queryset()
year = self.get_year()
month = self.get_month()
date_field = self.get_date_field()
end_date_field = self.get_end_d... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"super",
"(",
"BaseCalendarMonthView",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"year",
"=",
"self",
".",
"get_year",
"(",
")",
"month",
"=",
"self",
".",
"get_month",
"(",
")",
"date_fie... | 38.258065 | 19.645161 |
def _eval_progress(self, match):
'''
Runs the user-supplied progress calculation rule
'''
_locals = {k: safe_float(v) for k, v in match.groupdict().items()}
if "x" not in _locals:
_locals["x"] = [safe_float(x) for x in match.groups()]
try:
... | [
"def",
"_eval_progress",
"(",
"self",
",",
"match",
")",
":",
"_locals",
"=",
"{",
"k",
":",
"safe_float",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"match",
".",
"groupdict",
"(",
")",
".",
"items",
"(",
")",
"}",
"if",
"\"x\"",
"not",
"in",
... | 36.454545 | 21.909091 |
def copy_all_lines_from_to(inputFile, outputFile):
"""Copy all lines from an input file object to an output file object."""
currentLine = inputFile.readline()
while currentLine:
outputFile.write(currentLine)
currentLine = inputFile.readline() | [
"def",
"copy_all_lines_from_to",
"(",
"inputFile",
",",
"outputFile",
")",
":",
"currentLine",
"=",
"inputFile",
".",
"readline",
"(",
")",
"while",
"currentLine",
":",
"outputFile",
".",
"write",
"(",
"currentLine",
")",
"currentLine",
"=",
"inputFile",
".",
... | 44.166667 | 5.833333 |
def _get_mft_zone_size(self, num_clusters, mft_zone_multiplier=1):
"""Returns mft zone size in clusters.
From ntfs_progs.1.22."""
sizes = {
4: num_clusters >> 1, # 50%
3: (num_clusters * 3) >> 3, # 37,5%
2: num_clusters >> 2, # 25%
... | [
"def",
"_get_mft_zone_size",
"(",
"self",
",",
"num_clusters",
",",
"mft_zone_multiplier",
"=",
"1",
")",
":",
"sizes",
"=",
"{",
"4",
":",
"num_clusters",
">>",
"1",
",",
"# 50%",
"3",
":",
"(",
"num_clusters",
"*",
"3",
")",
">>",
"3",
",",
"# 37,5%"... | 34.727273 | 19.363636 |
def is_intersection(g, n):
"""
Determine if a node is an intersection
graph: 1 -->-- 2 -->-- 3
>>> is_intersection(g, 2)
False
graph:
1 -- 2 -- 3
|
4
>>> is_intersection(g, 2)
True
Parameters
----------
g : networkx DiGraph
n : node id
R... | [
"def",
"is_intersection",
"(",
"g",
",",
"n",
")",
":",
"return",
"len",
"(",
"set",
"(",
"g",
".",
"predecessors",
"(",
"n",
")",
"+",
"g",
".",
"successors",
"(",
"n",
")",
")",
")",
">",
"2"
] | 13.928571 | 25.285714 |
def Construct(self): # pylint: disable-msg=C0103
"""Construct nuSTORM from a GDML file"""
# Parse the GDML
self.world = self.gdml_parser.GetWorldVolume()
# Create sensitive detector
self.sensitive_detector = ScintSD()
# Get logical volume for X view, then attach SD
... | [
"def",
"Construct",
"(",
"self",
")",
":",
"# pylint: disable-msg=C0103",
"# Parse the GDML",
"self",
".",
"world",
"=",
"self",
".",
"gdml_parser",
".",
"GetWorldVolume",
"(",
")",
"# Create sensitive detector",
"self",
".",
"sensitive_detector",
"=",
"ScintSD",
"(... | 39.424242 | 20.151515 |
def change_env(name, val):
"""
Args:
name(str), val(str):
Returns:
a context where the environment variable ``name`` being set to
``val``. It will be set back after the context exits.
"""
oldval = os.environ.get(name, None)
os.environ[name] = val
yield
if oldval ... | [
"def",
"change_env",
"(",
"name",
",",
"val",
")",
":",
"oldval",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"name",
",",
"None",
")",
"os",
".",
"environ",
"[",
"name",
"]",
"=",
"val",
"yield",
"if",
"oldval",
"is",
"None",
":",
"del",
"os",
... | 24.125 | 18.125 |
def getslide(self,slide_num):
"""
Return the triggers with a specific slide number.
@param slide_num: the slide number to recover (contained in the event_id)
"""
slideTrigs = self.copy()
slideTrigs.extend(row for row in self if row.get_slide_number() == slide_num)
return slideTrigs | [
"def",
"getslide",
"(",
"self",
",",
"slide_num",
")",
":",
"slideTrigs",
"=",
"self",
".",
"copy",
"(",
")",
"slideTrigs",
".",
"extend",
"(",
"row",
"for",
"row",
"in",
"self",
"if",
"row",
".",
"get_slide_number",
"(",
")",
"==",
"slide_num",
")",
... | 36.125 | 16.375 |
def login(token, apikey, username, password):
"""
Login to FloydHub.
"""
if manual_login_success(token, username, password):
return
if not apikey:
if has_browser():
apikey = wait_for_apikey()
else:
floyd_logger.error(
"No browser found... | [
"def",
"login",
"(",
"token",
",",
"apikey",
",",
"username",
",",
"password",
")",
":",
"if",
"manual_login_success",
"(",
"token",
",",
"username",
",",
"password",
")",
":",
"return",
"if",
"not",
"apikey",
":",
"if",
"has_browser",
"(",
")",
":",
"... | 34 | 22.090909 |
def add(self, name, func):
''' Attach a callback to a hook. '''
if name not in self.hooks:
raise ValueError("Unknown hook name %s" % name)
was_empty = self._empty()
self.hooks[name].append(func)
if self.app and was_empty and not self._empty(): self.app.reset() | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"func",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"hooks",
":",
"raise",
"ValueError",
"(",
"\"Unknown hook name %s\"",
"%",
"name",
")",
"was_empty",
"=",
"self",
".",
"_empty",
"(",
")",
"self",
... | 43.714286 | 12.285714 |
def NdarrayToEntry(self, x):
"""Converts an ndarray to the Entry format."""
row_counts = []
for row in x:
try:
rc = np.count_nonzero(~np.isnan(row))
if rc != 0:
row_counts.append(rc)
except TypeError:
try:
row_counts.append(row.size)
except Att... | [
"def",
"NdarrayToEntry",
"(",
"self",
",",
"x",
")",
":",
"row_counts",
"=",
"[",
"]",
"for",
"row",
"in",
"x",
":",
"try",
":",
"rc",
"=",
"np",
".",
"count_nonzero",
"(",
"~",
"np",
".",
"isnan",
"(",
"row",
")",
")",
"if",
"rc",
"!=",
"0",
... | 29 | 15.047619 |
def iscomplete(rawmessage):
"""Test if the raw message is a complete message."""
if len(rawmessage) < 2:
return False
if rawmessage[0] != 0x02:
raise ValueError('message does not start with 0x02')
messageBuffer = bytearray()
filler = bytearray(30)
messageBuffer.extend(rawmessag... | [
"def",
"iscomplete",
"(",
"rawmessage",
")",
":",
"if",
"len",
"(",
"rawmessage",
")",
"<",
"2",
":",
"return",
"False",
"if",
"rawmessage",
"[",
"0",
"]",
"!=",
"0x02",
":",
"raise",
"ValueError",
"(",
"'message does not start with 0x02'",
")",
"messageBuff... | 27.481481 | 17.925926 |
def tables_(self) -> list:
"""Return a list of the existing tables in a database
:return: list of the table names
:rtype: list
:example: ``tables = ds.tables_()``
"""
if self._check_db() == False:
return
try:
return self._tables()
... | [
"def",
"tables_",
"(",
"self",
")",
"->",
"list",
":",
"if",
"self",
".",
"_check_db",
"(",
")",
"==",
"False",
":",
"return",
"try",
":",
"return",
"self",
".",
"_tables",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"err",
"(",
... | 27 | 13.857143 |
def save(self, path, key, format, data):
"""Save a newly generated thumbnail.
path:
path of the source image
key:
key of the thumbnail
format:
thumbnail's file extension
data:
thumbnail's binary data
"""
thumbpath =... | [
"def",
"save",
"(",
"self",
",",
"path",
",",
"key",
",",
"format",
",",
"data",
")",
":",
"thumbpath",
"=",
"self",
".",
"get_thumbpath",
"(",
"path",
",",
"key",
",",
"format",
")",
"fullpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
... | 30 | 12.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.