text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def try_run_setup(**kwargs):
""" Fails gracefully when various install steps don't work.
"""
try:
run_setup(**kwargs)
except Exception as e:
print(str(e))
if "xgboost" in str(e).lower():
kwargs["test_xgboost"] = False
print("Couldn't install XGBoost for t... | [
"def",
"try_run_setup",
"(",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"run_setup",
"(",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"str",
"(",
"e",
")",
")",
"if",
"\"xgboost\"",
"in",
"str",
"(",
"e",
")",
"."... | 36.545455 | 0.002424 |
def _api_delete(path, data, server=None):
'''
Do a DELETE request to the API
'''
server = _get_server(server)
response = requests.delete(
url=_get_url(server['ssl'], server['url'], server['port'], path),
auth=_get_auth(server['user'], server['password']),
headers=... | [
"def",
"_api_delete",
"(",
"path",
",",
"data",
",",
"server",
"=",
"None",
")",
":",
"server",
"=",
"_get_server",
"(",
"server",
")",
"response",
"=",
"requests",
".",
"delete",
"(",
"url",
"=",
"_get_url",
"(",
"server",
"[",
"'ssl'",
"]",
",",
"s... | 31.846154 | 0.002347 |
def _update_index(self, axis, key, value):
"""Update the current axis index based on a given key or value
This is an internal method designed to set the origin or step for
an index, whilst updating existing Index arrays as appropriate
Examples
--------
>>> self._update_... | [
"def",
"_update_index",
"(",
"self",
",",
"axis",
",",
"key",
",",
"value",
")",
":",
"# delete current value if given None",
"if",
"value",
"is",
"None",
":",
"return",
"delattr",
"(",
"self",
",",
"key",
")",
"_key",
"=",
"\"_{}\"",
".",
"format",
"(",
... | 31.111111 | 0.001385 |
def per_installer_data(self):
"""
Return download data by installer name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of installer name/version (str) to count (int).
:rtype: dict
"""
ret = {}
for cache_date in sel... | [
"def",
"per_installer_data",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"cache_date",
"in",
"self",
".",
"cache_dates",
":",
"data",
"=",
"self",
".",
"_cache_get",
"(",
"cache_date",
")",
"ret",
"[",
"cache_date",
"]",
"=",
"{",
"}",
"for",
... | 38.272727 | 0.002317 |
def decrease_writes_in_percent(
current_provisioning, percent, min_provisioned_writes, log_tag):
""" Decrease the current_provisioning with percent %
:type current_provisioning: int
:param current_provisioning: The current provisioning
:type percent: int
:param percent: How many percent sho... | [
"def",
"decrease_writes_in_percent",
"(",
"current_provisioning",
",",
"percent",
",",
"min_provisioned_writes",
",",
"log_tag",
")",
":",
"percent",
"=",
"float",
"(",
"percent",
")",
"decrease",
"=",
"int",
"(",
"float",
"(",
"current_provisioning",
")",
"*",
... | 34.888889 | 0.000775 |
def init2(
self,
input_tube, # Read task from the input tube.
output_tubes, # Send result on all the output tubes.
num_workers, # Total number of workers in the stage.
disable_result, # Whether to override any result with None.
do_stop_task, # Whether to ... | [
"def",
"init2",
"(",
"self",
",",
"input_tube",
",",
"# Read task from the input tube.",
"output_tubes",
",",
"# Send result on all the output tubes.",
"num_workers",
",",
"# Total number of workers in the stage.",
"disable_result",
",",
"# Whether to override any result with None.",... | 45.5 | 0.007177 |
def parents_from_boolRule(self,rule):
""" Determine parents based on boolean updaterule.
Returns list of parents.
"""
rule_pa = rule.replace('(','').replace(')','').replace('or','').replace('and','').replace('not','')
rule_pa = rule_pa.split()
# if there are no paren... | [
"def",
"parents_from_boolRule",
"(",
"self",
",",
"rule",
")",
":",
"rule_pa",
"=",
"rule",
".",
"replace",
"(",
"'('",
",",
"''",
")",
".",
"replace",
"(",
"')'",
",",
"''",
")",
".",
"replace",
"(",
"'or'",
",",
"''",
")",
".",
"replace",
"(",
... | 43.448276 | 0.01087 |
def download_artifact_bundle(self, id_or_uri, file_path):
"""
Download the Artifact Bundle.
Args:
id_or_uri: ID or URI of the Artifact Bundle.
file_path(str): Destination file path.
Returns:
bool: Successfully downloaded.
"""
uri = se... | [
"def",
"download_artifact_bundle",
"(",
"self",
",",
"id_or_uri",
",",
"file_path",
")",
":",
"uri",
"=",
"self",
".",
"DOWNLOAD_PATH",
"+",
"'/'",
"+",
"extract_id_from_uri",
"(",
"id_or_uri",
")",
"return",
"self",
".",
"_client",
".",
"download",
"(",
"ur... | 32 | 0.004673 |
def prior_omega_m(self, omega_m, omega_m_min=0, omega_m_max=1):
"""
checks whether the parameter omega_m is within the given bounds
:param omega_m:
:param omega_m_min:
:param omega_m_max:
:return:
"""
if omega_m < omega_m_min or omega_m > omega_m_max:
... | [
"def",
"prior_omega_m",
"(",
"self",
",",
"omega_m",
",",
"omega_m_min",
"=",
"0",
",",
"omega_m_max",
"=",
"1",
")",
":",
"if",
"omega_m",
"<",
"omega_m_min",
"or",
"omega_m",
">",
"omega_m_max",
":",
"penalty",
"=",
"-",
"10",
"**",
"15",
"return",
"... | 31.384615 | 0.004762 |
def chatToId(url):
"""
Extract the conversation ID from a conversation URL.
Matches addresses containing ``conversations/<chat>``.
Args:
url (str): Skype API URL
Returns:
str: extracted identifier
"""
match = re.search(r"conversations/([... | [
"def",
"chatToId",
"(",
"url",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r\"conversations/([0-9]+:[^/]+)\"",
",",
"url",
")",
"return",
"match",
".",
"group",
"(",
"1",
")",
"if",
"match",
"else",
"None"
] | 26.785714 | 0.005155 |
def listdir(self, dirname):
"""Returns a list of entries contained within a directory."""
client = boto3.client("s3")
bucket, path = self.bucket_and_path(dirname)
p = client.get_paginator("list_objects")
if not path.endswith("/"):
path += "/" # This will now only ret... | [
"def",
"listdir",
"(",
"self",
",",
"dirname",
")",
":",
"client",
"=",
"boto3",
".",
"client",
"(",
"\"s3\"",
")",
"bucket",
",",
"path",
"=",
"self",
".",
"bucket_and_path",
"(",
"dirname",
")",
"p",
"=",
"client",
".",
"get_paginator",
"(",
"\"list_... | 48.4 | 0.004054 |
def double_exponential_moving_average(data, period):
"""
Double Exponential Moving Average.
Formula:
DEMA = 2*EMA - EMA(EMA)
"""
catch_errors.check_for_period_error(data, period)
dema = (2 * ema(data, period)) - ema(ema(data, period), period)
return dema | [
"def",
"double_exponential_moving_average",
"(",
"data",
",",
"period",
")",
":",
"catch_errors",
".",
"check_for_period_error",
"(",
"data",
",",
"period",
")",
"dema",
"=",
"(",
"2",
"*",
"ema",
"(",
"data",
",",
"period",
")",
")",
"-",
"ema",
"(",
"e... | 25.272727 | 0.003472 |
def _check_requirements(self):
"""
Check if VPCS is available with the correct version.
"""
path = self._vpcs_path()
if not path:
raise VPCSError("No path to a VPCS executable has been set")
# This raise an error if ubridge is not available
self.ubri... | [
"def",
"_check_requirements",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"_vpcs_path",
"(",
")",
"if",
"not",
"path",
":",
"raise",
"VPCSError",
"(",
"\"No path to a VPCS executable has been set\"",
")",
"# This raise an error if ubridge is not available",
"self",... | 31.421053 | 0.003252 |
def numpy_to_texture(image):
"""Convert a NumPy image array to a vtk.vtkTexture"""
if not isinstance(image, np.ndarray):
raise TypeError('Unknown input type ({})'.format(type(image)))
if image.ndim != 3 or image.shape[2] != 3:
raise AssertionError('Input image must be nn by nm by RGB')
g... | [
"def",
"numpy_to_texture",
"(",
"image",
")",
":",
"if",
"not",
"isinstance",
"(",
"image",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"TypeError",
"(",
"'Unknown input type ({})'",
".",
"format",
"(",
"type",
"(",
"image",
")",
")",
")",
"if",
"image... | 53.8 | 0.005484 |
def list_all_versions(pkg,
bin_env=None,
include_alpha=False,
include_beta=False,
include_rc=False,
user=None,
cwd=None,
index_url=None,
extra_i... | [
"def",
"list_all_versions",
"(",
"pkg",
",",
"bin_env",
"=",
"None",
",",
"include_alpha",
"=",
"False",
",",
"include_beta",
"=",
"False",
",",
"include_rc",
"=",
"False",
",",
"user",
"=",
"None",
",",
"cwd",
"=",
"None",
",",
"index_url",
"=",
"None",... | 28.989796 | 0.001361 |
def add_copy_spec(self, copyspecs, sizelimit=None, tailit=True, pred=None):
"""Add a file or glob but limit it to sizelimit megabytes. If fname is
a single file the file will be tailed to meet sizelimit. If the first
file in a glob is too large it will be tailed to meet the sizelimit.
""... | [
"def",
"add_copy_spec",
"(",
"self",
",",
"copyspecs",
",",
"sizelimit",
"=",
"None",
",",
"tailit",
"=",
"True",
",",
"pred",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"test_predicate",
"(",
"pred",
"=",
"pred",
")",
":",
"self",
".",
"_log_i... | 37.27027 | 0.000706 |
def status(self, value):
"""Set the workflow stage status."""
# FIXME(BM) This is currently a hack because workflow stages
# don't each have their own db entry.
pb_key = SchedulingObject.get_key(PB_KEY, self._pb_id)
stages = DB.get_hash_value(pb_key, 'workflow_stages')
... | [
"def",
"status",
"(",
"self",
",",
"value",
")",
":",
"# FIXME(BM) This is currently a hack because workflow stages",
"# don't each have their own db entry.",
"pb_key",
"=",
"SchedulingObject",
".",
"get_key",
"(",
"PB_KEY",
",",
"self",
".",
"_pb_id",
")",
"sta... | 51.111111 | 0.004274 |
def download(source=None, username=None, directory='.', max_size='128m',
quiet=None, debug=None):
"""
Download public data from Open Humans.
:param source: This field is the data source from which to download. It's
default value is None.
:param username: This fiels is username of u... | [
"def",
"download",
"(",
"source",
"=",
"None",
",",
"username",
"=",
"None",
",",
"directory",
"=",
"'.'",
",",
"max_size",
"=",
"'128m'",
",",
"quiet",
"=",
"None",
",",
"debug",
"=",
"None",
")",
":",
"if",
"debug",
":",
"logging",
".",
"basicConfi... | 29.732394 | 0.000459 |
def cpf(numero):
"""Valida um número de CPF. O número deverá ser informado como uma string
contendo 11 dígitos numéricos. Se o número informado for inválido será
lançada a exceção :exc:`NumeroCPFError`. Esta implementação da validação
foi delicadamente copiada de `python-sped <http://git.io/vfuGW>`.
... | [
"def",
"cpf",
"(",
"numero",
")",
":",
"_digitos",
"=",
"[",
"int",
"(",
"c",
")",
"for",
"c",
"in",
"numero",
"if",
"c",
".",
"isdigit",
"(",
")",
"]",
"if",
"len",
"(",
"_digitos",
")",
"!=",
"11",
"or",
"len",
"(",
"numero",
")",
"!=",
"11... | 37.275862 | 0.001803 |
def build_estimator(model_dir, model_type, model_column_fn, inter_op, intra_op, ctx):
"""Build an estimator appropriate for the given model type."""
wide_columns, deep_columns = model_column_fn()
hidden_units = [100, 75, 50, 25]
# Create a tf.estimator.RunConfig to ensure the model is run on CPU, which
# tra... | [
"def",
"build_estimator",
"(",
"model_dir",
",",
"model_type",
",",
"model_column_fn",
",",
"inter_op",
",",
"intra_op",
",",
"ctx",
")",
":",
"wide_columns",
",",
"deep_columns",
"=",
"model_column_fn",
"(",
")",
"hidden_units",
"=",
"[",
"100",
",",
"75",
... | 43.6875 | 0.009797 |
def fill_out_and_submit(self, data, prefix='', skip_reset=False):
"""
Calls :py:meth:`~.Form.fill_out` and then :py:meth:`.submit`.
"""
self.fill_out(data, prefix, skip_reset)
self.submit() | [
"def",
"fill_out_and_submit",
"(",
"self",
",",
"data",
",",
"prefix",
"=",
"''",
",",
"skip_reset",
"=",
"False",
")",
":",
"self",
".",
"fill_out",
"(",
"data",
",",
"prefix",
",",
"skip_reset",
")",
"self",
".",
"submit",
"(",
")"
] | 37.333333 | 0.008734 |
def __ensure_gcloud():
"""The *NIX installer is not guaranteed to add the google cloud sdk to the
user's PATH (the Windows installer does). This ensures that if the default
directory for the executables exists, it is added to the PATH for the
duration of this package's use."""
if which('gcloud') is ... | [
"def",
"__ensure_gcloud",
"(",
")",
":",
"if",
"which",
"(",
"'gcloud'",
")",
"is",
"None",
":",
"gcloud_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'google-cloud-sdk'",
",",
"'bin'",
... | 49.071429 | 0.001429 |
def voicing_measures(ref_voicing, est_voicing):
"""Compute the voicing recall and false alarm rates given two voicing
indicator sequences, one as reference (truth) and the other as the estimate
(prediction). The sequences must be of the same length.
Examples
--------
>>> ref_time, ref_freq = m... | [
"def",
"voicing_measures",
"(",
"ref_voicing",
",",
"est_voicing",
")",
":",
"validate_voicing",
"(",
"ref_voicing",
",",
"est_voicing",
")",
"ref_voicing",
"=",
"ref_voicing",
".",
"astype",
"(",
"bool",
")",
"est_voicing",
"=",
"est_voicing",
".",
"astype",
"(... | 35.028986 | 0.000402 |
def register_pickle():
"""The fastest serialization method, but restricts
you to python clients."""
import cPickle
registry.register('pickle', cPickle.dumps, cPickle.loads,
content_type='application/x-python-serialize',
content_encoding='binary') | [
"def",
"register_pickle",
"(",
")",
":",
"import",
"cPickle",
"registry",
".",
"register",
"(",
"'pickle'",
",",
"cPickle",
".",
"dumps",
",",
"cPickle",
".",
"loads",
",",
"content_type",
"=",
"'application/x-python-serialize'",
",",
"content_encoding",
"=",
"'... | 42.857143 | 0.003268 |
def split_utxos(self, wif, limit, fee=10000, max_outputs=100):
"""Split utxos of <wif> unitil <limit> or <max_outputs> reached."""
key = deserialize.key(self.testnet, wif)
limit = deserialize.positive_integer(limit)
fee = deserialize.positive_integer(fee)
max_outputs = deserializ... | [
"def",
"split_utxos",
"(",
"self",
",",
"wif",
",",
"limit",
",",
"fee",
"=",
"10000",
",",
"max_outputs",
"=",
"100",
")",
":",
"key",
"=",
"deserialize",
".",
"key",
"(",
"self",
".",
"testnet",
",",
"wif",
")",
"limit",
"=",
"deserialize",
".",
... | 59.166667 | 0.002774 |
def get_agent(self):
"""Gets the ``Agent`` identified in this authentication credential.
:return: the ``Agent``
:rtype: ``osid.authentication.Agent``
:raise: ``OperationFailed`` -- unable to complete request
*compliance: mandatory -- This method must be implemented.*
"... | [
"def",
"get_agent",
"(",
"self",
")",
":",
"agent_id",
"=",
"self",
".",
"get_agent_id",
"(",
")",
"return",
"Agent",
"(",
"identifier",
"=",
"agent_id",
".",
"identifier",
",",
"namespace",
"=",
"agent_id",
".",
"namespace",
",",
"authority",
"=",
"agent_... | 35.928571 | 0.003876 |
def _iter_frequencies(self):
"""Iterate over the frequencies of this `QPlane`
"""
# work out how many frequencies we need
minf, maxf = self.frange
fcum_mismatch = log(maxf / minf) * (2 + self.q**2)**(1/2.) / 2.
nfreq = int(max(1, ceil(fcum_mismatch / self.deltam)))
... | [
"def",
"_iter_frequencies",
"(",
"self",
")",
":",
"# work out how many frequencies we need",
"minf",
",",
"maxf",
"=",
"self",
".",
"frange",
"fcum_mismatch",
"=",
"log",
"(",
"maxf",
"/",
"minf",
")",
"*",
"(",
"2",
"+",
"self",
".",
"q",
"**",
"2",
")... | 42.214286 | 0.003311 |
def Process(self, parser_mediator, root_item=None, **kwargs):
"""Parses an OLECF file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
root_item (Optional[pyolecf.item]): root item of the OLECF file.
Raise... | [
"def",
"Process",
"(",
"self",
",",
"parser_mediator",
",",
"root_item",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# This will raise if unhandled keyword arguments are passed.",
"super",
"(",
"AutomaticDestinationsOLECFPlugin",
",",
"self",
")",
".",
"Process",... | 34.527778 | 0.007042 |
def loadFromFile(fileName):
"""
load the configuration for the ReturnInfo from a fileName
@param fileName: filename that contains the json configuration to use in the ReturnInfo
"""
assert os.path.exists(fileName), "File " + fileName + " does not exist"
conf = json.load(o... | [
"def",
"loadFromFile",
"(",
"fileName",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"fileName",
")",
",",
"\"File \"",
"+",
"fileName",
"+",
"\" does not exist\"",
"conf",
"=",
"json",
".",
"load",
"(",
"open",
"(",
"fileName",
")",
")",
... | 57.444444 | 0.004757 |
def GroupsPost(self, parameters):
"""
Create a group in CommonSense.
If GroupsPost is successful, the group details, including its group_id, can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictonary) - Dictionary c... | [
"def",
"GroupsPost",
"(",
"self",
",",
"parameters",
")",
":",
"if",
"self",
".",
"__SenseApiCall__",
"(",
"'/groups.json'",
",",
"'POST'",
",",
"parameters",
"=",
"parameters",
")",
":",
"return",
"True",
"else",
":",
"self",
".",
"__error__",
"=",
"\"api... | 49.714286 | 0.015515 |
def to_checksum_address(value: AnyStr) -> ChecksumAddress:
"""
Makes a checksum address given a supported format.
"""
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address)))
checksum_address = add_0x_prefix(
"".join(
... | [
"def",
"to_checksum_address",
"(",
"value",
":",
"AnyStr",
")",
"->",
"ChecksumAddress",
":",
"norm_address",
"=",
"to_normalized_address",
"(",
"value",
")",
"address_hash",
"=",
"encode_hex",
"(",
"keccak",
"(",
"text",
"=",
"remove_0x_prefix",
"(",
"norm_addres... | 30.611111 | 0.001761 |
def extend_array(edges, binsz, lo, hi):
"""Extend an array to encompass lo and hi values."""
numlo = int(np.ceil((edges[0] - lo) / binsz))
numhi = int(np.ceil((hi - edges[-1]) / binsz))
edges = copy.deepcopy(edges)
if numlo > 0:
edges_lo = np.linspace(edges[0] - numlo * binsz, edges[0], nu... | [
"def",
"extend_array",
"(",
"edges",
",",
"binsz",
",",
"lo",
",",
"hi",
")",
":",
"numlo",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"(",
"edges",
"[",
"0",
"]",
"-",
"lo",
")",
"/",
"binsz",
")",
")",
"numhi",
"=",
"int",
"(",
"np",
".",
"... | 33.6875 | 0.001805 |
def false_positives(links_true, links_pred):
"""Count the number of False Positives.
Returns the number of incorrect predictions of true non-links. (true non-
links, but predicted as links). This value is known as the number of False
Positives (FP).
Parameters
----------
links_true: pandas... | [
"def",
"false_positives",
"(",
"links_true",
",",
"links_pred",
")",
":",
"links_true",
"=",
"_get_multiindex",
"(",
"links_true",
")",
"links_pred",
"=",
"_get_multiindex",
"(",
"links_pred",
")",
"return",
"len",
"(",
"links_pred",
".",
"difference",
"(",
"lin... | 27.8 | 0.001391 |
def api_user(request, userPk, key=None, hproPk=None):
"""Return information about an user"""
if not check_api_key(request, key, hproPk):
return HttpResponseForbidden
if settings.PIAPI_STANDALONE:
if not settings.PIAPI_REALUSERS:
user = generate_user(pk=userPk)
if us... | [
"def",
"api_user",
"(",
"request",
",",
"userPk",
",",
"key",
"=",
"None",
",",
"hproPk",
"=",
"None",
")",
":",
"if",
"not",
"check_api_key",
"(",
"request",
",",
"key",
",",
"hproPk",
")",
":",
"return",
"HttpResponseForbidden",
"if",
"settings",
".",
... | 33.745455 | 0.001571 |
def fromDict(cls, _dict):
""" Builds instance from dictionary of properties. """
obj = cls()
obj.__dict__.update(_dict)
return obj | [
"def",
"fromDict",
"(",
"cls",
",",
"_dict",
")",
":",
"obj",
"=",
"cls",
"(",
")",
"obj",
".",
"__dict__",
".",
"update",
"(",
"_dict",
")",
"return",
"obj"
] | 31.6 | 0.012346 |
def _parse(self):
""" Given self.resource, split information from the CTS API
:return: None
"""
self.response = self.resource
self.resource = self.resource.xpath("//ti:passage/tei:TEI", namespaces=XPATH_NAMESPACES)[0]
self._prev_id, self._next_id = _SharedMethod.prevnex... | [
"def",
"_parse",
"(",
"self",
")",
":",
"self",
".",
"response",
"=",
"self",
".",
"resource",
"self",
".",
"resource",
"=",
"self",
".",
"resource",
".",
"xpath",
"(",
"\"//ti:passage/tei:TEI\"",
",",
"namespaces",
"=",
"XPATH_NAMESPACES",
")",
"[",
"0",
... | 40.933333 | 0.006369 |
def _zone_expired(self, zone):
"""
Determine if a zone is expired or not.
:param zone: zone number
:type zone: int
:returns: whether or not the zone is expired
"""
return (time.time() > self._zones[zone].timestamp + Zonetracker.EXPIRE) and self._zones[zone].expa... | [
"def",
"_zone_expired",
"(",
"self",
",",
"zone",
")",
":",
"return",
"(",
"time",
".",
"time",
"(",
")",
">",
"self",
".",
"_zones",
"[",
"zone",
"]",
".",
"timestamp",
"+",
"Zonetracker",
".",
"EXPIRE",
")",
"and",
"self",
".",
"_zones",
"[",
"zo... | 32.4 | 0.009009 |
def fetch_request_ids(item_ids, cls, attr_name, verification_list=None):
"""Return a list of cls instances for all the ids provided in item_ids.
:param item_ids: The list of ids to fetch objects for
:param cls: The class to fetch the ids from
:param attr_name: The name of the attribute for exception pu... | [
"def",
"fetch_request_ids",
"(",
"item_ids",
",",
"cls",
",",
"attr_name",
",",
"verification_list",
"=",
"None",
")",
":",
"if",
"not",
"item_ids",
":",
"return",
"[",
"]",
"items",
"=",
"[",
"]",
"for",
"item_id",
"in",
"item_ids",
":",
"item",
"=",
... | 37.681818 | 0.001176 |
def get_permissions(self):
"""
Permissions of the user.
Returns:
List of Permission objects.
"""
user_role = self.last_login_role() if self.last_login_role_key else self.role_set[0].role
return user_role.get_permissions() | [
"def",
"get_permissions",
"(",
"self",
")",
":",
"user_role",
"=",
"self",
".",
"last_login_role",
"(",
")",
"if",
"self",
".",
"last_login_role_key",
"else",
"self",
".",
"role_set",
"[",
"0",
"]",
".",
"role",
"return",
"user_role",
".",
"get_permissions",... | 30.444444 | 0.010638 |
def _create_merge_filelist(bam_files, base_file, config):
"""Create list of input files for merge, ensuring all files are valid.
"""
bam_file_list = "%s.list" % os.path.splitext(base_file)[0]
samtools = config_utils.get_program("samtools", config)
with open(bam_file_list, "w") as out_handle:
... | [
"def",
"_create_merge_filelist",
"(",
"bam_files",
",",
"base_file",
",",
"config",
")",
":",
"bam_file_list",
"=",
"\"%s.list\"",
"%",
"os",
".",
"path",
".",
"splitext",
"(",
"base_file",
")",
"[",
"0",
"]",
"samtools",
"=",
"config_utils",
".",
"get_progr... | 48.181818 | 0.001852 |
def process_command_line(argv):
""" parses the arguments.
removes our arguments from the command line """
setup = {}
for handler in ACCEPTED_ARG_HANDLERS:
setup[handler.arg_name] = handler.default_val
setup['file'] = ''
setup['qt-support'] = ''
i = 0
del argv[0]
while i ... | [
"def",
"process_command_line",
"(",
"argv",
")",
":",
"setup",
"=",
"{",
"}",
"for",
"handler",
"in",
"ACCEPTED_ARG_HANDLERS",
":",
"setup",
"[",
"handler",
".",
"arg_name",
"]",
"=",
"handler",
".",
"default_val",
"setup",
"[",
"'file'",
"]",
"=",
"''",
... | 39.283019 | 0.003749 |
def force_unicode(raw):
'''Try really really hard to get a Unicode copy of a string.
First try :class:`BeautifulSoup.UnicodeDammit` to try to force
to Unicode; if that fails, assume UTF-8 encoding, and ignore
all errors.
:param str raw: string to coerce
:return: Unicode approximation of `raw`
... | [
"def",
"force_unicode",
"(",
"raw",
")",
":",
"converted",
"=",
"UnicodeDammit",
"(",
"raw",
",",
"isHTML",
"=",
"True",
")",
"if",
"not",
"converted",
".",
"unicode",
":",
"converted",
".",
"unicode",
"=",
"unicode",
"(",
"raw",
",",
"'utf8'",
",",
"e... | 30.695652 | 0.001374 |
def _get_objects_by_path(self, paths):
"""Return a list of all bluez DBus objects from the provided list of paths.
"""
return map(lambda x: self._bus.get_object('org.bluez', x), paths) | [
"def",
"_get_objects_by_path",
"(",
"self",
",",
"paths",
")",
":",
"return",
"map",
"(",
"lambda",
"x",
":",
"self",
".",
"_bus",
".",
"get_object",
"(",
"'org.bluez'",
",",
"x",
")",
",",
"paths",
")"
] | 51.25 | 0.014423 |
def fixup_scipy_ndimage_result(whatever_it_returned):
"""Convert a result from scipy.ndimage to a numpy array
scipy.ndimage has the annoying habit of returning a single, bare
value instead of an array if the indexes passed in are of length 1.
For instance:
scind.maximum(image, labels, [1]) retu... | [
"def",
"fixup_scipy_ndimage_result",
"(",
"whatever_it_returned",
")",
":",
"if",
"getattr",
"(",
"whatever_it_returned",
",",
"\"__getitem__\"",
",",
"False",
")",
":",
"return",
"np",
".",
"array",
"(",
"whatever_it_returned",
")",
"else",
":",
"return",
"np",
... | 39.357143 | 0.007092 |
def and_evaluator(conditions, leaf_evaluator):
""" Evaluates a list of conditions as if the evaluator had been applied
to each entry and the results AND-ed together.
Args:
conditions: List of conditions ex: [operand_1, operand_2].
leaf_evaluator: Function which will be called to evaluate leaf condition v... | [
"def",
"and_evaluator",
"(",
"conditions",
",",
"leaf_evaluator",
")",
":",
"saw_null_result",
"=",
"False",
"for",
"condition",
"in",
"conditions",
":",
"result",
"=",
"evaluate",
"(",
"condition",
",",
"leaf_evaluator",
")",
"if",
"result",
"is",
"False",
":... | 30.333333 | 0.010652 |
def verify(self, msg, sig, key):
"""
Verify a message signature
:param msg: The message
:param sig: A signature
:param key: A ec.EllipticCurvePublicKey to use for the verification.
:raises: BadSignature if the signature can't be verified.
:return: True
""... | [
"def",
"verify",
"(",
"self",
",",
"msg",
",",
"sig",
",",
"key",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"ec",
".",
"EllipticCurvePublicKey",
")",
":",
"raise",
"TypeError",
"(",
"\"The public key must be an instance of \"",
"\"ec.EllipticCurvePub... | 35.870968 | 0.001751 |
def start(self, *args, **kwargs):#pylint:disable=unused-argument
"""
| Launch the consumer.
| It can listen forever for messages or just wait for one.
:param forever: If set, the consumer listens forever. Default to `True`.
:type forever: bool
:param timeout: If set, the... | [
"def",
"start",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#pylint:disable=unused-argument",
"forever",
"=",
"kwargs",
".",
"get",
"(",
"'forever'",
",",
"True",
")",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
",",
... | 40.9 | 0.008363 |
def append_text(self, content):
"""
Append text nodes into L{Content.data}
@param content: The current content being unmarshalled.
@type content: L{Content}
"""
if content.node.hasText():
content.text = content.node.getText() | [
"def",
"append_text",
"(",
"self",
",",
"content",
")",
":",
"if",
"content",
".",
"node",
".",
"hasText",
"(",
")",
":",
"content",
".",
"text",
"=",
"content",
".",
"node",
".",
"getText",
"(",
")"
] | 34.75 | 0.007018 |
def sched(self):
""" Yield CPU.
This will choose another process from the running list and change
current running process. May give the same cpu if only one running
process.
"""
if len(self.procs) > 1:
logger.debug("SCHED:")
logger.debu... | [
"def",
"sched",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"procs",
")",
">",
"1",
":",
"logger",
".",
"debug",
"(",
"\"SCHED:\"",
")",
"logger",
".",
"debug",
"(",
"f\"\\tProcess: {self.procs!r}\"",
")",
"logger",
".",
"debug",
"(",
"f\"\\t... | 47 | 0.003475 |
def openOrder(self, orderId, contract, order, orderState):
"""
This wrapper is called to:
* feed in open orders at startup;
* feed in open orders or order updates from other clients and TWS
if clientId=master id;
* feed in manual orders and order updates from TWS if cl... | [
"def",
"openOrder",
"(",
"self",
",",
"orderId",
",",
"contract",
",",
"order",
",",
"orderState",
")",
":",
"if",
"order",
".",
"whatIf",
":",
"# response to whatIfOrder",
"self",
".",
"_endReq",
"(",
"order",
".",
"orderId",
",",
"orderState",
")",
"else... | 42.242424 | 0.001403 |
def delete_alias(self, alias_name):
"""Delete the alias."""
for aliases in self.key_to_aliases.values():
if alias_name in aliases:
aliases.remove(alias_name) | [
"def",
"delete_alias",
"(",
"self",
",",
"alias_name",
")",
":",
"for",
"aliases",
"in",
"self",
".",
"key_to_aliases",
".",
"values",
"(",
")",
":",
"if",
"alias_name",
"in",
"aliases",
":",
"aliases",
".",
"remove",
"(",
"alias_name",
")"
] | 39.4 | 0.00995 |
def _left_motion(self, event):
"""Function bound to move event for marker canvas"""
iid = self.current_iid
if iid is None:
return
marker = self._markers[iid]
if marker["move"] is False:
return
delta = marker["finish"] - marker["start"]
# Li... | [
"def",
"_left_motion",
"(",
"self",
",",
"event",
")",
":",
"iid",
"=",
"self",
".",
"current_iid",
"if",
"iid",
"is",
"None",
":",
"return",
"marker",
"=",
"self",
".",
"_markers",
"[",
"iid",
"]",
"if",
"marker",
"[",
"\"move\"",
"]",
"is",
"False"... | 51.64 | 0.003294 |
def federated_query(self,
environment_id,
filter=None,
query=None,
natural_language_query=None,
passages=None,
aggregation=None,
count=None,
... | [
"def",
"federated_query",
"(",
"self",
",",
"environment_id",
",",
"filter",
"=",
"None",
",",
"query",
"=",
"None",
",",
"natural_language_query",
"=",
"None",
",",
"passages",
"=",
"None",
",",
"aggregation",
"=",
"None",
",",
"count",
"=",
"None",
",",
... | 53.4 | 0.009315 |
def rec_edit(self, zone, record_type, record_id, name, content, ttl=1, service_mode=None, priority=None,
service=None, service_name=None, protocol=None, weight=None, port=None, target=None):
"""
Edit a DNS record for the given zone.
:param zone: domain name
:type zone: s... | [
"def",
"rec_edit",
"(",
"self",
",",
"zone",
",",
"record_type",
",",
"record_id",
",",
"name",
",",
"content",
",",
"ttl",
"=",
"1",
",",
"service_mode",
"=",
"None",
",",
"priority",
"=",
"None",
",",
"service",
"=",
"None",
",",
"service_name",
"=",... | 40.080645 | 0.003928 |
def oauth2_auth_url(redirect_uri=None, client_id=None, base_url=OH_BASE_URL):
"""
Returns an OAuth2 authorization URL for a project, given Client ID. This
function constructs an authorization URL for a user to follow.
The user will be redirected to Authorize Open Humans data for our external
applica... | [
"def",
"oauth2_auth_url",
"(",
"redirect_uri",
"=",
"None",
",",
"client_id",
"=",
"None",
",",
"base_url",
"=",
"OH_BASE_URL",
")",
":",
"if",
"not",
"client_id",
":",
"client_id",
"=",
"os",
".",
"getenv",
"(",
"'OHAPI_CLIENT_ID'",
")",
"if",
"not",
"cli... | 43.764706 | 0.000657 |
def setEditorData(self, editor, index):
"""Sets the current data for the editor.
The data displayed has the same value as `index.data(Qt.EditRole)`
(the translated name of the datatype). Therefor a lookup for all items
of the combobox is made and the matching item is set as the currentl... | [
"def",
"setEditorData",
"(",
"self",
",",
"editor",
",",
"index",
")",
":",
"editor",
".",
"blockSignals",
"(",
"True",
")",
"data",
"=",
"index",
".",
"data",
"(",
")",
"dataIndex",
"=",
"editor",
".",
"findData",
"(",
"data",
")",
"# dataIndex = editor... | 40.727273 | 0.004362 |
def hostapi_info(index=None):
"""Return a generator with information about each host API.
If index is given, only one dictionary for the given host API is
returned.
"""
if index is None:
return (hostapi_info(i) for i in range(_pa.Pa_GetHostApiCount()))
else:
info = _pa.Pa_GetHo... | [
"def",
"hostapi_info",
"(",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"return",
"(",
"hostapi_info",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"_pa",
".",
"Pa_GetHostApiCount",
"(",
")",
")",
")",
"else",
":",
"info",
"... | 37.294118 | 0.001538 |
def _get_name_info(name_index, name_list):
"""Helper to get optional details about named references
Returns the dereferenced name as both value and repr if the name
list is defined.
Otherwise returns the name index and its repr().
"""
argval = name_index
if (name_list is not None
... | [
"def",
"_get_name_info",
"(",
"name_index",
",",
"name_list",
")",
":",
"argval",
"=",
"name_index",
"if",
"(",
"name_list",
"is",
"not",
"None",
"# PyPY seems to \"optimize\" out constant names,",
"# so we need for that:",
"and",
"name_index",
"<",
"len",
"(",
"name_... | 33.058824 | 0.00346 |
def reshape(self, data_shapes, label_shapes):
"""Reshape executors.
Parameters
----------
data_shapes : list
label_shapes : list
"""
if data_shapes == self.data_shapes and label_shapes == self.label_shapes:
return
if self._default_execs is Non... | [
"def",
"reshape",
"(",
"self",
",",
"data_shapes",
",",
"label_shapes",
")",
":",
"if",
"data_shapes",
"==",
"self",
".",
"data_shapes",
"and",
"label_shapes",
"==",
"self",
".",
"label_shapes",
":",
"return",
"if",
"self",
".",
"_default_execs",
"is",
"None... | 33.230769 | 0.006757 |
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look ... | [
"def",
"import_string",
"(",
"dotted_path",
")",
":",
"try",
":",
"module_path",
",",
"class_name",
"=",
"dotted_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":",
"msg",
"=",
"\"%s doesn't look like a module path\"",
"%",
"dotted_path... | 35.6 | 0.001368 |
def current_frame(self):
"""
Compute the number of the current frame (0-indexed)
"""
if not self._pause_level:
return (
int((self._clock() + self._offset) * self.frames_per_second)
% len(self._frames)
)
else:
ret... | [
"def",
"current_frame",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pause_level",
":",
"return",
"(",
"int",
"(",
"(",
"self",
".",
"_clock",
"(",
")",
"+",
"self",
".",
"_offset",
")",
"*",
"self",
".",
"frames_per_second",
")",
"%",
"len",
... | 30.181818 | 0.005848 |
def to_color(self):
"""Convert the grayscale image to a ColorImage.
Returns
-------
:obj:`ColorImage`
A color image equivalent to the grayscale one.
"""
color_data = np.repeat(self.data[:,:,np.newaxis], 3, axis=2)
return ColorImage(color_data, self._f... | [
"def",
"to_color",
"(",
"self",
")",
":",
"color_data",
"=",
"np",
".",
"repeat",
"(",
"self",
".",
"data",
"[",
":",
",",
":",
",",
"np",
".",
"newaxis",
"]",
",",
"3",
",",
"axis",
"=",
"2",
")",
"return",
"ColorImage",
"(",
"color_data",
",",
... | 31.6 | 0.012308 |
def get_latex(ink_filename):
"""Get the LaTeX string from a file by the *.ink filename."""
tex_file = os.path.splitext(ink_filename)[0] + ".tex"
with open(tex_file) as f:
tex_content = f.read().strip()
pattern = re.compile(r"\\begin\{displaymath\}(.*?)\\end\{displaymath\}",
... | [
"def",
"get_latex",
"(",
"ink_filename",
")",
":",
"tex_file",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"ink_filename",
")",
"[",
"0",
"]",
"+",
"\".tex\"",
"with",
"open",
"(",
"tex_file",
")",
"as",
"f",
":",
"tex_content",
"=",
"f",
".",
"rea... | 38.846154 | 0.000966 |
def reboot(name, call=None):
'''
reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
node = get_node(name)
ret = ... | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"node",
"=",
"get_node",
"(",
"name",
")",
"ret",
"=",
"take_action",
"(",
"name",
"=",
"name",
",",
"call",
"=",
"call",
",",
"method",
"=",
"'POST'",
",",
"command",
"=",
"'my/mach... | 29.833333 | 0.001805 |
def call_actions_parallel_future(self, service_name, actions, **kwargs):
"""
This method is identical in signature and behavior to `call_actions_parallel`, except that it sends the requests
and then immediately returns a `FutureResponse` instead of blocking waiting on responses and returning a
... | [
"def",
"call_actions_parallel_future",
"(",
"self",
",",
"service_name",
",",
"actions",
",",
"*",
"*",
"kwargs",
")",
":",
"job_responses",
"=",
"self",
".",
"call_jobs_parallel_future",
"(",
"jobs",
"=",
"(",
"{",
"'service_name'",
":",
"service_name",
",",
... | 54.84375 | 0.007279 |
def norm(x, encoding="latin1"):
"Convertir acentos codificados en ISO 8859-1 u otro, a ASCII regular"
if not isinstance(x, basestring):
x = unicode(x)
elif isinstance(x, str):
x = x.decode(encoding, 'ignore')
return unicodedata.normalize('NFKD', x).encode('ASCII', 'ignore') | [
"def",
"norm",
"(",
"x",
",",
"encoding",
"=",
"\"latin1\"",
")",
":",
"if",
"not",
"isinstance",
"(",
"x",
",",
"basestring",
")",
":",
"x",
"=",
"unicode",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"str",
")",
":",
"x",
"=",
"x",
".... | 42.857143 | 0.003268 |
def isa_from_graph(graph: nx.Graph, oneq_type='Xhalves', twoq_type='CZ') -> ISA:
"""
Generate an ISA object from a NetworkX graph.
:param graph: The graph
:param oneq_type: The type of 1-qubit gate. Currently 'Xhalves'
:param twoq_type: The type of 2-qubit gate. One of 'CZ' or 'CPHASE'.
"""
... | [
"def",
"isa_from_graph",
"(",
"graph",
":",
"nx",
".",
"Graph",
",",
"oneq_type",
"=",
"'Xhalves'",
",",
"twoq_type",
"=",
"'CZ'",
")",
"->",
"ISA",
":",
"all_qubits",
"=",
"list",
"(",
"range",
"(",
"max",
"(",
"graph",
".",
"nodes",
")",
"+",
"1",
... | 46.666667 | 0.007005 |
def serialize_model(model):
"""Serialize the HTK model into a file.
:param model: Model to be serialized
"""
result = ''
# First serialize the macros
for macro in model['macros']:
if macro.get('options', None):
result += '~o '
for option in macro['options']['de... | [
"def",
"serialize_model",
"(",
"model",
")",
":",
"result",
"=",
"''",
"# First serialize the macros",
"for",
"macro",
"in",
"model",
"[",
"'macros'",
"]",
":",
"if",
"macro",
".",
"get",
"(",
"'options'",
",",
"None",
")",
":",
"result",
"+=",
"'~o '",
... | 34.266667 | 0.000631 |
def transliterate(mode, string, ignore = '', reverse = False ):
# @todo: arabtex and iso8859-6 need individual handling because in some cases using one-two mapping
"""
encode & decode different romanization systems
:param mode:
:param string:
:param ignore:
:param reverse:
:return:
... | [
"def",
"transliterate",
"(",
"mode",
",",
"string",
",",
"ignore",
"=",
"''",
",",
"reverse",
"=",
"False",
")",
":",
"# @todo: arabtex and iso8859-6 need individual handling because in some cases using one-two mapping",
"if",
"mode",
"in",
"available_transliterate_systems",
... | 26.84375 | 0.007865 |
def make(self):
"""
Make the lock file.
"""
try:
# Create the lock file
self.mkfile(self.lock_file)
except Exception as e:
self.die('Failed to generate lock file: {}'.format(str(e))) | [
"def",
"make",
"(",
"self",
")",
":",
"try",
":",
"# Create the lock file",
"self",
".",
"mkfile",
"(",
"self",
".",
"lock_file",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"die",
"(",
"'Failed to generate lock file: {}'",
".",
"format",
"(",
... | 26.6 | 0.010909 |
def attach(self, lun_or_snap, skip_hlu_0=False):
""" Attaches lun, snap or member snap of cg snap to host.
Don't pass cg snapshot in as `lun_or_snap`.
:param lun_or_snap: the lun, snap, or a member snap of cg snap
:param skip_hlu_0: whether to skip hlu 0
:return: the hlu number... | [
"def",
"attach",
"(",
"self",
",",
"lun_or_snap",
",",
"skip_hlu_0",
"=",
"False",
")",
":",
"# `UnityResourceAlreadyAttachedError` check was removed due to there",
"# is a host cache existing in Cinder driver. If the lun was attached to",
"# the host and the info was stored in the cache... | 41.096774 | 0.001534 |
def artist(self):
"""
:class:`Artist` object of album's artist
"""
if not self._artist:
self._artist = Artist(self._artist_id, self._artist_name, self._connection)
return self._artist | [
"def",
"artist",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_artist",
":",
"self",
".",
"_artist",
"=",
"Artist",
"(",
"self",
".",
"_artist_id",
",",
"self",
".",
"_artist_name",
",",
"self",
".",
"_connection",
")",
"return",
"self",
".",
"_... | 32.714286 | 0.012766 |
def _nullpager(stream, generator, color):
"""Simply print unformatted text. This is the ultimate fallback."""
for text in generator:
if not color:
text = strip_ansi(text)
stream.write(text) | [
"def",
"_nullpager",
"(",
"stream",
",",
"generator",
",",
"color",
")",
":",
"for",
"text",
"in",
"generator",
":",
"if",
"not",
"color",
":",
"text",
"=",
"strip_ansi",
"(",
"text",
")",
"stream",
".",
"write",
"(",
"text",
")"
] | 36.833333 | 0.004425 |
def djng_locale_script(context, default_language='en'):
"""
Returns a script tag for including the proper locale script in any HTML page.
This tag determines the current language with its locale.
Usage:
<script src="{% static 'node_modules/angular-i18n/' %}{% djng_locale_script %}"></script>
... | [
"def",
"djng_locale_script",
"(",
"context",
",",
"default_language",
"=",
"'en'",
")",
":",
"language",
"=",
"get_language_from_request",
"(",
"context",
"[",
"'request'",
"]",
")",
"if",
"not",
"language",
":",
"language",
"=",
"default_language",
"return",
"f... | 45.642857 | 0.006135 |
def _report_profile(self, command, lock_name, elapsed_time, memory):
"""
Writes a string to self.pipeline_profile_file.
"""
message_raw = str(command) + "\t " + \
str(lock_name) + "\t" + \
str(datetime.timedelta(seconds = round(elapsed_time, 2))) + "\t " + \
... | [
"def",
"_report_profile",
"(",
"self",
",",
"command",
",",
"lock_name",
",",
"elapsed_time",
",",
"memory",
")",
":",
"message_raw",
"=",
"str",
"(",
"command",
")",
"+",
"\"\\t \"",
"+",
"str",
"(",
"lock_name",
")",
"+",
"\"\\t\"",
"+",
"str",
"(",
... | 39.636364 | 0.011211 |
def getEdgeDirected(self, networkId, edgeId, verbose=None):
"""
Returns true if the edge specified by the `edgeId` and `networkId` parameters is directed.
:param networkId: SUID of the network containing the edge
:param edgeId: SUID of the edge
:param verbose: print more
... | [
"def",
"getEdgeDirected",
"(",
"self",
",",
"networkId",
",",
"edgeId",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'networks/'",
"+",
"str",
"(",
"networkId",
")",
"+",
"'/edges/'",
"+",... | 41.076923 | 0.009158 |
def GetHTTPHeaders(self):
"""Returns the HTTP headers required for request authorization.
Returns:
A dictionary containing the required headers.
"""
http_headers = self._adwords_client.oauth2_client.CreateHttpHeader()
if self.enable_compression:
http_headers['accept-encoding'] = 'gzip'
... | [
"def",
"GetHTTPHeaders",
"(",
"self",
")",
":",
"http_headers",
"=",
"self",
".",
"_adwords_client",
".",
"oauth2_client",
".",
"CreateHttpHeader",
"(",
")",
"if",
"self",
".",
"enable_compression",
":",
"http_headers",
"[",
"'accept-encoding'",
"]",
"=",
"'gzip... | 29.461538 | 0.005063 |
def gene_dir(self):
"""Gene folder"""
if self.root_dir:
return op.join(self.root_dir, self.id)
else:
return None | [
"def",
"gene_dir",
"(",
"self",
")",
":",
"if",
"self",
".",
"root_dir",
":",
"return",
"op",
".",
"join",
"(",
"self",
".",
"root_dir",
",",
"self",
".",
"id",
")",
"else",
":",
"return",
"None"
] | 25.833333 | 0.0125 |
def policy_map_clss_priority_mapping_table_imprt_cee(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
po_name_key = ET.SubElement(policy_map, "po-name")
... | [
"def",
"policy_map_clss_priority_mapping_table_imprt_cee",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"policy_map",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"policy-map\"",
",",
"xmln... | 47.647059 | 0.003632 |
def fulfill(self, agreement_id, message, account_address, signature, from_account):
"""
Fulfill the sign conditon.
:param agreement_id: id of the agreement, hex str
:param message:
:param account_address: ethereum account address, hex str
:param signature: signed agreeme... | [
"def",
"fulfill",
"(",
"self",
",",
"agreement_id",
",",
"message",
",",
"account_address",
",",
"signature",
",",
"from_account",
")",
":",
"return",
"self",
".",
"_fulfill",
"(",
"agreement_id",
",",
"message",
",",
"account_address",
",",
"signature",
",",
... | 34.526316 | 0.004451 |
def distances(self):
"""The matrix with the all-pairs shortest path lenghts"""
from molmod.ext import graphs_floyd_warshall
distances = np.zeros((self.num_vertices,)*2, dtype=int)
#distances[:] = -1 # set all -1, which is just a very big integer
#distances.ravel()[::len(distances... | [
"def",
"distances",
"(",
"self",
")",
":",
"from",
"molmod",
".",
"ext",
"import",
"graphs_floyd_warshall",
"distances",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"num_vertices",
",",
")",
"*",
"2",
",",
"dtype",
"=",
"int",
")",
"#distances[:] = -... | 47.454545 | 0.009398 |
def find_match(self):
"""Try to find a pattern that matches the source and calll a parser
method to create Python objects.
A callback that raises an IgnoredMatchException indicates that the
given string data is ignored by the parser and no objects are created.
If none of the pa... | [
"def",
"find_match",
"(",
"self",
")",
":",
"for",
"pattern",
",",
"callback",
"in",
"self",
".",
"rules",
":",
"match",
"=",
"pattern",
".",
"match",
"(",
"self",
".",
"source",
",",
"pos",
"=",
"self",
".",
"pos",
")",
"if",
"not",
"match",
":",
... | 30.357143 | 0.002281 |
def update_relationship(self, relationship_form):
"""Updates an existing relationship.
arg: relationship_form (osid.relationship.RelationshipForm):
the form containing the elements to be updated
raise: IllegalState - ``relationship_form`` already used in an
u... | [
"def",
"update_relationship",
"(",
"self",
",",
"relationship_form",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.update_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'relationship'",
",",
"collection",
"=",
"'Relationsh... | 53.170732 | 0.004054 |
def make_path(*sub_paths):
"""
Create a path from a list of sub paths.
:param sub_paths: a list of sub paths
:return:
"""
queued_params = [quote(c.encode('utf-8'), '') for c in sub_paths if c not in NULL_VALUES]
queued_params.insert(0, '')
return '/'.join(... | [
"def",
"make_path",
"(",
"*",
"sub_paths",
")",
":",
"queued_params",
"=",
"[",
"quote",
"(",
"c",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"''",
")",
"for",
"c",
"in",
"sub_paths",
"if",
"c",
"not",
"in",
"NULL_VALUES",
"]",
"queued_params",
".",
"i... | 36.222222 | 0.008982 |
def result(self):
"""Return the context result object pulled from the persistence_engine
if it has been set.
"""
if not self._result:
if not self._persistence_engine:
return None
self._result = self._persistence_engine.get_context_result(self)
... | [
"def",
"result",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_result",
":",
"if",
"not",
"self",
".",
"_persistence_engine",
":",
"return",
"None",
"self",
".",
"_result",
"=",
"self",
".",
"_persistence_engine",
".",
"get_context_result",
"(",
"self... | 30.454545 | 0.005797 |
def _add_match(self, match_key, match_value):
"""Adds a match key/value"""
if match_key is None:
raise errors.NullArgument()
self._query_terms[match_key] = str(match_key) + '=' + str(match_value) | [
"def",
"_add_match",
"(",
"self",
",",
"match_key",
",",
"match_value",
")",
":",
"if",
"match_key",
"is",
"None",
":",
"raise",
"errors",
".",
"NullArgument",
"(",
")",
"self",
".",
"_query_terms",
"[",
"match_key",
"]",
"=",
"str",
"(",
"match_key",
")... | 45.4 | 0.008658 |
def _buffer_iter_rows(self, start):
"""
Read in the buffer for iteration
"""
self._row_buffer = self[start:start+self._iter_row_buffer]
# start back at the front of the buffer
self._row_buffer_index = 0 | [
"def",
"_buffer_iter_rows",
"(",
"self",
",",
"start",
")",
":",
"self",
".",
"_row_buffer",
"=",
"self",
"[",
"start",
":",
"start",
"+",
"self",
".",
"_iter_row_buffer",
"]",
"# start back at the front of the buffer",
"self",
".",
"_row_buffer_index",
"=",
"0"... | 30.5 | 0.007968 |
def grab_token(host, email, password):
"""Grab token from gateway. Press sync button before running."""
urllib3.disable_warnings()
url = ('https://' + host + '/gwr/gop.php?cmd=GWRLogin&data=<gip><version>1</version><email>' + str(email) + '</email><password>' + str(password) + '</password></gip>&fmt=xml')
... | [
"def",
"grab_token",
"(",
"host",
",",
"email",
",",
"password",
")",
":",
"urllib3",
".",
"disable_warnings",
"(",
")",
"url",
"=",
"(",
"'https://'",
"+",
"host",
"+",
"'/gwr/gop.php?cmd=GWRLogin&data=<gip><version>1</version><email>'",
"+",
"str",
"(",
"email",... | 55 | 0.003578 |
def _bbox_to_area_polygon(self, bbox):
"""Transforms bounding box into a polygon object in the area CRS.
:param bbox: A bounding box
:type bbox: BBox
:return: A polygon
:rtype: shapely.geometry.polygon.Polygon
"""
projected_bbox = bbox.transform(self.crs)
... | [
"def",
"_bbox_to_area_polygon",
"(",
"self",
",",
"bbox",
")",
":",
"projected_bbox",
"=",
"bbox",
".",
"transform",
"(",
"self",
".",
"crs",
")",
"return",
"projected_bbox",
".",
"geometry"
] | 34.2 | 0.005698 |
def get_symops(self, data):
"""
In order to generate symmetry equivalent positions, the symmetry
operations are parsed. If the symops are not present, the space
group symbol is parsed, and symops are generated.
"""
symops = []
for symmetry_label in ["_symmetry_equ... | [
"def",
"get_symops",
"(",
"self",
",",
"data",
")",
":",
"symops",
"=",
"[",
"]",
"for",
"symmetry_label",
"in",
"[",
"\"_symmetry_equiv_pos_as_xyz\"",
",",
"\"_symmetry_equiv_pos_as_xyz_\"",
",",
"\"_space_group_symop_operation_xyz\"",
",",
"\"_space_group_symop_operatio... | 45.957447 | 0.001586 |
def findAttr(self, svgNode, name):
"""Search an attribute with some name in some node or above.
First the node is searched, then its style attribute, then
the search continues in the node's parent node. If no such
attribute is found, '' is returned.
"""
# This needs als... | [
"def",
"findAttr",
"(",
"self",
",",
"svgNode",
",",
"name",
")",
":",
"# This needs also to lookup values like \"url(#SomeName)\"...",
"if",
"self",
".",
"css_rules",
"is",
"not",
"None",
"and",
"not",
"svgNode",
".",
"attrib",
".",
"get",
"(",
"'__rules_applied'... | 40.730769 | 0.002768 |
def get_redirect_url(self, **kwargs):
"""
Redirect to request parameter 'next' or to referrer if url is not defined.
"""
if self.request.REQUEST.has_key('next'):
return self.request.REQUEST.get('next')
url = RedirectView.get_redirect_url(self, **kwargs)
if u... | [
"def",
"get_redirect_url",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"request",
".",
"REQUEST",
".",
"has_key",
"(",
"'next'",
")",
":",
"return",
"self",
".",
"request",
".",
"REQUEST",
".",
"get",
"(",
"'next'",
")",
"url",... | 39 | 0.015038 |
def pseudo_bytes(num):
"""
Returns num bytes of pseudo random data. Pseudo- random byte
sequences generated by pseudo_bytes() will be unique if
they are of sufficient length, but are not necessarily
unpredictable. They can be used for non-cryptographic purposes
and for certain purposes in crypt... | [
"def",
"pseudo_bytes",
"(",
"num",
")",
":",
"if",
"num",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"'num' should be > 0\"",
")",
"buf",
"=",
"create_string_buffer",
"(",
"num",
")",
"libcrypto",
".",
"RAND_pseudo_bytes",
"(",
"buf",
",",
"num",
")",
"... | 39 | 0.001789 |
def get_active_lines(lines, comment_char="#"):
"""
Returns lines, or parts of lines, from content that are not commented out
or completely empty. The resulting lines are all individually stripped.
This is useful for parsing many config files such as ifcfg.
Parameters:
lines (list): List o... | [
"def",
"get_active_lines",
"(",
"lines",
",",
"comment_char",
"=",
"\"#\"",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"None",
",",
"(",
"line",
".",
"split",
"(",
"comment_char",
",",
"1",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"for",
"l... | 35.259259 | 0.002045 |
def load_data(self):
"""
Loads data from MRMS GRIB2 files and handles compression duties if files are compressed.
"""
data = []
loaded_dates = []
loaded_indices = []
for t, timestamp in enumerate(self.all_dates):
date_str = timestamp.date().strftime("%... | [
"def",
"load_data",
"(",
"self",
")",
":",
"data",
"=",
"[",
"]",
"loaded_dates",
"=",
"[",
"]",
"loaded_indices",
"=",
"[",
"]",
"for",
"t",
",",
"timestamp",
"in",
"enumerate",
"(",
"self",
".",
"all_dates",
")",
":",
"date_str",
"=",
"timestamp",
... | 53 | 0.003163 |
def hatchery():
""" Main entry point for the hatchery program """
args = docopt.docopt(__doc__)
task_list = args['<task>']
if not task_list or 'help' in task_list or args['--help']:
print(__doc__.format(version=_version.__version__, config_files=config.CONFIG_LOCATIONS))
return 0
l... | [
"def",
"hatchery",
"(",
")",
":",
"args",
"=",
"docopt",
".",
"docopt",
"(",
"__doc__",
")",
"task_list",
"=",
"args",
"[",
"'<task>'",
"]",
"if",
"not",
"task_list",
"or",
"'help'",
"in",
"task_list",
"or",
"args",
"[",
"'--help'",
"]",
":",
"print",
... | 32.923077 | 0.001134 |
def get_precision(self):
"""
Get the current precision from the sensor.
:returns: sensor resolution from 9-12 bits
:rtype: int
"""
config_str = self.raw_sensor_strings[1].split()[4] # Byte 5 is the config register
bit_base = int(config_str, 16) >> 5 ... | [
"def",
"get_precision",
"(",
"self",
")",
":",
"config_str",
"=",
"self",
".",
"raw_sensor_strings",
"[",
"1",
"]",
".",
"split",
"(",
")",
"[",
"4",
"]",
"# Byte 5 is the config register",
"bit_base",
"=",
"int",
"(",
"config_str",
",",
"16",
")",
">>",
... | 39.1 | 0.01 |
def url(self, url):
""" Set API URL endpoint
Args:
url: the url of the API endpoint
"""
if url and url.endswith('/'):
url = url[:-1]
self._url = url | [
"def",
"url",
"(",
"self",
",",
"url",
")",
":",
"if",
"url",
"and",
"url",
".",
"endswith",
"(",
"'/'",
")",
":",
"url",
"=",
"url",
"[",
":",
"-",
"1",
"]",
"self",
".",
"_url",
"=",
"url"
] | 21.3 | 0.009009 |
def flags(self, index):
""""Determines interaction allowed with table cells.
See :qtdoc:`QAbstractItemModel<QAbstractItemModel.flags>`,
and :qtdoc:`subclassing<qabstractitemmodel.subclassing>`
"""
if index.isValid():
if self.model.editableRow(index.row()) and index.... | [
"def",
"flags",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"if",
"self",
".",
"model",
".",
"editableRow",
"(",
"index",
".",
"row",
"(",
")",
")",
"and",
"index",
".",
"column",
"(",
")",
"<",
"4",
":",
... | 43.4 | 0.004511 |
def ensure_stacker_compat_config(config_filename):
"""Ensure config file can be loaded by Stacker."""
try:
with open(config_filename, 'r') as stream:
yaml.safe_load(stream)
except yaml.constructor.ConstructorError as yaml_error:
if yaml_error.problem.startswith(
'... | [
"def",
"ensure_stacker_compat_config",
"(",
"config_filename",
")",
":",
"try",
":",
"with",
"open",
"(",
"config_filename",
",",
"'r'",
")",
"as",
"stream",
":",
"yaml",
".",
"safe_load",
"(",
"stream",
")",
"except",
"yaml",
".",
"constructor",
".",
"Const... | 52.0625 | 0.001179 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.