text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def add_layer_from_env(self):
"""This function creates a new layer, gets a list of all the
current attributes, and attempts to find matching environment variables
with the prefix of FJS\_. If matches are found it sets those attributes
in the new layer.
"""
self.add_layer(... | [
"def",
"add_layer_from_env",
"(",
"self",
")",
":",
"self",
".",
"add_layer",
"(",
")",
"for",
"attribute",
"in",
"self",
".",
"get_attributes",
"(",
")",
":",
"env_attribute",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'FJS_{}'",
".",
"format",
"(",
... | 46.909091 | 0.005703 |
def remove_entry(self, entry):
"""!
@brief Remove clustering feature from the leaf node.
@param[in] entry (cfentry): Clustering feature.
"""
self.feature -= entry;
self.entries.remove(entry); | [
"def",
"remove_entry",
"(",
"self",
",",
"entry",
")",
":",
"self",
".",
"feature",
"-=",
"entry",
"self",
".",
"entries",
".",
"remove",
"(",
"entry",
")"
] | 27.4 | 0.024735 |
def show_bounds(self, mesh=None, bounds=None, show_xaxis=True,
show_yaxis=True, show_zaxis=True, show_xlabels=True,
show_ylabels=True, show_zlabels=True, italic=False,
bold=True, shadow=False, font_size=None,
font_family=Non... | [
"def",
"show_bounds",
"(",
"self",
",",
"mesh",
"=",
"None",
",",
"bounds",
"=",
"None",
",",
"show_xaxis",
"=",
"True",
",",
"show_yaxis",
"=",
"True",
",",
"show_zaxis",
"=",
"True",
",",
"show_xlabels",
"=",
"True",
",",
"show_ylabels",
"=",
"True",
... | 36.6 | 0.002365 |
def commit(self):
'''
:param tag:
Checks out specified commit.
If set to ``None`` the latest commit will be checked out
:returns:
A list of all commits, descending
'''
commit = self._log(num=-1, format='%H')
if commit.get('returncode')... | [
"def",
"commit",
"(",
"self",
")",
":",
"commit",
"=",
"self",
".",
"_log",
"(",
"num",
"=",
"-",
"1",
",",
"format",
"=",
"'%H'",
")",
"if",
"commit",
".",
"get",
"(",
"'returncode'",
")",
"==",
"0",
":",
"return",
"commit",
".",
"get",
"(",
"... | 29.583333 | 0.005464 |
def pipeline_refine(d0, candloc, scaledm=2.1, scalepix=2, scaleuv=1.0, chans=[], returndata=False):
"""
Reproduces candidate and potentially improves sensitivity through better DM and imaging parameters.
scale* parameters enhance sensitivity by making refining dmgrid and images.
Other options include: ... | [
"def",
"pipeline_refine",
"(",
"d0",
",",
"candloc",
",",
"scaledm",
"=",
"2.1",
",",
"scalepix",
"=",
"2",
",",
"scaleuv",
"=",
"1.0",
",",
"chans",
"=",
"[",
"]",
",",
"returndata",
"=",
"False",
")",
":",
"import",
"rtpipe",
".",
"parseparams",
"a... | 37.21875 | 0.004089 |
def tds7_crypt_pass(password):
""" Mangle password according to tds rules
:param password: Password str
:returns: Byte-string with encoded password
"""
encoded = bytearray(ucs2_codec.encode(password)[0])
for i, ch in enumerate(encoded):
encoded[i] = ((ch << 4) & 0xff | (ch >> 4)) ^ 0xA5... | [
"def",
"tds7_crypt_pass",
"(",
"password",
")",
":",
"encoded",
"=",
"bytearray",
"(",
"ucs2_codec",
".",
"encode",
"(",
"password",
")",
"[",
"0",
"]",
")",
"for",
"i",
",",
"ch",
"in",
"enumerate",
"(",
"encoded",
")",
":",
"encoded",
"[",
"i",
"]"... | 33 | 0.00295 |
def _deconstruct_url(self, url):
""" Breaks down URL and returns server and endpoint """
url = url.split("://", 1)[-1]
server, endpoint = url.split("/", 1)
return (server, endpoint) | [
"def",
"_deconstruct_url",
"(",
"self",
",",
"url",
")",
":",
"url",
"=",
"url",
".",
"split",
"(",
"\"://\"",
",",
"1",
")",
"[",
"-",
"1",
"]",
"server",
",",
"endpoint",
"=",
"url",
".",
"split",
"(",
"\"/\"",
",",
"1",
")",
"return",
"(",
"... | 41.8 | 0.00939 |
def _calcQuadSize(corners, aspectRatio):
'''
return the size of a rectangle in perspective distortion in [px]
DEBUG: PUT THAT BACK IN??::
if aspectRatio is not given is will be determined
'''
if aspectRatio > 1: # x is bigger -> reduce y
x_length =... | [
"def",
"_calcQuadSize",
"(",
"corners",
",",
"aspectRatio",
")",
":",
"if",
"aspectRatio",
">",
"1",
":",
"# x is bigger -> reduce y\r",
"x_length",
"=",
"PerspectiveCorrection",
".",
"_quadXLength",
"(",
"corners",
")",
"y",
"=",
"x_length",
"/",
"aspectRatio",
... | 43.214286 | 0.003236 |
def WalkTree(top, getChildren: Callable = None, getFirstChild: Callable = None, getNextSibling: Callable = None, yieldCondition: Callable = None, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF):
"""
Walk a tree not using recursive algorithm.
top: a tree node.
getChildren: function(treeNode) -> lis... | [
"def",
"WalkTree",
"(",
"top",
",",
"getChildren",
":",
"Callable",
"=",
"None",
",",
"getFirstChild",
":",
"Callable",
"=",
"None",
",",
"getNextSibling",
":",
"Callable",
"=",
"None",
",",
"yieldCondition",
":",
"Callable",
"=",
"None",
",",
"includeTop",
... | 41.794118 | 0.002406 |
def get_all(self):
"""Gets all items in file."""
logger.debug('Fetching items. Path: {data_file}'.format(
data_file=self.data_file
))
return load_file(self.data_file) | [
"def",
"get_all",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Fetching items. Path: {data_file}'",
".",
"format",
"(",
"data_file",
"=",
"self",
".",
"data_file",
")",
")",
"return",
"load_file",
"(",
"self",
".",
"data_file",
")"
] | 29.285714 | 0.009479 |
def read_gtf(
filepath_or_buffer,
expand_attribute_column=True,
infer_biotype_column=False,
column_converters={},
usecols=None,
features=None,
chunksize=1024 * 1024):
"""
Parse a GTF into a dictionary mapping column names to sequences of values.
Param... | [
"def",
"read_gtf",
"(",
"filepath_or_buffer",
",",
"expand_attribute_column",
"=",
"True",
",",
"infer_biotype_column",
"=",
"False",
",",
"column_converters",
"=",
"{",
"}",
",",
"usecols",
"=",
"None",
",",
"features",
"=",
"None",
",",
"chunksize",
"=",
"10... | 40.349398 | 0.001457 |
def contains(self, x, y):
'''
Return cached bounds of this Grob.
If bounds are not cached, render to a meta surface, and
keep the meta surface and bounds cached.
'''
if self._bounds:
return self._bounds
record_surface = cairo.RecordingSurface(cairo.CO... | [
"def",
"contains",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"self",
".",
"_bounds",
":",
"return",
"self",
".",
"_bounds",
"record_surface",
"=",
"cairo",
".",
"RecordingSurface",
"(",
"cairo",
".",
"CONTENT_COLOR_ALPHA",
",",
"(",
"-",
"1",
",... | 32.666667 | 0.005952 |
def create(self, subject, displayName, issuerToken, expiration, secret):
"""Create a new guest issuer using the provided issuer token.
This function returns a guest issuer with an api access token.
Args:
subject(basestring): Unique and public identifier
displayName(base... | [
"def",
"create",
"(",
"self",
",",
"subject",
",",
"displayName",
",",
"issuerToken",
",",
"expiration",
",",
"secret",
")",
":",
"check_type",
"(",
"subject",
",",
"basestring",
")",
"check_type",
"(",
"displayName",
",",
"basestring",
")",
"check_type",
"(... | 37.255814 | 0.001217 |
def start(self, inputs):
"""Start the process.
:param inputs: An instance of `Inputs` describing the process inputs
:return: An instance of `Outputs` describing the process outputs
"""
self.logger.info("Process is starting")
outputs = Outputs(self._meta.outputs)
... | [
"def",
"start",
"(",
"self",
",",
"inputs",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"Process is starting\"",
")",
"outputs",
"=",
"Outputs",
"(",
"self",
".",
"_meta",
".",
"outputs",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Proces... | 36.541667 | 0.003333 |
def set(self, key, value):
"""
Sets the value for a specific requirement.
:param key: Name of requirement to be set
:param value: Value to set for requirement key
:return: Nothing, modifies requirement
"""
if key == "tags":
self._set_tag(tags=value)
... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"==",
"\"tags\"",
":",
"self",
".",
"_set_tag",
"(",
"tags",
"=",
"value",
")",
"else",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
"and",
"key",
"in",
"self... | 37.5 | 0.004878 |
def in_interactions_iter(self, nbunch=None, t=None):
"""Return an iterator over the in interactions present in a given snapshot.
Edges are returned as tuples in the order (node, neighbor).
Parameters
----------
nbunch : iterable container, optional (default= all nodes)
... | [
"def",
"in_interactions_iter",
"(",
"self",
",",
"nbunch",
"=",
"None",
",",
"t",
"=",
"None",
")",
":",
"if",
"nbunch",
"is",
"None",
":",
"nodes_nbrs_pred",
"=",
"self",
".",
"_pred",
".",
"items",
"(",
")",
"else",
":",
"nodes_nbrs_pred",
"=",
"[",
... | 34.041667 | 0.002974 |
def revoke_qualification(self, subject_id, qualification_type_id,
reason=None):
"""TODO: Document."""
params = {'SubjectId' : subject_id,
'QualificationTypeId' : qualification_type_id,
'Reason' : reason}
return self._process_reques... | [
"def",
"revoke_qualification",
"(",
"self",
",",
"subject_id",
",",
"qualification_type_id",
",",
"reason",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'SubjectId'",
":",
"subject_id",
",",
"'QualificationTypeId'",
":",
"qualification_type_id",
",",
"'Reason'",
":... | 49.428571 | 0.017045 |
def urls(self):
"""
The decoded URL list for this MIME::Type.
The special URL value IANA will be translated into:
http://www.iana.org/assignments/media-types/<mediatype>/<subtype>
The special URL value RFC### will be translated into:
http://www.rfc-editor.org/rfc/rfc#... | [
"def",
"urls",
"(",
"self",
")",
":",
"def",
"_url",
"(",
"el",
")",
":",
"if",
"el",
"==",
"'IANA'",
":",
"return",
"IANA_URL",
"%",
"(",
"self",
".",
"media_type",
",",
"self",
".",
"sub_type",
")",
"elif",
"el",
"==",
"'LTSW'",
":",
"return",
... | 39.675 | 0.005535 |
def trace(self, item):
"""Traces a parse element (only enabled in develop)."""
if DEVELOP:
item.debugActions = (
None, # no start action
self._trace_success_action,
self._trace_exc_action,
)
item.debug = True
re... | [
"def",
"trace",
"(",
"self",
",",
"item",
")",
":",
"if",
"DEVELOP",
":",
"item",
".",
"debugActions",
"=",
"(",
"None",
",",
"# no start action",
"self",
".",
"_trace_success_action",
",",
"self",
".",
"_trace_exc_action",
",",
")",
"item",
".",
"debug",
... | 32 | 0.006079 |
def delete_leaderboard_named(self, leaderboard_name):
'''
Delete the named leaderboard.
@param leaderboard_name [String] Name of the leaderboard.
'''
pipeline = self.redis_connection.pipeline()
pipeline.delete(leaderboard_name)
pipeline.delete(self._member_data_k... | [
"def",
"delete_leaderboard_named",
"(",
"self",
",",
"leaderboard_name",
")",
":",
"pipeline",
"=",
"self",
".",
"redis_connection",
".",
"pipeline",
"(",
")",
"pipeline",
".",
"delete",
"(",
"leaderboard_name",
")",
"pipeline",
".",
"delete",
"(",
"self",
"."... | 38.909091 | 0.004566 |
def fill_luis_event_properties(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
) -> Dict[str, str]:
"""Fills the event properties for LuisResult event for telemetry.
These properties are logged when t... | [
"def",
"fill_luis_event_properties",
"(",
"self",
",",
"recognizer_result",
":",
"RecognizerResult",
",",
"turn_context",
":",
"TurnContext",
",",
"telemetry_properties",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"None",
",",
")",
"->",
"Dict",
"[",
"str"... | 45.528571 | 0.003993 |
def _segment_lengths(self, relative=False, n=20):
""" Returns a list with the lengths of each segment in the path.
"""
# From nodebox_gl
lengths = []
first = True
for el in self._get_elements():
if first is True:
close_x, close_y = el.x, el.y
... | [
"def",
"_segment_lengths",
"(",
"self",
",",
"relative",
"=",
"False",
",",
"n",
"=",
"20",
")",
":",
"# From nodebox_gl",
"lengths",
"=",
"[",
"]",
"first",
"=",
"True",
"for",
"el",
"in",
"self",
".",
"_get_elements",
"(",
")",
":",
"if",
"first",
... | 40.617647 | 0.002829 |
def path_to_url2(path):
"""
Convert a path to a file: URL. The path will be made absolute and have
quoted path parts.
"""
path = os.path.normpath(os.path.abspath(path))
drive, path = os.path.splitdrive(path)
filepath = path.split(os.path.sep)
url = '/'.join([urllib.quote(part) for part ... | [
"def",
"path_to_url2",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"drive",
",",
"path",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"path",
")",
"file... | 33.833333 | 0.002398 |
def handle(self, *args, **kwargs):
"""
Handle execution of the command.
"""
cutoff = timezone.now()
cutoff -= app_settings.CONFIRMATION_EXPIRATION
cutoff -= app_settings.CONFIRMATION_SAVE_PERIOD
queryset = models.EmailConfirmation.objects.filter(
crea... | [
"def",
"handle",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cutoff",
"=",
"timezone",
".",
"now",
"(",
")",
"cutoff",
"-=",
"app_settings",
".",
"CONFIRMATION_EXPIRATION",
"cutoff",
"-=",
"app_settings",
".",
"CONFIRMATION_SAVE_PERIOD... | 27.423077 | 0.00271 |
def connect_value(instance, prop, widget, value_range=None, log=False):
"""
Connect a numerical callback property with a Qt widget representing a value.
Parameters
----------
instance : object
The class instance that the callback property is attached to
prop : str
The name of th... | [
"def",
"connect_value",
"(",
"instance",
",",
"prop",
",",
"widget",
",",
"value_range",
"=",
"None",
",",
"log",
"=",
"False",
")",
":",
"if",
"log",
":",
"if",
"value_range",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"log option can only be set if v... | 36.27451 | 0.003158 |
def noisy_moments(self, moments: 'Iterable[cirq.Moment]',
system_qubits: Sequence['cirq.Qid']
) -> Sequence['cirq.OP_TREE']:
"""Adds possibly stateful noise to a series of moments.
Args:
moments: The moments to add noise to.
system_qubi... | [
"def",
"noisy_moments",
"(",
"self",
",",
"moments",
":",
"'Iterable[cirq.Moment]'",
",",
"system_qubits",
":",
"Sequence",
"[",
"'cirq.Qid'",
"]",
")",
"->",
"Sequence",
"[",
"'cirq.OP_TREE'",
"]",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"noisy_moment"... | 37.807692 | 0.003968 |
def pposition(hd, details=False):
"""Parse string into angular position.
A string containing 2 or 6 numbers is parsed, and the numbers are
converted into decimal numbers. In the former case the numbers are
assumed to be floats. In the latter case, the numbers are assumed
to be sexagesimal.
Par... | [
"def",
"pposition",
"(",
"hd",
",",
"details",
"=",
"False",
")",
":",
"# :TODO: split two angles based on user entered separator and process each part separately.",
"# Split at any character other than a digit, \".\", \"-\", and \"+\".",
"p",
"=",
"re",
".",
"split",
"(",
"r\"[^... | 28.876289 | 0.00069 |
def _save_file_and_pos(self):
""" Save current position into file
"""
if not self._pos_changed:
return
with open(self.pos_storage_filename, 'w+') as f:
_pos = '%s:%s' % (self._log_file, self._log_pos)
_logger.debug('Saving position %s to file %s'
... | [
"def",
"_save_file_and_pos",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pos_changed",
":",
"return",
"with",
"open",
"(",
"self",
".",
"pos_storage_filename",
",",
"'w+'",
")",
"as",
"f",
":",
"_pos",
"=",
"'%s:%s'",
"%",
"(",
"self",
".",
"_lo... | 39.181818 | 0.004535 |
def _conditional_committors(source, sink, waypoint, tprob):
"""
Computes the conditional committors :math:`q^{ABC^+}` which are is the
probability of starting in one state and visiting state B before A while
also visiting state C at some point.
Note that in the notation of Dickson et. al. this comp... | [
"def",
"_conditional_committors",
"(",
"source",
",",
"sink",
",",
"waypoint",
",",
"tprob",
")",
":",
"n_states",
"=",
"np",
".",
"shape",
"(",
"tprob",
")",
"[",
"0",
"]",
"forward_committors",
"=",
"_committors",
"(",
"[",
"source",
"]",
",",
"[",
"... | 32.575758 | 0.001354 |
def append(self, key, _item): # type: (Union[Key, str], Any) -> Table
"""
Appends a (key, item) to the table.
"""
if not isinstance(_item, Item):
_item = item(_item)
self._value.append(key, _item)
if isinstance(key, Key):
key = key.key
... | [
"def",
"append",
"(",
"self",
",",
"key",
",",
"_item",
")",
":",
"# type: (Union[Key, str], Any) -> Table",
"if",
"not",
"isinstance",
"(",
"_item",
",",
"Item",
")",
":",
"_item",
"=",
"item",
"(",
"_item",
")",
"self",
".",
"_value",
".",
"append",
"(... | 27.37931 | 0.002433 |
def verify_psd_options_multi_ifo(opt, parser, ifos):
"""Parses the CLI options and verifies that they are consistent and
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes (psd_model, psd_file, asd_f... | [
"def",
"verify_psd_options_multi_ifo",
"(",
"opt",
",",
"parser",
",",
"ifos",
")",
":",
"for",
"ifo",
"in",
"ifos",
":",
"for",
"opt_group",
"in",
"ensure_one_opt_groups",
":",
"ensure_one_opt_multi_ifo",
"(",
"opt",
",",
"parser",
",",
"ifo",
",",
"opt_group... | 38.952381 | 0.005967 |
def stop(self):
"""
Stop all threads and modules of the client.
:return:
"""
super(BitfinexWSS, self).stop()
log.info("BitfinexWSS.stop(): Stopping client..")
log.info("BitfinexWSS.stop(): Joining receiver thread..")
try:
self.receiver_thread... | [
"def",
"stop",
"(",
"self",
")",
":",
"super",
"(",
"BitfinexWSS",
",",
"self",
")",
".",
"stop",
"(",
")",
"log",
".",
"info",
"(",
"\"BitfinexWSS.stop(): Stopping client..\"",
")",
"log",
".",
"info",
"(",
"\"BitfinexWSS.stop(): Joining receiver thread..\"",
"... | 30.74359 | 0.001617 |
def indication(self, pdu):
"""Client requests are queued for delivery."""
if _debug: UDPDirector._debug("indication %r", pdu)
# get the destination
addr = pdu.pduDestination
# get the peer
peer = self.peers.get(addr, None)
if not peer:
peer = self.ac... | [
"def",
"indication",
"(",
"self",
",",
"pdu",
")",
":",
"if",
"_debug",
":",
"UDPDirector",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"pdu",
")",
"# get the destination",
"addr",
"=",
"pdu",
".",
"pduDestination",
"# get the peer",
"peer",
"=",
"self",
"... | 27.428571 | 0.007557 |
def get_default_view_path(resource):
"Returns the dotted path to the default view class."
parts = [a.member_name for a in resource.ancestors] +\
[resource.collection_name or resource.member_name]
if resource.prefix:
parts.insert(-1, resource.prefix)
view_file = '%s' % '_'.join(par... | [
"def",
"get_default_view_path",
"(",
"resource",
")",
":",
"parts",
"=",
"[",
"a",
".",
"member_name",
"for",
"a",
"in",
"resource",
".",
"ancestors",
"]",
"+",
"[",
"resource",
".",
"collection_name",
"or",
"resource",
".",
"member_name",
"]",
"if",
"reso... | 34.642857 | 0.002008 |
def from_filenames(filenames, transformations=None, primitive=True,
extend_collection=False):
"""
Generates a TransformedStructureCollection from a cif, possibly
containing multiple structures.
Args:
filenames: List of strings of the cif files
... | [
"def",
"from_filenames",
"(",
"filenames",
",",
"transformations",
"=",
"None",
",",
"primitive",
"=",
"True",
",",
"extend_collection",
"=",
"False",
")",
":",
"allcifs",
"=",
"[",
"]",
"for",
"fname",
"in",
"filenames",
":",
"with",
"open",
"(",
"fname",... | 39.47619 | 0.003534 |
def get_migrations_dir(graph):
"""
Resolve the migrations directory path.
Either take the directory from a component of the object graph or by
using the metaata's path resolution facilities.
"""
try:
migrations_dir = graph.migrations_dir
except (LockedGraphError, NotBoundError):
... | [
"def",
"get_migrations_dir",
"(",
"graph",
")",
":",
"try",
":",
"migrations_dir",
"=",
"graph",
".",
"migrations_dir",
"except",
"(",
"LockedGraphError",
",",
"NotBoundError",
")",
":",
"migrations_dir",
"=",
"graph",
".",
"metadata",
".",
"get_path",
"(",
"\... | 31.625 | 0.001919 |
def filter_permissions(self, search):
"""Filter given query based on permissions of the user in the request.
:param search: ElasticSearch query object
"""
user = self.request.user
if user.is_superuser:
return search
if user.is_anonymous:
user = g... | [
"def",
"filter_permissions",
"(",
"self",
",",
"search",
")",
":",
"user",
"=",
"self",
".",
"request",
".",
"user",
"if",
"user",
".",
"is_superuser",
":",
"return",
"search",
"if",
"user",
".",
"is_anonymous",
":",
"user",
"=",
"get_anonymous_user",
"(",... | 33.8 | 0.004317 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | [
"def",
"get_mean_and_stddevs",
"(",
"self",
",",
"sites",
",",
"rup",
",",
"dists",
",",
"imt",
",",
"stddev_types",
")",
":",
"# extracting dictionary of coefficients specific to required",
"# intensity measure type.",
"C",
"=",
"self",
".",
"COEFFS_SSLAB",
"[",
"imt... | 39.324324 | 0.001341 |
def create_packages(self):
"""Create missing packages joining the vendor root to the base of the vendored distribution.
For example, given a root at ``/home/jake/dev/pantsbuild/pex`` and a vendored distribution at
``pex/vendor/_vendored/requests`` this method would create the following package files::
... | [
"def",
"create_packages",
"(",
"self",
")",
":",
"for",
"index",
",",
"_",
"in",
"enumerate",
"(",
"self",
".",
"_subpath_components",
")",
":",
"relpath",
"=",
"_PACKAGE_COMPONENTS",
"+",
"self",
".",
"_subpath_components",
"[",
":",
"index",
"+",
"1",
"]... | 51 | 0.009627 |
def fit(self, X, y, **args):
"""
The fit method is the primary entry point for the manual alpha
selection visualizer. It sets the alpha param for each alpha in the
alphas list on the wrapped estimator, then scores the model using the
passed in X and y data set. Those scores are t... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"*",
"*",
"args",
")",
":",
"self",
".",
"errors",
"=",
"[",
"]",
"for",
"alpha",
"in",
"self",
".",
"alphas",
":",
"self",
".",
"estimator",
".",
"set_params",
"(",
"alpha",
"=",
"alpha",
")"... | 38.3 | 0.002548 |
def flattenTrees(root, nodeSelector: Callable[[LNode], bool]):
"""
Walk all nodes and discover trees of nodes (usually operators)
and reduce them to single node with multiple outputs
:attention: selected nodes has to have single output
and has to be connected to nets with single driver
... | [
"def",
"flattenTrees",
"(",
"root",
",",
"nodeSelector",
":",
"Callable",
"[",
"[",
"LNode",
"]",
",",
"bool",
"]",
")",
":",
"for",
"ch",
"in",
"root",
".",
"children",
":",
"if",
"ch",
".",
"children",
":",
"flattenTrees",
"(",
"ch",
",",
"nodeSele... | 37.238095 | 0.000831 |
def write(self, path, prog=None, format='raw'):
"""Write graph to file in selected format.
Given a filename 'path' it will open/create and truncate
such file and write on it a representation of the graph
defined by the dot object and in the format specified by
'format'. 'path' c... | [
"def",
"write",
"(",
"self",
",",
"path",
",",
"prog",
"=",
"None",
",",
"format",
"=",
"'raw'",
")",
":",
"if",
"prog",
"is",
"None",
":",
"prog",
"=",
"self",
".",
"prog",
"fobj",
",",
"close",
"=",
"get_fobj",
"(",
"path",
",",
"'w+b'",
")",
... | 33.280702 | 0.001024 |
def group_items(items, groupids):
r"""
Groups a list of items by group id.
Args:
items (Iterable): a list of items to group
groupids (Iterable or Callable): a corresponding list of item groupids
or a function mapping an item to a groupid.
Returns:
dict: groupid_to_i... | [
"def",
"group_items",
"(",
"items",
",",
"groupids",
")",
":",
"if",
"callable",
"(",
"groupids",
")",
":",
"keyfunc",
"=",
"groupids",
"pair_list",
"=",
"(",
"(",
"keyfunc",
"(",
"item",
")",
",",
"item",
")",
"for",
"item",
"in",
"items",
")",
"els... | 34.714286 | 0.003203 |
def multi_iter(iterable, count=2):
"""Return `count` independent, thread-safe iterators for `iterable`"""
# no need to special-case re-usable, container-like iterables
if not isinstance(
iterable,
(
list, tuple, set,
FutureChainResults,
... | [
"def",
"multi_iter",
"(",
"iterable",
",",
"count",
"=",
"2",
")",
":",
"# no need to special-case re-usable, container-like iterables",
"if",
"not",
"isinstance",
"(",
"iterable",
",",
"(",
"list",
",",
"tuple",
",",
"set",
",",
"FutureChainResults",
",",
"collec... | 43.083333 | 0.003788 |
def get_file_to_bytes(self, share_name, directory_name, file_name,
start_range=None, end_range=None, range_get_content_md5=None,
progress_callback=None, max_connections=1, max_retries=5,
retry_wait=1.0, timeout=None):
'''
Dow... | [
"def",
"get_file_to_bytes",
"(",
"self",
",",
"share_name",
",",
"directory_name",
",",
"file_name",
",",
"start_range",
"=",
"None",
",",
"end_range",
"=",
"None",
",",
"range_get_content_md5",
"=",
"None",
",",
"progress_callback",
"=",
"None",
",",
"max_conne... | 47.086957 | 0.005728 |
def memcache_get(self, key, for_cas=False, namespace=None, use_cache=False,
deadline=None):
"""An auto-batching wrapper for memcache.get() or .get_multi().
Args:
key: Key to set. This must be a string; no prefix is applied.
for_cas: If True, request and store CAS ids on the Cont... | [
"def",
"memcache_get",
"(",
"self",
",",
"key",
",",
"for_cas",
"=",
"False",
",",
"namespace",
"=",
"None",
",",
"use_cache",
"=",
"False",
",",
"deadline",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"basestring",
")",
":",
"... | 37.846154 | 0.006938 |
async def reinvoke(self, *, call_hooks=False, restart=True):
"""|coro|
Calls the command again.
This is similar to :meth:`~.Context.invoke` except that it bypasses
checks, cooldowns, and error handlers.
.. note::
If you want to bypass :exc:`.UserInputError` derive... | [
"async",
"def",
"reinvoke",
"(",
"self",
",",
"*",
",",
"call_hooks",
"=",
"False",
",",
"restart",
"=",
"True",
")",
":",
"cmd",
"=",
"self",
".",
"command",
"view",
"=",
"self",
".",
"view",
"if",
"cmd",
"is",
"None",
":",
"raise",
"ValueError",
... | 35.415094 | 0.001555 |
def to_dataframe(self):
"""Export grid data to dataframes for statistical analysis.
The export to dataframe is similar to db tables exported by `export_mv_grid_new`.
Returns
-------
:pandas:`pandas.DataFrame<dataframe>`
Pandas Data Frame
See Als... | [
"def",
"to_dataframe",
"(",
"self",
")",
":",
"node_cols",
"=",
"[",
"'node_id'",
",",
"'grid_id'",
",",
"'v_nom'",
",",
"'geom'",
",",
"'v_res0'",
",",
"'v_res1'",
",",
"'peak_load'",
",",
"'generation_capacity'",
",",
"'type'",
"]",
"edges_cols",
"=",
"[",... | 45.439655 | 0.003713 |
def killBatchJobs(self, jobIDs):
"""
Kills the given jobs, represented as Job ids, then checks they are dead by checking
they are not in the list of issued jobs.
"""
self.killLocalJobs(jobIDs)
jobIDs = set(jobIDs)
logger.debug('Jobs to be killed: %r', jobIDs)
... | [
"def",
"killBatchJobs",
"(",
"self",
",",
"jobIDs",
")",
":",
"self",
".",
"killLocalJobs",
"(",
"jobIDs",
")",
"jobIDs",
"=",
"set",
"(",
"jobIDs",
")",
"logger",
".",
"debug",
"(",
"'Jobs to be killed: %r'",
",",
"jobIDs",
")",
"for",
"jobID",
"in",
"j... | 39.9 | 0.004896 |
def pls(df):
"""
A simple implementation of a least-squares approach to imputation using partial least squares
regression (PLS).
:param df:
:return:
"""
if not sklearn:
assert('This library depends on scikit-learn (sklearn) to perform PLS-based imputation')
df = df.copy()
... | [
"def",
"pls",
"(",
"df",
")",
":",
"if",
"not",
"sklearn",
":",
"assert",
"(",
"'This library depends on scikit-learn (sklearn) to perform PLS-based imputation'",
")",
"df",
"=",
"df",
".",
"copy",
"(",
")",
"df",
"[",
"np",
".",
"isinf",
"(",
"df",
")",
"]"... | 27.489796 | 0.009319 |
def convert_to_tflayer_args(args_names, name_mapping):
"""
After applying this decorator:
1. data_format becomes tf.layers style
2. nl becomes activation
3. initializers are renamed
4. positional args are transformed to corresponding kwargs, according to args_names
5. kwargs are mapped to tf... | [
"def",
"convert_to_tflayer_args",
"(",
"args_names",
",",
"name_mapping",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"decorated_func",
"(",
"inputs",
",",
"*",
"args",
",",
"*",
"*",
"kwa... | 37.184211 | 0.003448 |
def load_tabs(self):
"""Loads the tab group.
It compiles the table instances for each table attached to
any :class:`horizon.tabs.TableTab` instances on the tab group.
This step is necessary before processing any tab or table actions.
"""
tab_group = self.get_tabs(self.re... | [
"def",
"load_tabs",
"(",
"self",
")",
":",
"tab_group",
"=",
"self",
".",
"get_tabs",
"(",
"self",
".",
"request",
",",
"*",
"*",
"self",
".",
"kwargs",
")",
"tabs",
"=",
"tab_group",
".",
"get_tabs",
"(",
")",
"for",
"tab",
"in",
"[",
"t",
"for",
... | 48.5 | 0.00289 |
def read_data(self, **kwargs):
"""
get the data from the service
:param kwargs: contain keyword args : trigger_id at least
:type kwargs: dict
:rtype: list
"""
date_triggered = kwargs.get('date_triggered')
trigger_id = kwargs.get('trigger_... | [
"def",
"read_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"date_triggered",
"=",
"kwargs",
".",
"get",
"(",
"'date_triggered'",
")",
"trigger_id",
"=",
"kwargs",
".",
"get",
"(",
"'trigger_id'",
")",
"kwargs",
"[",
"'model_name'",
"]",
"=",
"'E... | 31.695652 | 0.002663 |
def replace_namespaced_daemon_set_status(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_daemon_set_status # noqa: E501
replace status of the specified DaemonSet # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous H... | [
"def",
"replace_namespaced_daemon_set_status",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req... | 63.04 | 0.00125 |
def stop(self):
"""Stop the daemon."""
pid = None
if os.path.exists(self.pidfile):
with open(self.pidfile, 'r') as fp:
pid = int(fp.read().strip())
if not pid:
msg = 'pidfile (%s) does not exist. Daemon not running?\n'
sys.stderr.write... | [
"def",
"stop",
"(",
"self",
")",
":",
"pid",
"=",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"pidfile",
")",
":",
"with",
"open",
"(",
"self",
".",
"pidfile",
",",
"'r'",
")",
"as",
"fp",
":",
"pid",
"=",
"int",
"(",
"f... | 29.791667 | 0.00271 |
def getDefaultUncertainty(self, result=None):
"""Return the uncertainty value, if the result falls within
specified ranges for the service from which this analysis was derived.
"""
if result is None:
result = self.getResult()
uncertainties = self.getUncertainties()
... | [
"def",
"getDefaultUncertainty",
"(",
"self",
",",
"result",
"=",
"None",
")",
":",
"if",
"result",
"is",
"None",
":",
"result",
"=",
"self",
".",
"getResult",
"(",
")",
"uncertainties",
"=",
"self",
".",
"getUncertainties",
"(",
")",
"if",
"uncertainties",... | 37.645161 | 0.001671 |
def argrelmin(data, axis=0, order=1, mode='clip'):
"""
Calculate the relative minima of `data`.
.. versionadded:: 0.11.0
Parameters
----------
data : ndarray
Array in which to find the relative minima.
axis : int, optional
Axis over which to select from `data`. Default is ... | [
"def",
"argrelmin",
"(",
"data",
",",
"axis",
"=",
"0",
",",
"order",
"=",
"1",
",",
"mode",
"=",
"'clip'",
")",
":",
"return",
"argrelextrema",
"(",
"data",
",",
"np",
".",
"less",
",",
"axis",
",",
"order",
",",
"mode",
")"
] | 27.472222 | 0.000977 |
def roc_curve(df, col_true=None, col_pred=None, col_scores=None, pos_label=1):
r"""
Compute true positive rate (TPR), false positive rate (FPR) and threshold from predicted DataFrame.
Note that this method will trigger the defined flow to execute.
:param df: predicted data frame
:type df: DataFram... | [
"def",
"roc_curve",
"(",
"df",
",",
"col_true",
"=",
"None",
",",
"col_pred",
"=",
"None",
",",
"col_scores",
"=",
"None",
",",
"pos_label",
"=",
"1",
")",
":",
"if",
"not",
"col_pred",
":",
"col_pred",
"=",
"get_field_name_by_role",
"(",
"df",
",",
"F... | 36.725 | 0.002653 |
def _parse_notes_dict(sbase):
""" Creates dictionary of COBRA notes.
Parameters
----------
sbase : libsbml.SBase
Returns
-------
dict of notes
"""
notes = sbase.getNotesString()
if notes and len(notes) > 0:
pattern = r"<p>\s*(\w+\s*\w*)\s*:\s*([\w|\s]+)<"
matche... | [
"def",
"_parse_notes_dict",
"(",
"sbase",
")",
":",
"notes",
"=",
"sbase",
".",
"getNotesString",
"(",
")",
"if",
"notes",
"and",
"len",
"(",
"notes",
")",
">",
"0",
":",
"pattern",
"=",
"r\"<p>\\s*(\\w+\\s*\\w*)\\s*:\\s*([\\w|\\s]+)<\"",
"matches",
"=",
"re",... | 25 | 0.002028 |
def lostitem_delete_view(request, item_id):
"""Delete a lostitem.
id: lostitem id
"""
if request.method == "POST":
try:
a = LostItem.objects.get(id=item_id)
if request.POST.get("full_delete", False):
a.delete()
messages.success(request, "... | [
"def",
"lostitem_delete_view",
"(",
"request",
",",
"item_id",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"try",
":",
"a",
"=",
"LostItem",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"item_id",
")",
"if",
"request",
".",
"POST",
... | 32.043478 | 0.003953 |
def GetRDFValueType(self):
"""Returns this attribute's RDFValue class."""
result = self.attribute_type
for field_name in self.field_names:
# Support the new semantic protobufs.
try:
result = result.type_infos.get(field_name).type
except AttributeError:
raise AttributeError(... | [
"def",
"GetRDFValueType",
"(",
"self",
")",
":",
"result",
"=",
"self",
".",
"attribute_type",
"for",
"field_name",
"in",
"self",
".",
"field_names",
":",
"# Support the new semantic protobufs.",
"try",
":",
"result",
"=",
"result",
".",
"type_infos",
".",
"get"... | 33.181818 | 0.010667 |
def stroke(self,*args):
'''Set a stroke color, applying it to new paths.'''
self._strokecolor = self.color(*args)
return self._strokecolor | [
"def",
"stroke",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"_strokecolor",
"=",
"self",
".",
"color",
"(",
"*",
"args",
")",
"return",
"self",
".",
"_strokecolor"
] | 39.75 | 0.018519 |
def toBytes(x):
'''
x-->unicode string | bytearray | bytes
Returns-->bytes
If x is unicode, MUST have encoding=latin1
'''
if isinstance(x, bytes):
return x
elif isinstance(x, bytearray):
return bytes(x)
elif isinstance(x, unicode):
pass
else:
return x ... | [
"def",
"toBytes",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"bytes",
")",
":",
"return",
"x",
"elif",
"isinstance",
"(",
"x",
",",
"bytearray",
")",
":",
"return",
"bytes",
"(",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"unicode",... | 26.1875 | 0.002304 |
def file_sign( blockchain_id, hostname, input_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ):
"""
Sign a file with the current blockchain ID's host's public key.
@config_path should be for the *client*, not blockstack-file
Return {'status': True, 'sender_key_id': ..., 'sig': ...} on ... | [
"def",
"file_sign",
"(",
"blockchain_id",
",",
"hostname",
",",
"input_path",
",",
"passphrase",
"=",
"None",
",",
"config_path",
"=",
"CONFIG_PATH",
",",
"wallet_keys",
"=",
"None",
")",
":",
"config_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"con... | 46.095238 | 0.012146 |
def parse_directive_locations(lexer: Lexer) -> List[NameNode]:
"""DirectiveLocations"""
# optional leading pipe
expect_optional_token(lexer, TokenKind.PIPE)
locations: List[NameNode] = []
append = locations.append
while True:
append(parse_directive_location(lexer))
if not expect_... | [
"def",
"parse_directive_locations",
"(",
"lexer",
":",
"Lexer",
")",
"->",
"List",
"[",
"NameNode",
"]",
":",
"# optional leading pipe",
"expect_optional_token",
"(",
"lexer",
",",
"TokenKind",
".",
"PIPE",
")",
"locations",
":",
"List",
"[",
"NameNode",
"]",
... | 35.181818 | 0.002519 |
def localize_date(date, city):
""" Localize date into city
Date: datetime
City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'..
"""
local = pytz.timezone(city)
local_dt = local.localize(date, is_dst=None)
return local_dt | [
"def",
"localize_date",
"(",
"date",
",",
"city",
")",
":",
"local",
"=",
"pytz",
".",
"timezone",
"(",
"city",
")",
"local_dt",
"=",
"local",
".",
"localize",
"(",
"date",
",",
"is_dst",
"=",
"None",
")",
"return",
"local_dt"
] | 29.111111 | 0.003704 |
def update(self, key, data):
"""Update document by key with partial data.
Updates the document matching _id=<key> with 'data'
Where 1st argument 'key' is <key>
'data' may contain dot notation fields in
order to specify nested values in the documents, e.g.
colle... | [
"def",
"update",
"(",
"self",
",",
"key",
",",
"data",
")",
":",
"if",
"key",
":",
"spec",
"=",
"{",
"'_id'",
":",
"key",
"}",
"write",
"=",
"data",
".",
"copy",
"(",
")",
"response",
"=",
"self",
".",
"_collection",
".",
"update",
"(",
"spec",
... | 35 | 0.001738 |
def grad_log_likelihood(self, y, quiet=False):
"""
Compute the gradient of the marginalized likelihood
The factorized matrix from the previous call to :func:`GP.compute` is
used so ``compute`` must be called first. The gradient is taken with
respect to the parameters returned by... | [
"def",
"grad_log_likelihood",
"(",
"self",
",",
"y",
",",
"quiet",
"=",
"False",
")",
":",
"if",
"not",
"solver",
".",
"has_autodiff",
"(",
")",
":",
"raise",
"RuntimeError",
"(",
"\"celerite must be compiled with autodiff \"",
"\"support to use the gradient methods\"... | 38.085714 | 0.000731 |
def remove_edge(self, p_from, p_to, p_remove_unconnected_nodes=True):
"""
Removes an edge from the graph.
When remove_unconnected_nodes is True, then the nodes are also removed
if they become isolated.
"""
if self.has_edge(p_from, p_to):
self._edges[p_from].r... | [
"def",
"remove_edge",
"(",
"self",
",",
"p_from",
",",
"p_to",
",",
"p_remove_unconnected_nodes",
"=",
"True",
")",
":",
"if",
"self",
".",
"has_edge",
"(",
"p_from",
",",
"p_to",
")",
":",
"self",
".",
"_edges",
"[",
"p_from",
"]",
".",
"remove",
"(",... | 29.809524 | 0.003096 |
async def delete(self, key):
""" Fix me after support 204 code in aiohttp """
try:
async with self._client.delete(self.path_keys(key)) as r:
if r.status not in [204, 404]:
return False
return True
except ContentEncodingError:
... | [
"async",
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"async",
"with",
"self",
".",
"_client",
".",
"delete",
"(",
"self",
".",
"path_keys",
"(",
"key",
")",
")",
"as",
"r",
":",
"if",
"r",
".",
"status",
"not",
"in",
"[",
"2... | 33.083333 | 0.007353 |
def get_object(self, bucket_name, object_name, request_headers=None, sse=None):
"""
Retrieves an object from a bucket.
This function returns an object that contains an open network
connection to enable incremental consumption of the
response. To re-use the connection (if desired... | [
"def",
"get_object",
"(",
"self",
",",
"bucket_name",
",",
"object_name",
",",
"request_headers",
"=",
"None",
",",
"sse",
"=",
"None",
")",
":",
"is_valid_bucket_name",
"(",
"bucket_name",
")",
"is_non_empty_string",
"(",
"object_name",
")",
"return",
"self",
... | 41.538462 | 0.002715 |
def oauth_login(self, provider, id_column, id, attrs, defaults, redirect_url=None):
"""Execute a login via oauth. If no user exists, oauth_signup() will be called
"""
user = self.query.filter(**dict([(id_column, id)])).first()
if not redirect_url:
redirect_url = request.args.... | [
"def",
"oauth_login",
"(",
"self",
",",
"provider",
",",
"id_column",
",",
"id",
",",
"attrs",
",",
"defaults",
",",
"redirect_url",
"=",
"None",
")",
":",
"user",
"=",
"self",
".",
"query",
".",
"filter",
"(",
"*",
"*",
"dict",
"(",
"[",
"(",
"id_... | 56.684211 | 0.006393 |
def load(param):
"""
If the supplied parameter is a string, assum it's a simple
pattern.
"""
return (
Pattern(param) if isinstance(param, str)
else param if param is not None
else Null()
) | [
"def",
"load",
"(",
"param",
")",
":",
"return",
"(",
"Pattern",
"(",
"param",
")",
"if",
"isinstance",
"(",
"param",
",",
"str",
")",
"else",
"param",
"if",
"param",
"is",
"not",
"None",
"else",
"Null",
"(",
")",
")"
] | 22.7 | 0.004237 |
def fail(state, msg="fail"):
"""Always fails the SCT, with an optional msg.
This function takes a single argument, ``msg``, that is the feedback given to the student.
Note that this would be a terrible idea for grading submissions, but may be useful while writing SCTs.
For example, failing a test will ... | [
"def",
"fail",
"(",
"state",
",",
"msg",
"=",
"\"fail\"",
")",
":",
"_msg",
"=",
"state",
".",
"build_message",
"(",
"msg",
")",
"state",
".",
"report",
"(",
"Feedback",
"(",
"_msg",
",",
"state",
")",
")",
"return",
"state"
] | 42.909091 | 0.008299 |
def to_yaml(self):
"""Store an instance to the referenced YAML file."""
import yaml
with self.__reference__.open('w') as fp:
yaml.dump(self.asjsonld(), fp, default_flow_style=False) | [
"def",
"to_yaml",
"(",
"self",
")",
":",
"import",
"yaml",
"with",
"self",
".",
"__reference__",
".",
"open",
"(",
"'w'",
")",
"as",
"fp",
":",
"yaml",
".",
"dump",
"(",
"self",
".",
"asjsonld",
"(",
")",
",",
"fp",
",",
"default_flow_style",
"=",
... | 35.5 | 0.009174 |
def strip_email_quotes(text):
"""Strip leading email quotation characters ('>').
Removes any combination of leading '>' interspersed with whitespace that
appears *identically* in all lines of the input text.
Parameters
----------
text : str
Examples
--------
Simple uses::
... | [
"def",
"strip_email_quotes",
"(",
"text",
")",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
")",
"matches",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"lines",
":",
"prefix",
"=",
"re",
".",
"match",
"(",
"r'^(\\s*>[ >]*)'",
",",
"line",
")",
"... | 27.195652 | 0.002315 |
def fit_predict(self, y, exogenous=None, n_periods=10, **fit_args):
"""Fit an ARIMA to a vector, ``y``, of observations with an
optional matrix of ``exogenous`` variables, and then generate
predictions.
Parameters
----------
y : array-like or iterable, shape=(n_samples,)... | [
"def",
"fit_predict",
"(",
"self",
",",
"y",
",",
"exogenous",
"=",
"None",
",",
"n_periods",
"=",
"10",
",",
"*",
"*",
"fit_args",
")",
":",
"self",
".",
"fit",
"(",
"y",
",",
"exogenous",
",",
"*",
"*",
"fit_args",
")",
"return",
"self",
".",
"... | 49.310345 | 0.001372 |
def get_wulff_shape(self, material_id):
"""
Constructs a Wulff shape for a material.
Args:
material_id (str): Materials Project material_id, e.g. 'mp-123'.
Returns:
pymatgen.analysis.wulff.WulffShape
"""
from pymatgen.symmetry.analyzer import Spac... | [
"def",
"get_wulff_shape",
"(",
"self",
",",
"material_id",
")",
":",
"from",
"pymatgen",
".",
"symmetry",
".",
"analyzer",
"import",
"SpacegroupAnalyzer",
"from",
"pymatgen",
".",
"analysis",
".",
"wulff",
"import",
"WulffShape",
",",
"hkl_tuple_to_str",
"structur... | 45.125 | 0.001808 |
def is_port_open(self, port, timeout=2):
"""
check if given port is open and receiving connections on container ip_address
:param port: int, container port
:param timeout: int, how many seconds to wait for connection; defaults to 2
:return: True if the connection has been establ... | [
"def",
"is_port_open",
"(",
"self",
",",
"port",
",",
"timeout",
"=",
"2",
")",
":",
"addresses",
"=",
"self",
".",
"get_IPv4s",
"(",
")",
"if",
"not",
"addresses",
":",
"return",
"False",
"return",
"check_port",
"(",
"port",
",",
"host",
"=",
"address... | 42.833333 | 0.009524 |
def compile(self):
"""
Compile this expression into an ODPS SQL
:return: compiled DAG
:rtype: str
"""
from ..engines import get_default_engine
engine = get_default_engine(self)
return engine.compile(self) | [
"def",
"compile",
"(",
"self",
")",
":",
"from",
".",
".",
"engines",
"import",
"get_default_engine",
"engine",
"=",
"get_default_engine",
"(",
"self",
")",
"return",
"engine",
".",
"compile",
"(",
"self",
")"
] | 21.666667 | 0.00738 |
def _prepare_tokens_for_encode(tokens):
"""Prepare tokens for encoding.
Tokens followed by a single space have "_" appended and the single space token
is dropped.
If a token is _UNDERSCORE_REPLACEMENT, it is broken up into 2 tokens.
Args:
tokens: `list<str>`, tokens to prepare.
Returns:
`list<st... | [
"def",
"_prepare_tokens_for_encode",
"(",
"tokens",
")",
":",
"prepared_tokens",
"=",
"[",
"]",
"def",
"_prepare_token",
"(",
"t",
",",
"next_t",
")",
":",
"skip_next",
"=",
"False",
"t",
"=",
"_escape",
"(",
"t",
")",
"# If next token is a single space, add _ s... | 28.413043 | 0.014053 |
def set_sources(self, sources):
"""
Creates GeocodeServiceConfigs from each str source
"""
if len(sources) == 0:
raise Exception('Must declare at least one source for a geocoder')
self._sources = []
for source in sources: # iterate through a list of sources
... | [
"def",
"set_sources",
"(",
"self",
",",
"sources",
")",
":",
"if",
"len",
"(",
"sources",
")",
"==",
"0",
":",
"raise",
"Exception",
"(",
"'Must declare at least one source for a geocoder'",
")",
"self",
".",
"_sources",
"=",
"[",
"]",
"for",
"source",
"in",... | 38.444444 | 0.00565 |
def pearson(x, y):
""" Correlates row vector x with each row vector in 2D array y. """
data = np.vstack((x, y))
ms = data.mean(axis=1)[(slice(None, None, None), None)]
datam = data - ms
datass = np.sqrt(np.sum(datam**2, axis=1))
temp = np.dot(datam[1:], datam[0].T)
rs = temp / (datass[1:] * ... | [
"def",
"pearson",
"(",
"x",
",",
"y",
")",
":",
"data",
"=",
"np",
".",
"vstack",
"(",
"(",
"x",
",",
"y",
")",
")",
"ms",
"=",
"data",
".",
"mean",
"(",
"axis",
"=",
"1",
")",
"[",
"(",
"slice",
"(",
"None",
",",
"None",
",",
"None",
")"... | 37.333333 | 0.002907 |
def call(cls, iterable, *a, **kw):
"""
Calls every item in *iterable* with the specified arguments.
"""
return cls(x(*a, **kw) for x in iterable) | [
"def",
"call",
"(",
"cls",
",",
"iterable",
",",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"return",
"cls",
"(",
"x",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
"for",
"x",
"in",
"iterable",
")"
] | 26.166667 | 0.006173 |
def load(jwks):
"""Parse a JWKSet and return a dictionary that maps key IDs on keys."""
sign_keys = {}
verify_keys = {}
try:
keyset = json.loads(jwks)
for key in keyset['keys']:
for op in key['key_ops']:
if op == 'sign':
k = sign_keys
... | [
"def",
"load",
"(",
"jwks",
")",
":",
"sign_keys",
"=",
"{",
"}",
"verify_keys",
"=",
"{",
"}",
"try",
":",
"keyset",
"=",
"json",
".",
"loads",
"(",
"jwks",
")",
"for",
"key",
"in",
"keyset",
"[",
"'keys'",
"]",
":",
"for",
"op",
"in",
"key",
... | 42.8 | 0.003656 |
def submit(command_filename, workingdir, send_mail = False, username = None):
'''Submit the given command filename to the queue. Adapted from the qb3 example.'''
return sge_interface.submit(command_filename, workingdir, send_mail = send_mail, username = username) | [
"def",
"submit",
"(",
"command_filename",
",",
"workingdir",
",",
"send_mail",
"=",
"False",
",",
"username",
"=",
"None",
")",
":",
"return",
"sge_interface",
".",
"submit",
"(",
"command_filename",
",",
"workingdir",
",",
"send_mail",
"=",
"send_mail",
",",
... | 89.666667 | 0.04059 |
def devmodel_to_array(model_name, train_fraction=1):
"""
a standardized method of turning a dev_model object into training and
testing arrays
Parameters
----------
model_name: dev_model
the dev_model object to be interrogated
train_fraction: int
the fraction to be reserved f... | [
"def",
"devmodel_to_array",
"(",
"model_name",
",",
"train_fraction",
"=",
"1",
")",
":",
"model_outputs",
"=",
"-",
"6",
"+",
"model_name",
".",
"Data_summary",
".",
"shape",
"[",
"0",
"]",
"devmodel",
"=",
"model_name",
"rawdf",
"=",
"devmodel",
".",
"Da... | 30.043478 | 0.000701 |
def remove(self, pk):
"""Remove an item from the cart.
Parameters
----------
pk : str or int
The primary key of the item.
Raises
------
ItemNotInCart
"""
pk = str(pk)
try:
del self.items[pk]
except KeyErro... | [
"def",
"remove",
"(",
"self",
",",
"pk",
")",
":",
"pk",
"=",
"str",
"(",
"pk",
")",
"try",
":",
"del",
"self",
".",
"items",
"[",
"pk",
"]",
"except",
"KeyError",
":",
"raise",
"ItemNotInCart",
"(",
"pk",
"=",
"pk",
")",
"self",
".",
"update",
... | 19.210526 | 0.005222 |
def _extract_traceback(text):
"""Receive a list of strings representing the input from stdin and return
the restructured backtrace.
This iterates over the output and once it identifies a hopefully genuine
identifier, it will start parsing output.
In the case the input includes a reraise (a Python 3... | [
"def",
"_extract_traceback",
"(",
"text",
")",
":",
"capture",
"=",
"False",
"entries",
"=",
"[",
"]",
"all_else",
"=",
"[",
"]",
"ignore_trace",
"=",
"False",
"# In python 3, a traceback may includes output from a reraise.",
"# e.g, an exception is captured and reraised wi... | 38.3 | 0.000424 |
def _find_variable(self, pattern, logline):
"""
Return the variable parts of the code given a tuple of strings pattern.
Example: (this, is, a, pattern) -> 'this is a good pattern' -> [good]
"""
var_subs = []
# find the beginning of the pattern
first_index = logli... | [
"def",
"_find_variable",
"(",
"self",
",",
"pattern",
",",
"logline",
")",
":",
"var_subs",
"=",
"[",
"]",
"# find the beginning of the pattern",
"first_index",
"=",
"logline",
".",
"index",
"(",
"pattern",
"[",
"0",
"]",
")",
"beg_str",
"=",
"logline",
"[",... | 40.352941 | 0.001423 |
def makefig(code, code_path, output_dir, output_base, config):
"""
Run a pyplot script *code* and save the images under *output_dir*
with file names derived from *output_base*
"""
# -- Parse format list
default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 50}
formats = []
for fmt in conf... | [
"def",
"makefig",
"(",
"code",
",",
"code_path",
",",
"output_dir",
",",
"output_base",
",",
"config",
")",
":",
"# -- Parse format list",
"default_dpi",
"=",
"{",
"'png'",
":",
"80",
",",
"'hires.png'",
":",
"200",
",",
"'pdf'",
":",
"50",
"}",
"formats",... | 30.978261 | 0.00068 |
def get_device(_id):
"""
Pull a device from the API.
"""
url = DEVICE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
... | [
"def",
"get_device",
"(",
"_id",
")",
":",
"url",
"=",
"DEVICE_URL",
"%",
"_id",
"arequest",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"HEADERS",
")",
"status_code",
"=",
"str",
"(",
"arequest",
".",
"status_code",
")",
"if",
"statu... | 30.545455 | 0.00578 |
def pop_events(self):
'''
Pop all events and return a `collections.deque` object. The
returned container can be empty. This method is preferred over
`pop_event()` as it is much faster as the lock has to be acquired
only once and also avoids running into an infinite loop during
event processing.
... | [
"def",
"pop_events",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"events",
"=",
"self",
".",
"events",
"self",
".",
"events",
"=",
"collections",
".",
"deque",
"(",
")",
"return",
"events"
] | 32.538462 | 0.009195 |
def ver(self, revision):
"""Clone and change the version."""
c = self.clone()
c.version = self._parse_version(self.version)
return c | [
"def",
"ver",
"(",
"self",
",",
"revision",
")",
":",
"c",
"=",
"self",
".",
"clone",
"(",
")",
"c",
".",
"version",
"=",
"self",
".",
"_parse_version",
"(",
"self",
".",
"version",
")",
"return",
"c"
] | 20 | 0.011976 |
def sign_execute_deposit(deposit_params, key_pair):
"""
Function to execute the deposit request by signing the transaction generated by the create deposit function.
Execution of this function is as follows::
sign_execute_deposit(deposit_details=create_deposit, key_pair=key_pair)
The expected r... | [
"def",
"sign_execute_deposit",
"(",
"deposit_params",
",",
"key_pair",
")",
":",
"signature",
"=",
"sign_transaction",
"(",
"transaction",
"=",
"deposit_params",
"[",
"'transaction'",
"]",
",",
"private_key_hex",
"=",
"private_key_to_hex",
"(",
"key_pair",
"=",
"key... | 44.590909 | 0.00499 |
def _to_narrow(self, terms, data, mask, dates, assets):
"""
Convert raw computed pipeline results into a DataFrame for public APIs.
Parameters
----------
terms : dict[str -> Term]
Dict mapping column names to terms.
data : dict[str -> ndarray[ndim=2]]
... | [
"def",
"_to_narrow",
"(",
"self",
",",
"terms",
",",
"data",
",",
"mask",
",",
"dates",
",",
"assets",
")",
":",
"if",
"not",
"mask",
".",
"any",
"(",
")",
":",
"# Manually handle the empty DataFrame case. This is a workaround",
"# to pandas failing to tz_localize a... | 40.138462 | 0.000748 |
def get_config(self, section=None):
""" Return the merged end-user configuration for this command or a
specific section if set in `section`. """
config = self.session.config
section = self.config_section() if section is None else section
try:
return config[section]
... | [
"def",
"get_config",
"(",
"self",
",",
"section",
"=",
"None",
")",
":",
"config",
"=",
"self",
".",
"session",
".",
"config",
"section",
"=",
"self",
".",
"config_section",
"(",
")",
"if",
"section",
"is",
"None",
"else",
"section",
"try",
":",
"retur... | 40.8 | 0.004796 |
def from_file(cls, filename):
"""
Reads configuration from given path to a file in local file system and
returns parsed version of it.
:param filename: Path to the YAML file in local file system where the
configuration will be read from.
:type filename: ... | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
")",
":",
"instance",
"=",
"cls",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"as",
"file_stream",
":",
"config_data",
"=",
"yaml",
".",
"load",
"(",
"file_stream",
")",
"instance",
".... | 30.55 | 0.003175 |
def flight_modes(logfile):
'''show flight modes for a log file'''
print("Processing log %s" % filename)
mlog = mavutil.mavlink_connection(filename)
mode = ""
previous_mode = ""
mode_start_timestamp = -1
time_in_mode = {}
previous_percent = -1
seconds_per_percent = -1
filesize =... | [
"def",
"flight_modes",
"(",
"logfile",
")",
":",
"print",
"(",
"\"Processing log %s\"",
"%",
"filename",
")",
"mlog",
"=",
"mavutil",
".",
"mavlink_connection",
"(",
"filename",
")",
"mode",
"=",
"\"\"",
"previous_mode",
"=",
"\"\"",
"mode_start_timestamp",
"=",... | 36.968254 | 0.005019 |
def word_count(text, html=True):
"""
Return the count of words in the given text. If the text is HTML (default True),
tags are stripped before counting. Handles punctuation and bad formatting like.this
when counting words, but assumes conventions for Latin script languages. May not
be reliable for o... | [
"def",
"word_count",
"(",
"text",
",",
"html",
"=",
"True",
")",
":",
"if",
"html",
":",
"text",
"=",
"_tag_re",
".",
"sub",
"(",
"' '",
",",
"text",
")",
"text",
"=",
"_strip_re",
".",
"sub",
"(",
"''",
",",
"text",
")",
"text",
"=",
"_punctuati... | 40.75 | 0.008 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.