text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def user_identities(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/user_identities#list-identities"
api_path = "/api/v2/users/{user_id}/identities.json"
api_path = api_path.format(user_id=user_id)
return self.call(api_path, **kwargs) | [
"def",
"user_identities",
"(",
"self",
",",
"user_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/users/{user_id}/identities.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"user_id",
"=",
"user_id",
")",
"return",
"self",
".",
"c... | 58 | 0.010204 |
def path_dispatch_kwarg(mname, path_default, returns_model):
"""
Parameterized decorator for methods that accept path as a second
argument.
"""
def _wrapper(self, path=path_default, **kwargs):
prefix, mgr, mgr_path = _resolve_path(path, self.managers)
result = getattr(mgr, mname)(pat... | [
"def",
"path_dispatch_kwarg",
"(",
"mname",
",",
"path_default",
",",
"returns_model",
")",
":",
"def",
"_wrapper",
"(",
"self",
",",
"path",
"=",
"path_default",
",",
"*",
"*",
"kwargs",
")",
":",
"prefix",
",",
"mgr",
",",
"mgr_path",
"=",
"_resolve_path... | 36.538462 | 0.002053 |
def dalignbed2dalignbedqueries(cfg):
"""
Get query seqeunces from the BED file
step#4
:param cfg: configuration dict
"""
datatmpd=cfg['datatmpd']
dalignbed=del_Unnamed(pd.read_csv(cfg['dalignbedp'],sep='\t'))
dqueries=set_index(del_Unnamed(pd.read_csv(cfg['dqueriesp'],sep='\t')),'query ... | [
"def",
"dalignbed2dalignbedqueries",
"(",
"cfg",
")",
":",
"datatmpd",
"=",
"cfg",
"[",
"'datatmpd'",
"]",
"dalignbed",
"=",
"del_Unnamed",
"(",
"pd",
".",
"read_csv",
"(",
"cfg",
"[",
"'dalignbedp'",
"]",
",",
"sep",
"=",
"'\\t'",
")",
")",
"dqueries",
... | 40.833333 | 0.022606 |
def guess_payload_class(self, payload):
# type: (str) -> base_classes.Packet_metaclass
""" guess_payload_class returns the Class object to use for parsing a payload
This function uses the H2Frame.type field value to decide which payload to parse. The implement cannot be # noqa: E501
per... | [
"def",
"guess_payload_class",
"(",
"self",
",",
"payload",
")",
":",
"# type: (str) -> base_classes.Packet_metaclass",
"if",
"len",
"(",
"payload",
")",
"==",
"0",
":",
"return",
"packet",
".",
"NoPayload",
"t",
"=",
"self",
".",
"getfieldval",
"(",
"'type'",
... | 40 | 0.001307 |
def DownloadDir(aff4_path, output_dir, bufsize=8192, preserve_path=True):
"""Take an aff4 path and download all files in it to output_dir.
Args:
aff4_path: Any aff4 path as a string
output_dir: A local directory to write to, will be created if not there.
bufsize: Buffer size to use.
preserve_path: ... | [
"def",
"DownloadDir",
"(",
"aff4_path",
",",
"output_dir",
",",
"bufsize",
"=",
"8192",
",",
"preserve_path",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"output_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"output_dir",
")... | 40.235294 | 0.010707 |
def trajectory_SgConst(Sg=0.1, delta_logt_dex=-0.01):
'''
setup trajectories for constant radiation entropy.
S_gamma/R where the radiation constant R = N_A*k
(Dave Arnett, Supernova book, p. 212)
This relates rho and T but the time scale for this
is independent.
Parameters
----------
... | [
"def",
"trajectory_SgConst",
"(",
"Sg",
"=",
"0.1",
",",
"delta_logt_dex",
"=",
"-",
"0.01",
")",
":",
"# reverse logarithmic time",
"logtimerev",
"=",
"np",
".",
"arange",
"(",
"5.",
",",
"-",
"6.",
",",
"delta_logt_dex",
")",
"logrho",
"=",
"np",
".",
... | 31.478261 | 0.03148 |
def change_range(self, min_port=1025, max_port=2000, port_sequence=None):
"""change Pool port range"""
self.__init_range(min_port, max_port, port_sequence) | [
"def",
"change_range",
"(",
"self",
",",
"min_port",
"=",
"1025",
",",
"max_port",
"=",
"2000",
",",
"port_sequence",
"=",
"None",
")",
":",
"self",
".",
"__init_range",
"(",
"min_port",
",",
"max_port",
",",
"port_sequence",
")"
] | 56.333333 | 0.011696 |
def load_wineind(as_series=False):
"""Australian total wine sales by wine makers in bottles <= 1 litre.
This time-series records wine sales by Australian wine makers between
Jan 1980 -- Aug 1994. This dataset is found in the R ``forecast`` package.
Parameters
----------
as_series : bool, optio... | [
"def",
"load_wineind",
"(",
"as_series",
"=",
"False",
")",
":",
"rslt",
"=",
"np",
".",
"array",
"(",
"[",
"15136",
",",
"16733",
",",
"20016",
",",
"17708",
",",
"18019",
",",
"19227",
",",
"22893",
",",
"23739",
",",
"21133",
",",
"22591",
",",
... | 48.468085 | 0.000215 |
def absent(name, profile='grafana'):
'''
Ensure that a user is present.
name
Name of the user to remove.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
'''
if isinstance(profile, string_types):
profile = __salt__['co... | [
"def",
"absent",
"(",
"name",
",",
"profile",
"=",
"'grafana'",
")",
":",
"if",
"isinstance",
"(",
"profile",
",",
"string_types",
")",
":",
"profile",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"profile",
")",
"ret",
"=",
"{",
"'name'",
":",
"... | 36.285714 | 0.000639 |
def lowpass(cutoff):
"""
This strategy uses an exponential approximation for cut-off frequency
calculation, found by matching the single pole and single zero Laplace
highpass filter and mirroring the resulting filter to get a lowpass.
"""
R = thub(exp(cutoff - pi), 2)
G = (R + 1) / 2
return G * (1 + z *... | [
"def",
"lowpass",
"(",
"cutoff",
")",
":",
"R",
"=",
"thub",
"(",
"exp",
"(",
"cutoff",
"-",
"pi",
")",
",",
"2",
")",
"G",
"=",
"(",
"R",
"+",
"1",
")",
"/",
"2",
"return",
"G",
"*",
"(",
"1",
"+",
"z",
"**",
"-",
"1",
")",
"/",
"(",
... | 37.444444 | 0.014493 |
def post(self, uri, body=None, logon_required=True,
wait_for_completion=False, operation_timeout=None):
"""
Perform the HTTP POST method against the resource identified by a URI,
using a provided request body.
A set of standard HTTP headers is automatically part of the requ... | [
"def",
"post",
"(",
"self",
",",
"uri",
",",
"body",
"=",
"None",
",",
"logon_required",
"=",
"True",
",",
"wait_for_completion",
"=",
"False",
",",
"operation_timeout",
"=",
"None",
")",
":",
"if",
"logon_required",
":",
"self",
".",
"logon",
"(",
")",
... | 42.737624 | 0.00034 |
def get_metadata(self, dataset_identifier, content_type="json"):
'''
Retrieve the metadata for a particular dataset.
'''
resource = _format_old_api_request(dataid=dataset_identifier, content_type=content_type)
return self._perform_request("get", resource) | [
"def",
"get_metadata",
"(",
"self",
",",
"dataset_identifier",
",",
"content_type",
"=",
"\"json\"",
")",
":",
"resource",
"=",
"_format_old_api_request",
"(",
"dataid",
"=",
"dataset_identifier",
",",
"content_type",
"=",
"content_type",
")",
"return",
"self",
".... | 48.333333 | 0.010169 |
def get_events(self, start_time, end_time, ignore_cancelled = True, get_recurring_events_as_instances = True, restrict_to_calendars = []):
'''A wrapper for events().list. Returns the events from the calendar within the specified times. Some of the interesting fields are:
description, end, htmlLi... | [
"def",
"get_events",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"ignore_cancelled",
"=",
"True",
",",
"get_recurring_events_as_instances",
"=",
"True",
",",
"restrict_to_calendars",
"=",
"[",
"]",
")",
":",
"es",
"=",
"[",
"]",
"calendar_ids",
"=",
... | 60.833333 | 0.013482 |
def get_ready_user_tasks(self):
"""
Returns a list of User Tasks that are READY for user action
"""
return [t for t in self.get_tasks(Task.READY)
if not self._is_engine_task(t.task_spec)] | [
"def",
"get_ready_user_tasks",
"(",
"self",
")",
":",
"return",
"[",
"t",
"for",
"t",
"in",
"self",
".",
"get_tasks",
"(",
"Task",
".",
"READY",
")",
"if",
"not",
"self",
".",
"_is_engine_task",
"(",
"t",
".",
"task_spec",
")",
"]"
] | 38.333333 | 0.008511 |
def add_chain(self, var):
"""
Create a new ChainFunction and attach to $var.
"""
chain = FunctionChain(var, [])
self._chains[var] = chain
self[var] = chain | [
"def",
"add_chain",
"(",
"self",
",",
"var",
")",
":",
"chain",
"=",
"FunctionChain",
"(",
"var",
",",
"[",
"]",
")",
"self",
".",
"_chains",
"[",
"var",
"]",
"=",
"chain",
"self",
"[",
"var",
"]",
"=",
"chain"
] | 28.142857 | 0.009852 |
def deepgetattr(obj, name, default=_UNSPECIFIED):
"""Try to retrieve the given attribute of an object, digging on '.'.
This is an extended getattr, digging deeper if '.' is found.
Args:
obj (object): the object of which an attribute should be read
name (str): the name of an attribute to lo... | [
"def",
"deepgetattr",
"(",
"obj",
",",
"name",
",",
"default",
"=",
"_UNSPECIFIED",
")",
":",
"try",
":",
"if",
"'.'",
"in",
"name",
":",
"attr",
",",
"subname",
"=",
"name",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"return",
"deepgetattr",
"(",
"g... | 31.740741 | 0.002265 |
def reset(self, align=8, clip=80, code=False, derive=False,
detail=0, ignored=True, infer=False, limit=100, stats=0,
stream=None):
'''Reset options, state, etc.
The available options and default values are:
*align=8* -- size alignment
... | [
"def",
"reset",
"(",
"self",
",",
"align",
"=",
"8",
",",
"clip",
"=",
"80",
",",
"code",
"=",
"False",
",",
"derive",
"=",
"False",
",",
"detail",
"=",
"0",
",",
"ignored",
"=",
"True",
",",
"infer",
"=",
"False",
",",
"limit",
"=",
"100",
","... | 29.847826 | 0.009873 |
def mkArrayUpdater(nextItemVal: Value, indexes: Tuple[Value],
invalidate: bool):
"""
Create value updater for simulation for value of array type
:param nextVal: instance of Value which will be asssiggned to signal
:param indexes: tuple on indexes where value should be updated
... | [
"def",
"mkArrayUpdater",
"(",
"nextItemVal",
":",
"Value",
",",
"indexes",
":",
"Tuple",
"[",
"Value",
"]",
",",
"invalidate",
":",
"bool",
")",
":",
"def",
"updater",
"(",
"currentVal",
")",
":",
"if",
"len",
"(",
"indexes",
")",
">",
"1",
":",
"rai... | 33.76 | 0.001152 |
def unfinished(finished_status,
update_interval,
status_key,
edit_at_key):
"""
Create dict query for pymongo that getting all unfinished task.
:param finished_status: int, status code that less than this
will be considered as unfinished.
:param updat... | [
"def",
"unfinished",
"(",
"finished_status",
",",
"update_interval",
",",
"status_key",
",",
"edit_at_key",
")",
":",
"return",
"{",
"\"$or\"",
":",
"[",
"{",
"status_key",
":",
"{",
"\"$lt\"",
":",
"finished_status",
"}",
"}",
",",
"{",
"edit_at_key",
":",
... | 29.384615 | 0.001267 |
def _add_rid_to_vrf_list(self, ri):
"""Add router ID to a VRF list.
In order to properly manage VRFs in the ASR, their
usage has to be tracked. VRFs are provided with neutron
router objects in their hosting_info fields of the gateway ports.
This means that the VRF is only availa... | [
"def",
"_add_rid_to_vrf_list",
"(",
"self",
",",
"ri",
")",
":",
"if",
"ri",
".",
"ex_gw_port",
"or",
"ri",
".",
"router",
".",
"get",
"(",
"'gw_port'",
")",
":",
"driver",
"=",
"self",
".",
"driver_manager",
".",
"get_driver",
"(",
"ri",
".",
"id",
... | 48.47619 | 0.001927 |
def _offset_setup(self,sigangle,leading,deltaAngleTrack):
"""The part of the setup related to calculating the stream/progenitor offset"""
#From the progenitor orbit, determine the sigmas in J and angle
self._sigjr= (self._progenitor.rap()-self._progenitor.rperi())/numpy.pi*self._sigv
sel... | [
"def",
"_offset_setup",
"(",
"self",
",",
"sigangle",
",",
"leading",
",",
"deltaAngleTrack",
")",
":",
"#From the progenitor orbit, determine the sigmas in J and angle",
"self",
".",
"_sigjr",
"=",
"(",
"self",
".",
"_progenitor",
".",
"rap",
"(",
")",
"-",
"self... | 55.711864 | 0.016442 |
def inferdialect(fname=None, datalines=None, delimiter_regex=None,
verbosity=DEFAULT_VERBOSITY):
"""
Attempts to convert infer dialect from csv file lines.
Essentially a small extension of the "sniff" function from Python CSV
module. csv.Sniffer().sniff attempts to infer the d... | [
"def",
"inferdialect",
"(",
"fname",
"=",
"None",
",",
"datalines",
"=",
"None",
",",
"delimiter_regex",
"=",
"None",
",",
"verbosity",
"=",
"DEFAULT_VERBOSITY",
")",
":",
"if",
"datalines",
"is",
"None",
":",
"if",
"is_string_like",
"(",
"fname",
")",
":"... | 35.105769 | 0.012254 |
def value_at_risk(returns, period=None, sigma=2.0):
"""
Get value at risk (VaR).
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
period : str, optional
Period over which to c... | [
"def",
"value_at_risk",
"(",
"returns",
",",
"period",
"=",
"None",
",",
"sigma",
"=",
"2.0",
")",
":",
"if",
"period",
"is",
"not",
"None",
":",
"returns_agg",
"=",
"ep",
".",
"aggregate_returns",
"(",
"returns",
",",
"period",
")",
"else",
":",
"retu... | 32.043478 | 0.001318 |
def simx(A,B,transpose=False):
"Similarity transform B^T(AB) or B(AB^T) (if transpose)"
if transpose:
return np.dot(B,np.dot(A,B.T))
return np.dot(B.T,np.dot(A,B)) | [
"def",
"simx",
"(",
"A",
",",
"B",
",",
"transpose",
"=",
"False",
")",
":",
"if",
"transpose",
":",
"return",
"np",
".",
"dot",
"(",
"B",
",",
"np",
".",
"dot",
"(",
"A",
",",
"B",
".",
"T",
")",
")",
"return",
"np",
".",
"dot",
"(",
"B",
... | 35.8 | 0.038251 |
def read_token(source, from_position):
# type: (Source, int) -> Token
"""Gets the next token from the source starting at the given position.
This skips over whitespace and comments until it finds the next lexable
token, then lexes punctuators immediately or calls the appropriate
helper fucntion for... | [
"def",
"read_token",
"(",
"source",
",",
"from_position",
")",
":",
"# type: (Source, int) -> Token",
"body",
"=",
"source",
".",
"body",
"body_length",
"=",
"len",
"(",
"body",
")",
"position",
"=",
"position_after_whitespace",
"(",
"body",
",",
"from_position",
... | 34.106383 | 0.001819 |
def qteEmulateKeypresses(self, keysequence):
"""
Emulate the Qt key presses that define ``keysequence``.
The method will put the keys into a queue and process them one
by one once the event loop is idle, ie. the event loop
executes all signals and macros associated with the emul... | [
"def",
"qteEmulateKeypresses",
"(",
"self",
",",
"keysequence",
")",
":",
"# Convert the key sequence into a QtmacsKeysequence object, or",
"# raise an QtmacsOtherError if the conversion is impossible.",
"keysequence",
"=",
"QtmacsKeysequence",
"(",
"keysequence",
")",
"key_list",
... | 33.575758 | 0.001754 |
def channel(self, rpc_timeout=60, lazy=False):
"""Open Channel.
:param int rpc_timeout: Timeout before we give up waiting for an RPC
response from the server.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel... | [
"def",
"channel",
"(",
"self",
",",
"rpc_timeout",
"=",
"60",
",",
"lazy",
"=",
"False",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'Opening a new Channel'",
")",
"if",
"not",
"compatibility",
".",
"is_integer",
"(",
"rpc_timeout",
")",
":",
"raise",
"AMQPInv... | 43.730769 | 0.001721 |
def unban_member_from_group(self, group_jid, peer_jid):
"""
Undos a ban of someone from a group
:param group_jid: The JID of the relevant group
:param peer_jid: The JID of the user to un-ban from the gorup
"""
log.info("[+] Requesting un-banning of user {} from the group... | [
"def",
"unban_member_from_group",
"(",
"self",
",",
"group_jid",
",",
"peer_jid",
")",
":",
"log",
".",
"info",
"(",
"\"[+] Requesting un-banning of user {} from the group {}\"",
".",
"format",
"(",
"peer_jid",
",",
"group_jid",
")",
")",
"return",
"self",
".",
"_... | 48.333333 | 0.009029 |
def table_type(table_name):
"""
Returns the type of a registered table.
The type can be either "dataframe" or "function".
Parameters
----------
table_name : str
Returns
-------
table_type : {'dataframe', 'function'}
"""
table = get_raw_table(table_name)
if isinstance... | [
"def",
"table_type",
"(",
"table_name",
")",
":",
"table",
"=",
"get_raw_table",
"(",
"table_name",
")",
"if",
"isinstance",
"(",
"table",
",",
"DataFrameWrapper",
")",
":",
"return",
"'dataframe'",
"elif",
"isinstance",
"(",
"table",
",",
"TableFuncWrapper",
... | 20.238095 | 0.002247 |
def tabText(self, tab):
""" allow index or tab widget instance"""
if not isinstance(tab, int):
tab = self.indexOf(tab)
return super(FwTabWidget, self).tabText(tab) | [
"def",
"tabText",
"(",
"self",
",",
"tab",
")",
":",
"if",
"not",
"isinstance",
"(",
"tab",
",",
"int",
")",
":",
"tab",
"=",
"self",
".",
"indexOf",
"(",
"tab",
")",
"return",
"super",
"(",
"FwTabWidget",
",",
"self",
")",
".",
"tabText",
"(",
"... | 39 | 0.01005 |
def set_errors(self):
"""Set errors markup.
"""
if not self.field.errors or self.attrs.get("_no_errors"):
return
self.values["class"].append("error")
for error in self.field.errors:
self.values["errors"] += ERROR_WRAPPER % {"message": error} | [
"def",
"set_errors",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"field",
".",
"errors",
"or",
"self",
".",
"attrs",
".",
"get",
"(",
"\"_no_errors\"",
")",
":",
"return",
"self",
".",
"values",
"[",
"\"class\"",
"]",
".",
"append",
"(",
"\"erro... | 26.1 | 0.040741 |
def add_access(self, **kwargs): # noqa: E501
"""Adds the specified ids to the given dashboards' ACL # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.add_access... | [
"def",
"add_access",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"add_access_with_http_info",
"(... | 39.047619 | 0.002381 |
def _generateInsertStatement(self, dataset_name, cols):
"""Generates a sql INSERT template"""
col_names = [col["varname"] for col in cols]
# Generate question mark placeholders
qms = ','.join(['?' for x in col_names])
return 'INSERT INTO %s (%s) values (%s)' % (dataset_name, ',... | [
"def",
"_generateInsertStatement",
"(",
"self",
",",
"dataset_name",
",",
"cols",
")",
":",
"col_names",
"=",
"[",
"col",
"[",
"\"varname\"",
"]",
"for",
"col",
"in",
"cols",
"]",
"# Generate question mark placeholders",
"qms",
"=",
"','",
".",
"join",
"(",
... | 42 | 0.008746 |
def phonex(word, max_length=4, zero_pad=True):
"""Return the Phonex code for a word.
This is a wrapper for :py:meth:`Phonex.encode`.
Parameters
----------
word : str
The word to transform
max_length : int
The length of the code returned (defaults to 4)
zero_pad : bool
... | [
"def",
"phonex",
"(",
"word",
",",
"max_length",
"=",
"4",
",",
"zero_pad",
"=",
"True",
")",
":",
"return",
"Phonex",
"(",
")",
".",
"encode",
"(",
"word",
",",
"max_length",
",",
"zero_pad",
")"
] | 20.59375 | 0.001449 |
def run_work(self):
"""Run attacks and defenses"""
if os.path.exists(LOCAL_EVAL_ROOT_DIR):
sudo_remove_dirtree(LOCAL_EVAL_ROOT_DIR)
self.run_attacks()
self.run_defenses() | [
"def",
"run_work",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"LOCAL_EVAL_ROOT_DIR",
")",
":",
"sudo_remove_dirtree",
"(",
"LOCAL_EVAL_ROOT_DIR",
")",
"self",
".",
"run_attacks",
"(",
")",
"self",
".",
"run_defenses",
"(",
")"
] | 31.166667 | 0.010417 |
def _make_hlog_numeric(b, r, d):
"""
Return a function that numerically computes the hlog transformation for given parameter values.
"""
hlog_obj = lambda y, x, b, r, d: hlog_inv(y, b, r, d) - x
find_inv = vectorize(lambda x: brentq(hlog_obj, -2 * r, 2 * r,
... | [
"def",
"_make_hlog_numeric",
"(",
"b",
",",
"r",
",",
"d",
")",
":",
"hlog_obj",
"=",
"lambda",
"y",
",",
"x",
",",
"b",
",",
"r",
",",
"d",
":",
"hlog_inv",
"(",
"y",
",",
"b",
",",
"r",
",",
"d",
")",
"-",
"x",
"find_inv",
"=",
"vectorize",... | 44 | 0.008357 |
def generate_prepare_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to prepare source XML
files for stripping."""
parser = subparsers.add_parser(
'prepare', description=constants.PREPARE_DESCRIPTION,
epilog=constants.PREPARE_EPILOG, formatter_class=ParagraphFormatter,
... | [
"def",
"generate_prepare_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'prepare'",
",",
"description",
"=",
"constants",
".",
"PREPARE_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"PREPARE_EPILOG",
",",
"form... | 51.5 | 0.001059 |
def all(self):
"""
Return a synthetic dictionary of all factories.
"""
return {
key: value
for key, value in chain(self.entry_points.items(), self.factories.items())
} | [
"def",
"all",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"chain",
"(",
"self",
".",
"entry_points",
".",
"items",
"(",
")",
",",
"self",
".",
"factories",
".",
"items",
"(",
")",
")",
"}"
] | 24.888889 | 0.012931 |
def create_qss_style(color_scheme):
"""Returns a QSS stylesheet with Spyder color scheme settings.
The stylesheet can contain classes for:
Qt: QPlainTextEdit, QFrame, QWidget, etc
Pygments: .c, .k, .o, etc. (see PygmentsHighlighter)
IPython: .error, .in-prompt, .out-prompt, etc
"""
... | [
"def",
"create_qss_style",
"(",
"color_scheme",
")",
":",
"def",
"give_font_weight",
"(",
"is_bold",
")",
":",
"if",
"is_bold",
":",
"return",
"'bold'",
"else",
":",
"return",
"'normal'",
"def",
"give_font_style",
"(",
"is_italic",
")",
":",
"if",
"is_italic",... | 36.898305 | 0.000895 |
def price(
self,
instrument,
**kwargs
):
"""
Fetch a price for an instrument. Accounts are not associated in any way
with this endpoint.
Args:
instrument:
Name of the Instrument
time:
The time at which t... | [
"def",
"price",
"(",
"self",
",",
"instrument",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"Request",
"(",
"'GET'",
",",
"'/v3/instruments/{instrument}/price'",
")",
"request",
".",
"set_path_param",
"(",
"'instrument'",
",",
"instrument",
")",
"reques... | 27.485714 | 0.001338 |
def showDescription( self ):
"""
Shows the description for the current plugin in the interface.
"""
plugin = self.currentPlugin()
if ( not plugin ):
self.uiDescriptionTXT.setText('')
else:
self.uiDescriptionTXT.setText(plugin.description()) | [
"def",
"showDescription",
"(",
"self",
")",
":",
"plugin",
"=",
"self",
".",
"currentPlugin",
"(",
")",
"if",
"(",
"not",
"plugin",
")",
":",
"self",
".",
"uiDescriptionTXT",
".",
"setText",
"(",
"''",
")",
"else",
":",
"self",
".",
"uiDescriptionTXT",
... | 34.666667 | 0.01875 |
def createPREMISEventXML(eventType, agentIdentifier, eventDetail, eventOutcome,
outcomeDetail=None, eventIdentifier=None,
linkObjectList=[], eventDate=None):
"""
Actually create our PREMIS Event XML
"""
eventXML = etree.Element(PREMIS + "event", nsmap=P... | [
"def",
"createPREMISEventXML",
"(",
"eventType",
",",
"agentIdentifier",
",",
"eventDetail",
",",
"eventOutcome",
",",
"outcomeDetail",
"=",
"None",
",",
"eventIdentifier",
"=",
"None",
",",
"linkObjectList",
"=",
"[",
"]",
",",
"eventDate",
"=",
"None",
")",
... | 40.95 | 0.000894 |
def implicit_static(cls, for_type=None, for_types=None):
"""Automatically generate implementations for a type.
Implement the protocol for the 'for_type' type by dispatching each
member function of the protocol to an instance method of the same name
declared on the type 'for_type'.
... | [
"def",
"implicit_static",
"(",
"cls",
",",
"for_type",
"=",
"None",
",",
"for_types",
"=",
"None",
")",
":",
"for",
"type_",
"in",
"cls",
".",
"__get_type_args",
"(",
"for_type",
",",
"for_types",
")",
":",
"implementations",
"=",
"{",
"}",
"for",
"funct... | 40.030303 | 0.002217 |
def set_url(self, url = None):
"""This method is used to set the url.
url must be a string.
"""
if url is None or type(url) is not str:
raise KPError("Need a new image number")
else:
self.url = url
self.last_mod = datetime.no... | [
"def",
"set_url",
"(",
"self",
",",
"url",
"=",
"None",
")",
":",
"if",
"url",
"is",
"None",
"or",
"type",
"(",
"url",
")",
"is",
"not",
"str",
":",
"raise",
"KPError",
"(",
"\"Need a new image number\"",
")",
"else",
":",
"self",
".",
"url",
"=",
... | 27.538462 | 0.013514 |
def update_port(self, port, body=None):
"""Updates a port."""
return self.put(self.port_path % (port), body=body) | [
"def",
"update_port",
"(",
"self",
",",
"port",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"port_path",
"%",
"(",
"port",
")",
",",
"body",
"=",
"body",
")"
] | 42.333333 | 0.015504 |
def get_creation_date(
self,
bucket: str,
key: str,
) -> datetime:
"""
Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is ... | [
"def",
"get_creation_date",
"(",
"self",
",",
"bucket",
":",
"str",
",",
"key",
":",
"str",
",",
")",
"->",
"datetime",
":",
"# An S3 object's creation date is stored in its LastModified field which stores the",
"# most recent value between the two.",
"return",
"self",
".",... | 40.214286 | 0.008681 |
def _generateFindR(self, **kwargs):
"""Generator which yields matches on AXChildren and their children."""
for needle in self._generateChildrenR():
if needle._match(**kwargs):
yield needle | [
"def",
"_generateFindR",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"needle",
"in",
"self",
".",
"_generateChildrenR",
"(",
")",
":",
"if",
"needle",
".",
"_match",
"(",
"*",
"*",
"kwargs",
")",
":",
"yield",
"needle"
] | 45.6 | 0.008621 |
def remove(self, option):
"""
Removes an option from a Config instance
IN: option (type: Option)
"""
if option.__class__ == Option:
if option in self.options:
del self.options[self.options.index(option)]
else:
raise OptionNotFoundError(option.name)
else:
raise TypeError("invalid type suppli... | [
"def",
"remove",
"(",
"self",
",",
"option",
")",
":",
"if",
"option",
".",
"__class__",
"==",
"Option",
":",
"if",
"option",
"in",
"self",
".",
"options",
":",
"del",
"self",
".",
"options",
"[",
"self",
".",
"options",
".",
"index",
"(",
"option",
... | 26.083333 | 0.040123 |
def i4_bit_hi1(n):
"""
i4_bit_hi1 returns the position of the high 1 bit base 2 in an integer.
Example:
+------+-------------+-----
| N | Binary | BIT
+------|-------------+-----
| 0 | 0 | 0
| 1 | 1 | 1
| 2 | 10 | 2
... | [
"def",
"i4_bit_hi1",
"(",
"n",
")",
":",
"i",
"=",
"np",
".",
"floor",
"(",
"n",
")",
"bit",
"=",
"0",
"while",
"i",
">",
"0",
":",
"bit",
"+=",
"1",
"i",
"//=",
"2",
"return",
"bit"
] | 28.071429 | 0.001639 |
def cluster(self, input_fasta_list, reverse_pipe):
'''
cluster - Clusters reads at 100% identity level and writes them to
file. Resets the input_fasta variable as the FASTA file containing the
clusters.
Parameters
----------
input_fasta_list : list
l... | [
"def",
"cluster",
"(",
"self",
",",
"input_fasta_list",
",",
"reverse_pipe",
")",
":",
"output_fasta_list",
"=",
"[",
"]",
"for",
"input_fasta",
"in",
"input_fasta_list",
":",
"output_path",
"=",
"input_fasta",
".",
"replace",
"(",
"'_hits.aln.fa'",
",",
"'_clus... | 46.022222 | 0.009929 |
def w(self):
"""Extract write lock (w) counter if available (lazy)."""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._w | [
"def",
"w",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_counters_calculated",
":",
"self",
".",
"_counters_calculated",
"=",
"True",
"self",
".",
"_extract_counters",
"(",
")",
"return",
"self",
".",
"_w"
] | 31.428571 | 0.00885 |
def _check_choices_attribute(self): # pragma: no cover
"""Checks to make sure that choices contains valid timezone choices."""
if self.choices:
warning_params = {
'msg': (
"'choices' contains an invalid time zone value '{value}' "
"w... | [
"def",
"_check_choices_attribute",
"(",
"self",
")",
":",
"# pragma: no cover",
"if",
"self",
".",
"choices",
":",
"warning_params",
"=",
"{",
"'msg'",
":",
"(",
"\"'choices' contains an invalid time zone value '{value}' \"",
"\"which was not found as a supported time zone by p... | 44.109091 | 0.000806 |
def _parse_device(s: str) -> Tuple[List[GridQubit], Dict[str, Set[GridQubit]]]:
"""Parse ASCIIart device layout into info about qubits and connectivity.
Args:
s: String representing the qubit layout. Each line represents a row,
and each character in the row is a qubit, or a blank site if th... | [
"def",
"_parse_device",
"(",
"s",
":",
"str",
")",
"->",
"Tuple",
"[",
"List",
"[",
"GridQubit",
"]",
",",
"Dict",
"[",
"str",
",",
"Set",
"[",
"GridQubit",
"]",
"]",
"]",
":",
"lines",
"=",
"s",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'\\n... | 45.461538 | 0.000829 |
def consonants(self):
"""
Return a new IPAString, containing only the consonants in the current string.
:rtype: IPAString
"""
return IPAString(ipa_chars=[c for c in self.ipa_chars if c.is_consonant]) | [
"def",
"consonants",
"(",
"self",
")",
":",
"return",
"IPAString",
"(",
"ipa_chars",
"=",
"[",
"c",
"for",
"c",
"in",
"self",
".",
"ipa_chars",
"if",
"c",
".",
"is_consonant",
"]",
")"
] | 33.428571 | 0.016667 |
def get(protocol, subset, classes=CLASSES, variables=VARIABLES):
'''Returns the data subset given a particular protocol
Parameters
protocol (string): one of the valid protocols supported by this interface
subset (string): one of 'train' or 'test'
classes (list of string): a list of strings containi... | [
"def",
"get",
"(",
"protocol",
",",
"subset",
",",
"classes",
"=",
"CLASSES",
",",
"variables",
"=",
"VARIABLES",
")",
":",
"retval",
"=",
"split_data",
"(",
"bob",
".",
"db",
".",
"iris",
".",
"data",
"(",
")",
",",
"subset",
",",
"PROTOCOLS",
"[",
... | 31.028571 | 0.008929 |
def acquire(self, lock):
'''Acquire the named lock, non-blocking.
The lock may be granted immediately, or in a future hook.
Returns True if the lock has been granted. The lock will be
automatically released at the end of the hook in which it is
granted.
Do not mindless... | [
"def",
"acquire",
"(",
"self",
",",
"lock",
")",
":",
"unit",
"=",
"hookenv",
".",
"local_unit",
"(",
")",
"ts",
"=",
"self",
".",
"requests",
"[",
"unit",
"]",
".",
"get",
"(",
"lock",
")",
"if",
"not",
"ts",
":",
"# If there is no outstanding request... | 39.194444 | 0.001383 |
def _trace (frame, event, arg):
"""Trace function calls."""
if event in ('call', 'c_call'):
_trace_line(frame, event, arg)
elif event in ('return', 'c_return'):
_trace_line(frame, event, arg)
print(" return:", arg)
#elif event in ('exception', 'c_exception'):
# _trace_lin... | [
"def",
"_trace",
"(",
"frame",
",",
"event",
",",
"arg",
")",
":",
"if",
"event",
"in",
"(",
"'call'",
",",
"'c_call'",
")",
":",
"_trace_line",
"(",
"frame",
",",
"event",
",",
"arg",
")",
"elif",
"event",
"in",
"(",
"'return'",
",",
"'c_return'",
... | 34.9 | 0.00838 |
def taper(self):
"""Taper the spectrum by adding zero flux to each end.
This is similar to :meth:`SpectralElement.taper`.
There is no check to see if the spectrum is already tapered.
Hence, calling this on a tapered spectrum will result in
multiple zero-flux entries at both ends... | [
"def",
"taper",
"(",
"self",
")",
":",
"OutSpec",
"=",
"TabularSourceSpectrum",
"(",
")",
"wcopy",
"=",
"N",
".",
"zeros",
"(",
"self",
".",
"_wavetable",
".",
"size",
"+",
"2",
",",
"dtype",
"=",
"N",
".",
"float64",
")",
"fcopy",
"=",
"N",
".",
... | 35.756757 | 0.001472 |
def _verify_config_dict(self, valid, config, dev_os, key_path=None):
'''
Verify if the config dict is valid.
'''
if not key_path:
key_path = []
for key, value in valid.items():
self._verify_config_key(key, value, valid, config, dev_os, key_path) | [
"def",
"_verify_config_dict",
"(",
"self",
",",
"valid",
",",
"config",
",",
"dev_os",
",",
"key_path",
"=",
"None",
")",
":",
"if",
"not",
"key_path",
":",
"key_path",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"valid",
".",
"items",
"(",
")",... | 37.75 | 0.009709 |
def make_qadapter(**kwargs):
"""
Return the concrete :class:`QueueAdapter` class from a string.
Note that one can register a customized version with:
.. example::
from qadapters import SlurmAdapter
class MyAdapter(SlurmAdapter):
QTYPE = "myslurm"
# Add your cus... | [
"def",
"make_qadapter",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Get all known subclasses of QueueAdapter.",
"d",
"=",
"{",
"c",
".",
"QTYPE",
":",
"c",
"for",
"c",
"in",
"all_subclasses",
"(",
"QueueAdapter",
")",
"}",
"# Preventive copy before pop",
"kwargs",
"="... | 27.193548 | 0.001145 |
def create(self, name, region, size, image, ssh_keys=None,
backups=None, ipv6=None, private_networking=None, wait=True):
"""
Create a new droplet
Parameters
----------
name: str
Name of new droplet
region: str
slug for region (e.g.,... | [
"def",
"create",
"(",
"self",
",",
"name",
",",
"region",
",",
"size",
",",
"image",
",",
"ssh_keys",
"=",
"None",
",",
"backups",
"=",
"None",
",",
"ipv6",
"=",
"None",
",",
"private_networking",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":",
"i... | 42.756098 | 0.001673 |
def _make_writeable(filename):
"""
Make sure that the file is writeable. Useful if our source is
read-only.
"""
import stat
if sys.platform.startswith('java'):
# On Jython there is no os.access()
return
if not os.access(filename, os.W_OK):
st = os.stat(filename)
... | [
"def",
"_make_writeable",
"(",
"filename",
")",
":",
"import",
"stat",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'java'",
")",
":",
"# On Jython there is no os.access()",
"return",
"if",
"not",
"os",
".",
"access",
"(",
"filename",
",",
"os",
".... | 31.692308 | 0.002358 |
def _commonParent(zi1, zi2):
"""
Locate the common parent of two Interface objects.
@param zi1: a zope Interface object.
@param zi2: another Interface object.
@return: the rightmost common parent of the two provided Interface objects,
or None, if they have no common parent other than Interfac... | [
"def",
"_commonParent",
"(",
"zi1",
",",
"zi2",
")",
":",
"shorter",
",",
"longer",
"=",
"sorted",
"(",
"[",
"_linearize",
"(",
"x",
")",
"[",
":",
":",
"-",
"1",
"]",
"for",
"x",
"in",
"zi1",
",",
"zi2",
"]",
",",
"key",
"=",
"len",
")",
"fo... | 31.736842 | 0.00161 |
def _iter_straight_packed(self, byte_blocks):
"""Iterator that undoes the effect of filtering;
yields each row as a sequence of packed bytes.
Assumes input is straightlaced.
`byte_blocks` should be an iterable that yields the raw bytes
in blocks of arbitrary size.
"""
... | [
"def",
"_iter_straight_packed",
"(",
"self",
",",
"byte_blocks",
")",
":",
"# length of row, in bytes",
"rb",
"=",
"self",
".",
"row_bytes",
"a",
"=",
"bytearray",
"(",
")",
"# The previous (reconstructed) scanline.",
"# None indicates first line of image.",
"recon",
"=",... | 39.25 | 0.001776 |
def _create_regs(self, state):
"""Creates a tuple of index pairs representing matched groups."""
regs = [(state.start, state.string_position)]
for group in range(self.re.groups):
mark_index = 2 * group
if mark_index + 1 < len(state.marks) \
... | [
"def",
"_create_regs",
"(",
"self",
",",
"state",
")",
":",
"regs",
"=",
"[",
"(",
"state",
".",
"start",
",",
"state",
".",
"string_position",
")",
"]",
"for",
"group",
"in",
"range",
"(",
"self",
".",
"re",
".",
"groups",
")",
":",
"mark_index",
... | 50.25 | 0.009772 |
def nl_family(self, value):
"""Family setter."""
self.bytearray[self._get_slicers(0)] = bytearray(c_uint(value or 0)) | [
"def",
"nl_family",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"bytearray",
"[",
"self",
".",
"_get_slicers",
"(",
"0",
")",
"]",
"=",
"bytearray",
"(",
"c_uint",
"(",
"value",
"or",
"0",
")",
")"
] | 43.666667 | 0.015038 |
def forget(identifier):
'''
Tells homely to forget about a dotfiles repository that was previously
added. You can then run `homely update` to have homely perform automatic
cleanup of anything that was installed by that dotfiles repo.
REPO
This should be the path to a local dotfiles reposito... | [
"def",
"forget",
"(",
"identifier",
")",
":",
"errors",
"=",
"False",
"for",
"one",
"in",
"identifier",
":",
"cfg",
"=",
"RepoListConfig",
"(",
")",
"info",
"=",
"cfg",
".",
"find_by_any",
"(",
"one",
",",
"\"ilc\"",
")",
"if",
"not",
"info",
":",
"w... | 33.965517 | 0.000987 |
def decrypt_pillar(self, pillar):
'''
Decrypt the specified pillar dictionary items, if configured to do so
'''
errors = []
if self.opts.get('decrypt_pillar'):
decrypt_pillar = self.opts['decrypt_pillar']
if not isinstance(decrypt_pillar, dict):
... | [
"def",
"decrypt_pillar",
"(",
"self",
",",
"pillar",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"self",
".",
"opts",
".",
"get",
"(",
"'decrypt_pillar'",
")",
":",
"decrypt_pillar",
"=",
"self",
".",
"opts",
"[",
"'decrypt_pillar'",
"]",
"if",
"not",
"is... | 46.050847 | 0.001441 |
def _align_and_warn(returns,
positions,
factor_returns,
factor_loadings,
transactions=None,
pos_in_dollars=True):
"""
Make sure that all inputs have matching dates and tickers,
and raise warnings if necessary... | [
"def",
"_align_and_warn",
"(",
"returns",
",",
"positions",
",",
"factor_returns",
",",
"factor_loadings",
",",
"transactions",
"=",
"None",
",",
"pos_in_dollars",
"=",
"True",
")",
":",
"missing_stocks",
"=",
"positions",
".",
"columns",
".",
"difference",
"(",... | 39.070175 | 0.000219 |
def buildProtocol(self, addr):
"""
Builds a bridge and associates it with an AMP protocol instance.
"""
proto = self._factory.buildProtocol(addr)
return JSONAMPDialectReceiver(proto) | [
"def",
"buildProtocol",
"(",
"self",
",",
"addr",
")",
":",
"proto",
"=",
"self",
".",
"_factory",
".",
"buildProtocol",
"(",
"addr",
")",
"return",
"JSONAMPDialectReceiver",
"(",
"proto",
")"
] | 36.166667 | 0.009009 |
def _feed(self, stanza):
"""
Dispatch the given `stanza`.
:param stanza: Stanza to dispatch
:type stanza: :class:`~.StanzaBase`
:rtype: :class:`bool`
:return: true if the stanza was dispatched, false otherwise.
Dispatch the stanza to up to one handler registered... | [
"def",
"_feed",
"(",
"self",
",",
"stanza",
")",
":",
"from_",
"=",
"stanza",
".",
"from_",
"if",
"from_",
"is",
"None",
":",
"from_",
"=",
"self",
".",
"local_jid",
"keys",
"=",
"[",
"(",
"stanza",
".",
"type_",
",",
"from_",
",",
"False",
")",
... | 29.470588 | 0.001932 |
def _apply_BCs(self):
r"""
Applies all the boundary conditions that have been specified, by
adding values to the *A* and *b* matrices.
"""
if 'pore.bc_rate' in self.keys():
# Update b
ind = np.isfinite(self['pore.bc_rate'])
self.b[ind] = self['... | [
"def",
"_apply_BCs",
"(",
"self",
")",
":",
"if",
"'pore.bc_rate'",
"in",
"self",
".",
"keys",
"(",
")",
":",
"# Update b",
"ind",
"=",
"np",
".",
"isfinite",
"(",
"self",
"[",
"'pore.bc_rate'",
"]",
")",
"self",
".",
"b",
"[",
"ind",
"]",
"=",
"se... | 46.607143 | 0.001502 |
def vendor_runtime(chroot, dest_basedir, label, root_module_names):
"""Includes portions of vendored distributions in a chroot.
The portion to include is selected by root module name. If the module is a file, just it is
included. If the module represents a package, the package and all its sub-packages are added
... | [
"def",
"vendor_runtime",
"(",
"chroot",
",",
"dest_basedir",
",",
"label",
",",
"root_module_names",
")",
":",
"vendor_module_names",
"=",
"{",
"root_module_name",
":",
"False",
"for",
"root_module_name",
"in",
"root_module_names",
"}",
"for",
"spec",
"in",
"iter_... | 53.2 | 0.011074 |
def is_higher_permission(level1, level2):
"""
Return True if the level1 is higher than level2
"""
return (is_publish_permission(level1) and
not is_publish_permission(level2) or
(is_edit_permission(level1) and
not is_publish_permission(level2) and
not is_... | [
"def",
"is_higher_permission",
"(",
"level1",
",",
"level2",
")",
":",
"return",
"(",
"is_publish_permission",
"(",
"level1",
")",
"and",
"not",
"is_publish_permission",
"(",
"level2",
")",
"or",
"(",
"is_edit_permission",
"(",
"level1",
")",
"and",
"not",
"is... | 38.636364 | 0.002299 |
def isFlexible(self):
"""
Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value.
"""
for key, value in self.arrayShapeRange.items():
if key in _CONSTRAINED_KEYS:
if value.isFlexible:
r... | [
"def",
"isFlexible",
"(",
"self",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"arrayShapeRange",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"_CONSTRAINED_KEYS",
":",
"if",
"value",
".",
"isFlexible",
":",
"return",
"True",
"return",
"... | 34.3 | 0.008523 |
def run_analysis( named_analysis, prepared_analyses=None,log_dir=default_log_dir):
"""
Runs just the named analysis. Otherwise just like run_analyses
"""
if prepared_analyses == None:
prepared_analyses = prepare_analyses()
state_collection = funtool.state_collection.StateCollection([],{})
... | [
"def",
"run_analysis",
"(",
"named_analysis",
",",
"prepared_analyses",
"=",
"None",
",",
"log_dir",
"=",
"default_log_dir",
")",
":",
"if",
"prepared_analyses",
"==",
"None",
":",
"prepared_analyses",
"=",
"prepare_analyses",
"(",
")",
"state_collection",
"=",
"f... | 46.818182 | 0.015238 |
def set_iscsi_initiator_info(self, initiator_iqn):
"""Set iSCSI initiator information in iLO.
:param initiator_iqn: Initiator iqn for iLO.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the system is
in the bios boot mode.
"""
... | [
"def",
"set_iscsi_initiator_info",
"(",
"self",
",",
"initiator_iqn",
")",
":",
"if",
"(",
"self",
".",
"_is_boot_mode_uefi",
"(",
")",
"is",
"True",
")",
":",
"iscsi_uri",
"=",
"self",
".",
"_check_iscsi_rest_patch_allowed",
"(",
")",
"initiator_info",
"=",
"... | 47.631579 | 0.002167 |
def url_permutations(url):
"""Try all permutations of hostname and path which can be applied
to blacklisted URLs
"""
def url_host_permutations(host):
if re.match(r'\d+\.\d+\.\d+\.\d+', host):
yield host
return
parts = host.split('.... | [
"def",
"url_permutations",
"(",
"url",
")",
":",
"def",
"url_host_permutations",
"(",
"host",
")",
":",
"if",
"re",
".",
"match",
"(",
"r'\\d+\\.\\d+\\.\\d+\\.\\d+'",
",",
"host",
")",
":",
"yield",
"host",
"return",
"parts",
"=",
"host",
".",
"split",
"("... | 34.365854 | 0.00207 |
def _apply_template(template, target, *, checkout, extra_context):
"""Apply a template to a temporary directory and then copy results to target."""
with tempfile.TemporaryDirectory() as tempdir:
repo_dir = cc_main.cookiecutter(
template,
checkout=checkout,
no_input=Tr... | [
"def",
"_apply_template",
"(",
"template",
",",
"target",
",",
"*",
",",
"checkout",
",",
"extra_context",
")",
":",
"with",
"tempfile",
".",
"TemporaryDirectory",
"(",
")",
"as",
"tempdir",
":",
"repo_dir",
"=",
"cc_main",
".",
"cookiecutter",
"(",
"templat... | 39.95 | 0.002445 |
def id(self):
"""A unique, stable, hashable id over the set of pinned artifacts."""
if not self._id:
# NB(gmalmquist): This id is not cheap to compute if there are a large number of artifacts.
# We cache it here, but invalidate the cached value if an artifact gets added or changed.
self._id = ... | [
"def",
"id",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_id",
":",
"# NB(gmalmquist): This id is not cheap to compute if there are a large number of artifacts.",
"# We cache it here, but invalidate the cached value if an artifact gets added or changed.",
"self",
".",
"_id",
... | 51.857143 | 0.01626 |
def batch_split_words(self, sentences: List[str]) -> List[List[Token]]:
"""
Spacy needs to do batch processing, or it can be really slow. This method lets you take
advantage of that if you want. Default implementation is to just iterate of the sentences
and call ``split_words``, but th... | [
"def",
"batch_split_words",
"(",
"self",
",",
"sentences",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"List",
"[",
"Token",
"]",
"]",
":",
"return",
"[",
"self",
".",
"split_words",
"(",
"sentence",
")",
"for",
"sentence",
"in",
"sentences",... | 57.875 | 0.010638 |
def delete_gene(self, *gene_ids):
"""Delete one or more gene ids form the list."""
self.gene_ids = [gene_id for gene_id in self.gene_ids
if gene_id not in gene_ids] | [
"def",
"delete_gene",
"(",
"self",
",",
"*",
"gene_ids",
")",
":",
"self",
".",
"gene_ids",
"=",
"[",
"gene_id",
"for",
"gene_id",
"in",
"self",
".",
"gene_ids",
"if",
"gene_id",
"not",
"in",
"gene_ids",
"]"
] | 50.5 | 0.009756 |
def resolve(
self, app_id, query, timezone_offset=None, verbose=None, staging=None, spell_check=None, bing_spell_check_subscription_key=None, log=None, custom_headers=None, raw=False, **operation_config):
"""Gets predictions for a given utterance, in the form of intents and
entities. The cur... | [
"def",
"resolve",
"(",
"self",
",",
"app_id",
",",
"query",
",",
"timezone_offset",
"=",
"None",
",",
"verbose",
"=",
"None",
",",
"staging",
"=",
"None",
",",
"spell_check",
"=",
"None",
",",
"bing_spell_check_subscription_key",
"=",
"None",
",",
"log",
"... | 46.662791 | 0.00244 |
def __add_group(self, group):
"""
add attributes to group nodes, as well as in-edges from other
groups. a group's ``type`` attribute tells us whether the group
node represents a span (of RST segments or other groups) OR
a multinuc(ular) relation (i.e. it dominates several RST nuc... | [
"def",
"__add_group",
"(",
"self",
",",
"group",
")",
":",
"group_id",
"=",
"self",
".",
"ns",
"+",
"':'",
"+",
"group",
".",
"attrib",
"[",
"'id'",
"]",
"group_type",
"=",
"group",
".",
"attrib",
"[",
"'type'",
"]",
"# 'span' or 'multinuc'",
"group_laye... | 49.172414 | 0.002063 |
def _render_condition_value(value, field_type):
"""Render a query condition value.
Parameters
----------
value : Union[bool, int, float, str, datetime]
The value of the condition
field_type : str
The data type of the field
Returns
-------
str
A value string.
... | [
"def",
"_render_condition_value",
"(",
"value",
",",
"field_type",
")",
":",
"# BigQuery cannot cast strings to booleans, convert to ints",
"if",
"field_type",
"==",
"\"BOOLEAN\"",
":",
"value",
"=",
"1",
"if",
"value",
"else",
"0",
"elif",
"field_type",
"in",
"(",
... | 26.583333 | 0.001513 |
def create(cls, source, *, transform_args=None):
"""Create an instance of the class from the source. By default cls.transform_args is used, but
can be overridden by passing in transform_args.
"""
if transform_args is None:
transform_args = cls.transform_args
return cls(get_obj(source, *transf... | [
"def",
"create",
"(",
"cls",
",",
"source",
",",
"*",
",",
"transform_args",
"=",
"None",
")",
":",
"if",
"transform_args",
"is",
"None",
":",
"transform_args",
"=",
"cls",
".",
"transform_args",
"return",
"cls",
"(",
"get_obj",
"(",
"source",
",",
"*",
... | 40.375 | 0.009091 |
def plot_pseudosection_type2(self, mid, **kwargs):
"""Create a pseudosection plot of type 2.
For a given measurement data set, create plots that graphically show
the data in a 2D color plot. Hereby, x and y coordinates in the plot
are determined by the current dipole (x-axis) and voltag... | [
"def",
"plot_pseudosection_type2",
"(",
"self",
",",
"mid",
",",
"*",
"*",
"kwargs",
")",
":",
"c",
"=",
"self",
".",
"configs",
"AB_ids",
"=",
"self",
".",
"_get_unique_identifiers",
"(",
"c",
"[",
":",
",",
"0",
":",
"2",
"]",
")",
"MN_ids",
"=",
... | 32.51046 | 0.00025 |
def replace_parameter(self, name, value=None):
""" Replace a query parameter values with a new value. If a new value does not match current
specifications, then exception is raised
:param name: parameter name to replace
:param value: new parameter value. None is for empty (null) value
:return: None
"""
s... | [
"def",
"replace_parameter",
"(",
"self",
",",
"name",
",",
"value",
"=",
"None",
")",
":",
"spec",
"=",
"self",
".",
"__specs",
"[",
"name",
"]",
"if",
"name",
"in",
"self",
".",
"__specs",
"else",
"None",
"if",
"self",
".",
"extra_parameters",
"(",
... | 42.809524 | 0.021763 |
def cache(*depends_on):
"""Caches function result in temporary file.
Cache will be expired when modification date of files from `depends_on`
will be changed.
Only functions should be wrapped in `cache`, not methods.
"""
def cache_decorator(fn):
@memoize
@wraps(fn)
def ... | [
"def",
"cache",
"(",
"*",
"depends_on",
")",
":",
"def",
"cache_decorator",
"(",
"fn",
")",
":",
"@",
"memoize",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"cache",
".",
"disabled",
... | 25.666667 | 0.001789 |
def human_size_to_bytes(human_size):
'''
Convert human-readable units to bytes
'''
size_exp_map = {'K': 1, 'M': 2, 'G': 3, 'T': 4, 'P': 5}
human_size_str = six.text_type(human_size)
match = re.match(r'^(\d+)([KMGTP])?$', human_size_str)
if not match:
raise ValueError(
'Si... | [
"def",
"human_size_to_bytes",
"(",
"human_size",
")",
":",
"size_exp_map",
"=",
"{",
"'K'",
":",
"1",
",",
"'M'",
":",
"2",
",",
"'G'",
":",
"3",
",",
"'T'",
":",
"4",
",",
"'P'",
":",
"5",
"}",
"human_size_str",
"=",
"six",
".",
"text_type",
"(",
... | 35.933333 | 0.001808 |
def buildShadowMaskImage(dqfile,detnum,extnum,maskname,bitvalue=None,binned=1):
""" Builds mask image from WFPC2 shadow calibrations.
detnum - string value for 'DETECTOR' detector
"""
# insure detnum is a string
if type(detnum) != type(''):
detnum = repr(detnum)
_funcroot = '_func_Sha... | [
"def",
"buildShadowMaskImage",
"(",
"dqfile",
",",
"detnum",
",",
"extnum",
",",
"maskname",
",",
"bitvalue",
"=",
"None",
",",
"binned",
"=",
"1",
")",
":",
"# insure detnum is a string",
"if",
"type",
"(",
"detnum",
")",
"!=",
"type",
"(",
"''",
")",
"... | 33.913043 | 0.011523 |
def get(self, key: Any, default: Any = None) -> Any:
"""
获取 cookie 中的 value
"""
if key in self:
return self[key].value
return default | [
"def",
"get",
"(",
"self",
",",
"key",
":",
"Any",
",",
"default",
":",
"Any",
"=",
"None",
")",
"->",
"Any",
":",
"if",
"key",
"in",
"self",
":",
"return",
"self",
"[",
"key",
"]",
".",
"value",
"return",
"default"
] | 25.571429 | 0.010811 |
def get_organization(self):
# type: () -> hdx.data.organization.Organization
"""Get the dataset's organization.
Returns:
Organization: Dataset's organization
"""
return hdx.data.organization.Organization.read_from_hdx(self.data['owner_org'], configuration=self.conf... | [
"def",
"get_organization",
"(",
"self",
")",
":",
"# type: () -> hdx.data.organization.Organization",
"return",
"hdx",
".",
"data",
".",
"organization",
".",
"Organization",
".",
"read_from_hdx",
"(",
"self",
".",
"data",
"[",
"'owner_org'",
"]",
",",
"configuration... | 40.375 | 0.012121 |
def strict_request_reply(msg, send: Callable, recv: Callable):
"""
Ensures a strict req-reply loop,
so that clients dont't receive out-of-order messages,
if an exception occurs between request-reply.
"""
try:
send(msg)
except Exception:
raise
try:
return recv()
... | [
"def",
"strict_request_reply",
"(",
"msg",
",",
"send",
":",
"Callable",
",",
"recv",
":",
"Callable",
")",
":",
"try",
":",
"send",
"(",
"msg",
")",
"except",
"Exception",
":",
"raise",
"try",
":",
"return",
"recv",
"(",
")",
"except",
"Exception",
":... | 24.8125 | 0.002427 |
def perturb_tmat(transmat, scale):
'''
Perturbs each nonzero entry in the MSM transition matrix by treating it as a Gaussian random variable
with mean t_ij and standard deviation equal to the standard error computed using "create_perturb_params".
Returns a sampled transition matrix that takes into consi... | [
"def",
"perturb_tmat",
"(",
"transmat",
",",
"scale",
")",
":",
"output",
"=",
"np",
".",
"vectorize",
"(",
"np",
".",
"random",
".",
"normal",
")",
"(",
"transmat",
",",
"scale",
")",
"output",
"[",
"np",
".",
"where",
"(",
"output",
"<",
"0",
")"... | 49.8 | 0.008867 |
def get_path_completion_type(cwords, cword, opts):
"""Get the type of path completion (``file``, ``dir``, ``path`` or None)
:param cwords: same as the environmental variable ``COMP_WORDS``
:param cword: same as the environmental variable ``COMP_CWORD``
:param opts: The available options to check
:r... | [
"def",
"get_path_completion_type",
"(",
"cwords",
",",
"cword",
",",
"opts",
")",
":",
"if",
"cword",
"<",
"2",
"or",
"not",
"cwords",
"[",
"cword",
"-",
"2",
"]",
".",
"startswith",
"(",
"'-'",
")",
":",
"return",
"for",
"opt",
"in",
"opts",
":",
... | 43.263158 | 0.00119 |
def get_image(image_id, flags=FLAGS.ALL, **conn):
"""
Orchestrates all the calls required to fully build out an EC2 Image (AMI, AKI, ARI)
{
"Architecture": "x86_64",
"Arn": "arn:aws:ec2:us-east-1::image/ami-11111111",
"BlockDeviceMappings": [],
"CreationDate": "2013-07-11... | [
"def",
"get_image",
"(",
"image_id",
",",
"flags",
"=",
"FLAGS",
".",
"ALL",
",",
"*",
"*",
"conn",
")",
":",
"image",
"=",
"dict",
"(",
"ImageId",
"=",
"image_id",
")",
"conn",
"[",
"'region'",
"]",
"=",
"conn",
".",
"get",
"(",
"'region'",
",",
... | 34.307692 | 0.017442 |
def _get_sequence_with_spacing(self, # pylint: disable=no-self-use
new_grammar,
expressions: List[Expression],
name: str = '') -> Sequence:
"""
This is a helper method for generating sequences, since... | [
"def",
"_get_sequence_with_spacing",
"(",
"self",
",",
"# pylint: disable=no-self-use",
"new_grammar",
",",
"expressions",
":",
"List",
"[",
"Expression",
"]",
",",
"name",
":",
"str",
"=",
"''",
")",
"->",
"Sequence",
":",
"expressions",
"=",
"[",
"subexpressio... | 51 | 0.011236 |
def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert squeeze operation.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: diction... | [
"def",
"convert_squeeze",
"(",
"params",
",",
"w_name",
",",
"scope_name",
",",
"inputs",
",",
"layers",
",",
"weights",
",",
"names",
")",
":",
"print",
"(",
"'Converting squeeze ...'",
")",
"if",
"len",
"(",
"params",
"[",
"'axes'",
"]",
")",
">",
"1",... | 33.166667 | 0.002442 |
def _add_parser_arguments_import(self, subparsers):
"""Create parser for 'import' subcommand, and associated arguments.
"""
import_pars = subparsers.add_parser(
"import", help="Import data.")
import_pars.add_argument(
'--update', '-u', dest='update',
... | [
"def",
"_add_parser_arguments_import",
"(",
"self",
",",
"subparsers",
")",
":",
"import_pars",
"=",
"subparsers",
".",
"add_parser",
"(",
"\"import\"",
",",
"help",
"=",
"\"Import data.\"",
")",
"import_pars",
".",
"add_argument",
"(",
"'--update'",
",",
"'-u'",
... | 42.136364 | 0.001054 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.