text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def highs(self, assets, dt):
"""
The high field's aggregation returns the largest high seen between
the market open and the current dt.
If there has been no data on or before the `dt` the high is `nan`.
Returns
-------
np.array with dtype=float64, in order of ass... | [
"def",
"highs",
"(",
"self",
",",
"assets",
",",
"dt",
")",
":",
"market_open",
",",
"prev_dt",
",",
"dt_value",
",",
"entries",
"=",
"self",
".",
"_prelude",
"(",
"dt",
",",
"'high'",
")",
"highs",
"=",
"[",
"]",
"session_label",
"=",
"self",
".",
... | 39.264706 | 15.029412 |
def update_context(cls, base_context, str_or_dict, template_path=None):
"""Helper method to structure initial message context data.
NOTE: updates `base_context` inplace.
:param dict base_context: context dict to update
:param dict, str str_or_dict: text representing a message, or a dic... | [
"def",
"update_context",
"(",
"cls",
",",
"base_context",
",",
"str_or_dict",
",",
"template_path",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"str_or_dict",
",",
"dict",
")",
":",
"base_context",
".",
"update",
"(",
"str_or_dict",
")",
"base_context",
... | 40.526316 | 20.315789 |
def _find_players(self, boxscore):
"""
Find all players for each team.
Iterate through every player for both teams as found in the boxscore
tables and create a list of instances of the BoxscorePlayer class for
each player. Return lists of player instances comprising the away and... | [
"def",
"_find_players",
"(",
"self",
",",
"boxscore",
")",
":",
"player_dict",
"=",
"{",
"}",
"tables",
"=",
"self",
".",
"_find_boxscore_tables",
"(",
"boxscore",
")",
"for",
"table",
"in",
"tables",
":",
"player_dict",
"=",
"self",
".",
"_extract_player_st... | 37.035714 | 22.392857 |
def set_objective_sense(self, sense):
"""Set type of problem (maximize or minimize)."""
if sense not in (ObjectiveSense.Minimize, ObjectiveSense.Maximize):
raise ValueError('Invalid objective sense')
self._p.ModelSense = self.OBJ_SENSE_MAP[sense] | [
"def",
"set_objective_sense",
"(",
"self",
",",
"sense",
")",
":",
"if",
"sense",
"not",
"in",
"(",
"ObjectiveSense",
".",
"Minimize",
",",
"ObjectiveSense",
".",
"Maximize",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid objective sense'",
")",
"self",
".",
... | 39.714286 | 21 |
def addvPPfunc(self,solution):
'''
Adds the marginal marginal value function to an existing solution, so
that the next solver can evaluate vPP and thus use cubic interpolation.
Parameters
----------
solution : ConsumerSolution
The solution to this single peri... | [
"def",
"addvPPfunc",
"(",
"self",
",",
"solution",
")",
":",
"vPPfuncNow",
"=",
"MargMargValueFunc2D",
"(",
"solution",
".",
"cFunc",
",",
"self",
".",
"CRRA",
")",
"solution",
".",
"vPPfunc",
"=",
"vPPfuncNow",
"return",
"solution"
] | 37 | 24.8 |
def _move_to_desired_location(self):
"""Animate movement to desired location on map."""
self._next_update = 100000
x_start = self._convert_longitude(self._longitude)
y_start = self._convert_latitude(self._latitude)
x_end = self._convert_longitude(self._desired_longitude)
... | [
"def",
"_move_to_desired_location",
"(",
"self",
")",
":",
"self",
".",
"_next_update",
"=",
"100000",
"x_start",
"=",
"self",
".",
"_convert_longitude",
"(",
"self",
".",
"_longitude",
")",
"y_start",
"=",
"self",
".",
"_convert_latitude",
"(",
"self",
".",
... | 54.62963 | 20.851852 |
def add_redirect(self, name, proto, host_ip, host_port, guest_ip, guest_port):
"""Adds a new NAT port-forwarding rule.
in name of type str
The name of the rule. An empty name is acceptable, in which case the NAT engine
auto-generates one using the other parameters.
in p... | [
"def",
"add_redirect",
"(",
"self",
",",
"name",
",",
"proto",
",",
"host_ip",
",",
"host_port",
",",
"guest_ip",
",",
"guest_port",
")",
":",
"if",
"not",
"isinstance",
"(",
"name",
",",
"basestring",
")",
":",
"raise",
"TypeError",
"(",
"\"name can only ... | 48.025 | 25.325 |
def is_url(value, **kwargs):
"""Indicate whether ``value`` is a URL.
.. note::
URL validation is...complicated. The methodology that we have
adopted here is *generally* compliant with
`RFC 1738 <https://tools.ietf.org/html/rfc1738>`_,
`RFC 6761 <https://tools.ietf.org/html/rfc6761>`_,
... | [
"def",
"is_url",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"url",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Exception",
":... | 36.540541 | 25.72973 |
def compute_context_vector(self, prev_state, inputs, precomputed_values=None, mask=None):
"""
Compute the context vector with soft attention.
"""
precomputed_values = precomputed_values if precomputed_values else self.precompute(inputs)
align_weights = self.compute_alignments(pre... | [
"def",
"compute_context_vector",
"(",
"self",
",",
"prev_state",
",",
"inputs",
",",
"precomputed_values",
"=",
"None",
",",
"mask",
"=",
"None",
")",
":",
"precomputed_values",
"=",
"precomputed_values",
"if",
"precomputed_values",
"else",
"self",
".",
"precomput... | 56.5 | 26.5 |
def delete_collection_api_service(self, **kwargs):
"""
delete collection of APIService
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_api_service(async_req=True)
... | [
"def",
"delete_collection_api_service",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"delete_collection_api_service_w... | 167.481481 | 138.740741 |
def _add_membership_multicast_socket(self):
"""
Make membership request to multicast
:rtype: None
"""
self._membership_request = socket.inet_aton(self._multicast_group) \
+ socket.inet_aton(self._multicast_ip)
# Send add membership request to socket
... | [
"def",
"_add_membership_multicast_socket",
"(",
"self",
")",
":",
"self",
".",
"_membership_request",
"=",
"socket",
".",
"inet_aton",
"(",
"self",
".",
"_multicast_group",
")",
"+",
"socket",
".",
"inet_aton",
"(",
"self",
".",
"_multicast_ip",
")",
"# Send add... | 32.647059 | 13.823529 |
def addSubEditor(self, subEditor, isFocusProxy=False):
""" Adds a sub editor to the layout (at the right but before the reset button)
Will add the necessary event filter to handle tabs and sets the strong focus so
that events will not propagate to the tree view.
If isFocusPr... | [
"def",
"addSubEditor",
"(",
"self",
",",
"subEditor",
",",
"isFocusProxy",
"=",
"False",
")",
":",
"self",
".",
"hBoxLayout",
".",
"insertWidget",
"(",
"len",
"(",
"self",
".",
"_subEditors",
")",
",",
"subEditor",
")",
"self",
".",
"_subEditors",
".",
"... | 39.941176 | 21.529412 |
def _set_ignore_delete_all_response(self, v, load=False):
"""
Setter method for ignore_delete_all_response, mapped from YANG variable /vcenter/discovery/ignore_delete_all_response (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ignore_delete_all_response is c... | [
"def",
"_set_ignore_delete_all_response",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v... | 79.5 | 38.666667 |
def _gettables(self):
"""Return a list of hdf5 tables name PyMCsamples.
"""
groups = self._h5file.list_nodes("/")
if len(groups) == 0:
return []
else:
return [
gr.PyMCsamples for gr in groups if gr._v_name[:5] == 'chain'] | [
"def",
"_gettables",
"(",
"self",
")",
":",
"groups",
"=",
"self",
".",
"_h5file",
".",
"list_nodes",
"(",
"\"/\"",
")",
"if",
"len",
"(",
"groups",
")",
"==",
"0",
":",
"return",
"[",
"]",
"else",
":",
"return",
"[",
"gr",
".",
"PyMCsamples",
"for... | 29.3 | 17.9 |
def plot_eigh(self, colorbar=True, cb_orientation='vertical',
tick_interval=[60, 60], minor_tick_interval=[20, 20],
xlabel='Longitude', ylabel='Latitude',
axes_labelsize=9, tick_labelsize=8, show=True, fname=None,
**kwargs):
"""
Plo... | [
"def",
"plot_eigh",
"(",
"self",
",",
"colorbar",
"=",
"True",
",",
"cb_orientation",
"=",
"'vertical'",
",",
"tick_interval",
"=",
"[",
"60",
",",
"60",
"]",
",",
"minor_tick_interval",
"=",
"[",
"20",
",",
"20",
"]",
",",
"xlabel",
"=",
"'Longitude'",
... | 43.435294 | 19.435294 |
def encrypt_with_caching(kms_cmk_arn, max_age_in_cache, cache_capacity):
"""Encrypts a string using an AWS KMS customer master key (CMK) and data key caching.
:param str kms_cmk_arn: Amazon Resource Name (ARN) of the KMS customer master key
:param float max_age_in_cache: Maximum time in seconds that a cach... | [
"def",
"encrypt_with_caching",
"(",
"kms_cmk_arn",
",",
"max_age_in_cache",
",",
"cache_capacity",
")",
":",
"# Data to be encrypted",
"my_data",
"=",
"\"My plaintext data\"",
"# Security thresholds",
"# Max messages (or max bytes per) data key are optional",
"MAX_ENTRY_MESSAGES",
... | 38.538462 | 25.153846 |
def _pop_digits(char_list):
"""Pop consecutive digits from the front of list and return them
Pops any and all consecutive digits from the start of the provided
character list and returns them as a list of string digits.
Operates on (and possibly alters) the passed list.
:param list char_list: a li... | [
"def",
"_pop_digits",
"(",
"char_list",
")",
":",
"logger",
".",
"debug",
"(",
"'_pop_digits(%s)'",
",",
"char_list",
")",
"digits",
"=",
"[",
"]",
"while",
"len",
"(",
"char_list",
")",
"!=",
"0",
"and",
"char_list",
"[",
"0",
"]",
".",
"isdigit",
"("... | 36.444444 | 15.611111 |
def ensure_local_net(
network_name: str = DOCKER_STARCRAFT_NETWORK,
subnet_cidr: str = SUBNET_CIDR
) -> None:
"""
Create docker local net if not found.
:raises docker.errors.APIError
"""
logger.info(f"checking whether docker has network {network_name}")
ipam_pool = docker.types.... | [
"def",
"ensure_local_net",
"(",
"network_name",
":",
"str",
"=",
"DOCKER_STARCRAFT_NETWORK",
",",
"subnet_cidr",
":",
"str",
"=",
"SUBNET_CIDR",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"f\"checking whether docker has network {network_name}\"",
")",
"ipam_p... | 41.833333 | 18.722222 |
def run_with_graph_transformation(self) -> Iterable[BELGraph]:
"""Calculate scores for all leaves until there are none, removes edges until there are, and repeats until
all nodes have been scored. Also, yields the current graph at every step so you can make a cool animation
of how the graph chan... | [
"def",
"run_with_graph_transformation",
"(",
"self",
")",
"->",
"Iterable",
"[",
"BELGraph",
"]",
":",
"yield",
"self",
".",
"get_remaining_graph",
"(",
")",
"while",
"not",
"self",
".",
"done_chomping",
"(",
")",
":",
"while",
"not",
"list",
"(",
"self",
... | 50.142857 | 14.142857 |
def merge(self, dataset):
""" Merge the specified dataset on top of the existing data.
This replaces all values in the existing dataset with the values from the
given dataset.
Args:
dataset (TaskData): A reference to the TaskData object that should be merged
... | [
"def",
"merge",
"(",
"self",
",",
"dataset",
")",
":",
"def",
"merge_data",
"(",
"source",
",",
"dest",
")",
":",
"for",
"key",
",",
"value",
"in",
"source",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"m... | 34.434783 | 17.434783 |
def serialize_options(opts):
"""
A helper method to serialize and processes the options dictionary.
"""
options = (opts or {}).copy()
for key in opts.keys():
if key not in DEFAULT_OPTIONS:
LOG.warning("Unknown option passed to Flask-CORS: %s", key)
# Ensure origins is a li... | [
"def",
"serialize_options",
"(",
"opts",
")",
":",
"options",
"=",
"(",
"opts",
"or",
"{",
"}",
")",
".",
"copy",
"(",
")",
"for",
"key",
"in",
"opts",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"DEFAULT_OPTIONS",
":",
"LOG",
".",
"war... | 38.966667 | 26.433333 |
def log_message(self, format, *args):
"""Log an arbitrary message.
This is used by all other logging functions. Override
it if you have specific logging wishes.
The first argument, FORMAT, is a format string for the
message to be logged. If the format string contains
... | [
"def",
"log_message",
"(",
"self",
",",
"format",
",",
"*",
"args",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s - - [%s] %s\\n\"",
"%",
"(",
"self",
".",
"address_string",
"(",
")",
",",
"self",
".",
"log_date_time_string",
"(",
")",
",",
... | 34 | 18.904762 |
def create_ui(self):
'''
Create UI elements and connect signals.
'''
box = Gtk.Box()
rotate_left = Gtk.Button('Rotate left')
rotate_right = Gtk.Button('Rotate right')
flip_horizontal = Gtk.Button('Flip horizontal')
flip_vertical = Gtk.Button('Flip vertical... | [
"def",
"create_ui",
"(",
"self",
")",
":",
"box",
"=",
"Gtk",
".",
"Box",
"(",
")",
"rotate_left",
"=",
"Gtk",
".",
"Button",
"(",
"'Rotate left'",
")",
"rotate_right",
"=",
"Gtk",
".",
"Button",
"(",
"'Rotate right'",
")",
"flip_horizontal",
"=",
"Gtk",... | 43.512195 | 19.268293 |
def kendalltau_dist(params1, params2=None):
r"""Compute the Kendall tau distance between two models.
This function computes the Kendall tau distance between the rankings
induced by two parameter vectors. Let :math:`\sigma_i` be the rank of item
``i`` in the model described by ``params1``, and :math:`\t... | [
"def",
"kendalltau_dist",
"(",
"params1",
",",
"params2",
"=",
"None",
")",
":",
"assert",
"params2",
"is",
"None",
"or",
"len",
"(",
"params1",
")",
"==",
"len",
"(",
"params2",
")",
"ranks1",
"=",
"rankdata",
"(",
"params1",
",",
"method",
"=",
"\"or... | 36.065217 | 23.391304 |
def coords(self):
"""The (X, Y) coordinates of the tablet tool, in mm from
the top left corner of the tablet in its current logical orientation
and whether they have changed in this event.
Use :meth:`transform_coords` for transforming the axes values into
a different coordinate space.
Note:
On some dev... | [
"def",
"coords",
"(",
"self",
")",
":",
"x_changed",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_x_has_changed",
"(",
"self",
".",
"_handle",
")",
"y_changed",
"=",
"self",
".",
"_libinput",
".",
"libinput_event_tablet_tool_y_has_changed",
"(",
... | 37.416667 | 22.708333 |
def a_connection_timeout(ctx):
"""Check the prompt and update the drivers."""
prompt = ctx.ctrl.after
ctx.msg = "Received the jump host prompt: '{}'".format(prompt)
ctx.device.connected = False
ctx.finished = True
raise ConnectionTimeoutError("Unable to connect to the device.", ctx.ctrl.hostname... | [
"def",
"a_connection_timeout",
"(",
"ctx",
")",
":",
"prompt",
"=",
"ctx",
".",
"ctrl",
".",
"after",
"ctx",
".",
"msg",
"=",
"\"Received the jump host prompt: '{}'\"",
".",
"format",
"(",
"prompt",
")",
"ctx",
".",
"device",
".",
"connected",
"=",
"False",
... | 45 | 17.285714 |
def remove_terms_used_in_less_than_num_docs(self, threshold):
'''
Parameters
----------
threshold: int
Minimum number of documents term should appear in to be kept
Returns
-------
TermDocMatrix, new object with terms removed.
'''
term_... | [
"def",
"remove_terms_used_in_less_than_num_docs",
"(",
"self",
",",
"threshold",
")",
":",
"term_counts",
"=",
"self",
".",
"_X",
".",
"astype",
"(",
"bool",
")",
".",
"astype",
"(",
"int",
")",
".",
"sum",
"(",
"axis",
"=",
"0",
")",
".",
"A",
"[",
... | 34.928571 | 24.928571 |
def _check_file_field(self, field):
"""Check that field exists and is a file field"""
is_field = field in self.field_names
is_file = self.__meta_metadata(field, 'field_type') == 'file'
if not (is_field and is_file):
msg = "'%s' is not a field or not a 'file' field" % field
... | [
"def",
"_check_file_field",
"(",
"self",
",",
"field",
")",
":",
"is_field",
"=",
"field",
"in",
"self",
".",
"field_names",
"is_file",
"=",
"self",
".",
"__meta_metadata",
"(",
"field",
",",
"'field_type'",
")",
"==",
"'file'",
"if",
"not",
"(",
"is_field... | 42.333333 | 13.333333 |
def get_plugins_directory(config_path=None, microdrop_user_root=None):
'''
Resolve plugins directory.
Plugins directory is resolved as follows, highest-priority first:
1. ``plugins`` directory specified in provided :data:`config_path`.
2. ``plugins`` sub-directory of specified MicroDrop profile ... | [
"def",
"get_plugins_directory",
"(",
"config_path",
"=",
"None",
",",
"microdrop_user_root",
"=",
"None",
")",
":",
"RESOLVED_BY_NONE",
"=",
"'default'",
"RESOLVED_BY_CONFIG_ARG",
"=",
"'config_path argument'",
"RESOLVED_BY_PROFILE_ARG",
"=",
"'microdrop_user_root argument'",... | 43.797468 | 21.924051 |
def _process_range_request(self, environ, complete_length=None, accept_ranges=None):
"""Handle Range Request related headers (RFC7233). If `Accept-Ranges`
header is valid, and Range Request is processable, we set the headers
as described by the RFC, and wrap the underlying response in a
... | [
"def",
"_process_range_request",
"(",
"self",
",",
"environ",
",",
"complete_length",
"=",
"None",
",",
"accept_ranges",
"=",
"None",
")",
":",
"from",
".",
".",
"exceptions",
"import",
"RequestedRangeNotSatisfiable",
"if",
"accept_ranges",
"is",
"None",
":",
"r... | 49.428571 | 22.257143 |
def book(symbol=None, token='', version=''):
'''Book shows IEX’s bids and asks for given symbols.
https://iexcloud.io/docs/api/#deep-book
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
dict: result
'''
... | [
"def",
"book",
"(",
"symbol",
"=",
"None",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"if",
"symbol",
":",
"return",
"_getJson",
"(",
"'deep/book?symbols='",
"+",
"symbol",
",",
"token",
",",
"ve... | 27.294118 | 20.117647 |
def FromLegacyResponses(cls, request=None, responses=None):
"""Creates a Responses object from old style flow request and responses."""
res = cls()
res.request = request
if request:
res.request_data = rdf_protodict.Dict(request.data)
dropped_responses = []
# The iterator that was returned ... | [
"def",
"FromLegacyResponses",
"(",
"cls",
",",
"request",
"=",
"None",
",",
"responses",
"=",
"None",
")",
":",
"res",
"=",
"cls",
"(",
")",
"res",
".",
"request",
"=",
"request",
"if",
"request",
":",
"res",
".",
"request_data",
"=",
"rdf_protodict",
... | 37.104167 | 20.46875 |
def get_transition(self, # suppress(too-many-arguments)
line,
line_index,
column,
is_escaped,
comment_system_transitions,
eof=False):
"""Get transition from DisabledParser."... | [
"def",
"get_transition",
"(",
"self",
",",
"# suppress(too-many-arguments)",
"line",
",",
"line_index",
",",
"column",
",",
"is_escaped",
",",
"comment_system_transitions",
",",
"eof",
"=",
"False",
")",
":",
"# If we are at the beginning of a line, to see if we should",
... | 45.196078 | 16.313725 |
def clear_search_defaults(self, args=None):
"""
Clear all search defaults specified by the list of parameter names
given as ``args``. If ``args`` is not given, then clear all existing
search defaults.
Examples::
conn.set_search_defaults(scope=ldap.SCOPE_BASE, attrs... | [
"def",
"clear_search_defaults",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"if",
"args",
"is",
"None",
":",
"self",
".",
"_search_defaults",
".",
"clear",
"(",
")",
"else",
":",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
"in",
"self",
".",
... | 34.666667 | 17.111111 |
def ungap_sequences(records, gap_chars=GAP_TABLE):
"""
Remove gaps from sequences, given an alignment.
"""
logging.info('Applying _ungap_sequences generator: removing all gap characters')
for record in records:
yield ungap_all(record, gap_chars) | [
"def",
"ungap_sequences",
"(",
"records",
",",
"gap_chars",
"=",
"GAP_TABLE",
")",
":",
"logging",
".",
"info",
"(",
"'Applying _ungap_sequences generator: removing all gap characters'",
")",
"for",
"record",
"in",
"records",
":",
"yield",
"ungap_all",
"(",
"record",
... | 38.142857 | 11.571429 |
def iter_modules(self, module=None, filename=None, source=None, excludes=None):
"""
An iterator for the modules that are imported by the specified *module*
or Python source file. The returned #ModuleInfo objects have their
*imported_from* member filled in order to be able to track how a module
was i... | [
"def",
"iter_modules",
"(",
"self",
",",
"module",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"source",
"=",
"None",
",",
"excludes",
"=",
"None",
")",
":",
"if",
"excludes",
"is",
"None",
":",
"excludes",
"=",
"self",
".",
"excludes",
"if",
"no... | 32.232558 | 21.813953 |
def not_storable(_type):
"""
Helper for tagging unserializable types.
Arguments:
_type (type): type to be ignored.
Returns:
Storable: storable instance that does not poke.
"""
return Storable(_type, handlers=StorableHandler(poke=fake_poke, peek=fail_peek(_type))) | [
"def",
"not_storable",
"(",
"_type",
")",
":",
"return",
"Storable",
"(",
"_type",
",",
"handlers",
"=",
"StorableHandler",
"(",
"poke",
"=",
"fake_poke",
",",
"peek",
"=",
"fail_peek",
"(",
"_type",
")",
")",
")"
] | 21.071429 | 24.357143 |
def indexXY(self, index):
"""Coordinates for the test row at *index*
Re-implemented from :meth:`AbstractDragView<sparkle.gui.abstract_drag_view.AbstractDragView.indexXY>`
"""
# just want the top left of row selected
row = index.row()
if row == -1:
row = self.... | [
"def",
"indexXY",
"(",
"self",
",",
"index",
")",
":",
"# just want the top left of row selected",
"row",
"=",
"index",
".",
"row",
"(",
")",
"if",
"row",
"==",
"-",
"1",
":",
"row",
"=",
"self",
".",
"model",
"(",
")",
".",
"rowCount",
"(",
")",
"y"... | 34.727273 | 17.727273 |
def updateAxes(self, maxAxis):
"""Ensures that there are entries for max_axis axes in the menu
(selected by default)."""
if maxAxis > len(self._axisId):
for i in range(len(self._axisId) + 1, maxAxis + 1, 1):
menuId =wx.NewId()
self._axisId.append(menuI... | [
"def",
"updateAxes",
"(",
"self",
",",
"maxAxis",
")",
":",
"if",
"maxAxis",
">",
"len",
"(",
"self",
".",
"_axisId",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_axisId",
")",
"+",
"1",
",",
"maxAxis",
"+",
"1",
",",
"1... | 50 | 10.666667 |
def generate_common_reg_log_config(json_value):
"""Generate common logtail config from loaded json value
:param json_value:
:return:
"""
input_detail = copy.deepcopy(json_value['inputDetail'])
output_detail = json_value['outputDetail']
logSample = json_value.get(... | [
"def",
"generate_common_reg_log_config",
"(",
"json_value",
")",
":",
"input_detail",
"=",
"copy",
".",
"deepcopy",
"(",
"json_value",
"[",
"'inputDetail'",
"]",
")",
"output_detail",
"=",
"json_value",
"[",
"'outputDetail'",
"]",
"logSample",
"=",
"json_value",
"... | 47 | 20.382353 |
def get_search_fields(cls):
"""
Returns search fields in sfdict
"""
sfdict = {}
for klass in tuple(cls.__bases__) + (cls, ):
if hasattr(klass, 'search_fields'):
sfdict.update(klass.search_fields)
return sfdict | [
"def",
"get_search_fields",
"(",
"cls",
")",
":",
"sfdict",
"=",
"{",
"}",
"for",
"klass",
"in",
"tuple",
"(",
"cls",
".",
"__bases__",
")",
"+",
"(",
"cls",
",",
")",
":",
"if",
"hasattr",
"(",
"klass",
",",
"'search_fields'",
")",
":",
"sfdict",
... | 30.777778 | 9.222222 |
def _filter_cluster_data(self):
"""
Filter the cluster data catalog into the filtered_data
catalog, which is what is shown in the H-R diagram.
Filter on the values of the sliders, as well as the lasso
selection in the skyviewer.
"""
min_temp = self.temperature_ra... | [
"def",
"_filter_cluster_data",
"(",
"self",
")",
":",
"min_temp",
"=",
"self",
".",
"temperature_range_slider",
".",
"value",
"[",
"0",
"]",
"max_temp",
"=",
"self",
".",
"temperature_range_slider",
".",
"value",
"[",
"1",
"]",
"temp_mask",
"=",
"np",
".",
... | 38.971429 | 21.771429 |
def _elect_dest_broker(self, victim_partition):
"""Select first under loaded brokers preferring not having
partition of same topic as victim partition.
"""
under_loaded_brokers = sorted(
[
broker
for broker in self._brokers
if (... | [
"def",
"_elect_dest_broker",
"(",
"self",
",",
"victim_partition",
")",
":",
"under_loaded_brokers",
"=",
"sorted",
"(",
"[",
"broker",
"for",
"broker",
"in",
"self",
".",
"_brokers",
"if",
"(",
"victim_partition",
"not",
"in",
"broker",
".",
"partitions",
"an... | 34.555556 | 13.481481 |
def satosa_logging(logger, level, message, state, **kwargs):
"""
Adds a session ID to the message.
:type logger: logging
:type level: int
:type message: str
:type state: satosa.state.State
:param logger: Logger to use
:param level: Logger level (ex: logging.DEBUG/logging.WARN/...)
... | [
"def",
"satosa_logging",
"(",
"logger",
",",
"level",
",",
"message",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"state",
"is",
"None",
":",
"session_id",
"=",
"\"UNKNOWN\"",
"else",
":",
"try",
":",
"session_id",
"=",
"state",
"[",
"LOGGER... | 31.791667 | 17.458333 |
def _add_tc_script(self):
"""
generates tc_script.sh and adds it to included files
"""
# fill context
context = dict(tc_options=self.config.get('tc_options', []))
# import pdb; pdb.set_trace()
contents = self._render_template('tc_script.sh', context)
self.... | [
"def",
"_add_tc_script",
"(",
"self",
")",
":",
"# fill context",
"context",
"=",
"dict",
"(",
"tc_options",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'tc_options'",
",",
"[",
"]",
")",
")",
"# import pdb; pdb.set_trace()",
"contents",
"=",
"self",
".",
... | 37.133333 | 14.466667 |
def from_dict(cls, fields, mapping):
"""
Create a Record from a dictionary of field mappings.
The *fields* object is used to determine the column indices
of fields in the mapping.
Args:
fields: the Relation schema for the table of this record
mapping: a ... | [
"def",
"from_dict",
"(",
"cls",
",",
"fields",
",",
"mapping",
")",
":",
"iterable",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"fields",
")",
"for",
"key",
",",
"value",
"in",
"mapping",
".",
"items",
"(",
")",
":",
"try",
":",
"index",
"=",
"field... | 34.181818 | 15.272727 |
def get_nameid_data(request, key=None):
"""
Gets the NameID Data of the the Logout Request
:param request: Logout Request Message
:type request: string|DOMDocument
:param key: The SP key
:type key: string
:return: Name ID Data (Value, Format, NameQualifier, SPName... | [
"def",
"get_nameid_data",
"(",
"request",
",",
"key",
"=",
"None",
")",
":",
"elem",
"=",
"OneLogin_Saml2_XML",
".",
"to_etree",
"(",
"request",
")",
"name_id",
"=",
"None",
"encrypted_entries",
"=",
"OneLogin_Saml2_XML",
".",
"query",
"(",
"elem",
",",
"'/s... | 40.272727 | 21.636364 |
def combine(self, name_all=None, out_ndx=None, operation='|', defaultgroups=False):
"""Combine individual groups into a single one and write output.
:Keywords:
name_all : string
Name of the combined group, ``None`` generates a name. [``None``]
out_ndx : filename
... | [
"def",
"combine",
"(",
"self",
",",
"name_all",
"=",
"None",
",",
"out_ndx",
"=",
"None",
",",
"operation",
"=",
"'|'",
",",
"defaultgroups",
"=",
"False",
")",
":",
"if",
"not",
"operation",
"in",
"(",
"'|'",
",",
"'&'",
",",
"False",
")",
":",
"r... | 48.367816 | 25.321839 |
def r_num(obj):
"""Read list of numbers."""
if isinstance(obj, (list, tuple)):
it = iter
else:
it = LinesIterator
dataset = Dataset([Dataset.FLOAT])
return dataset.load(it(obj)) | [
"def",
"r_num",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"it",
"=",
"iter",
"else",
":",
"it",
"=",
"LinesIterator",
"dataset",
"=",
"Dataset",
"(",
"[",
"Dataset",
".",
"FLOAT",
"]",
")... | 25.75 | 13.125 |
def fill(self, doc_contents):
""" Fill the content of the document with the information in doc_contents.
This is different from the TextDocument fill function, because this will
check for symbools in the values of `doc_content` and replace them
to good XML codes before filling the templa... | [
"def",
"fill",
"(",
"self",
",",
"doc_contents",
")",
":",
"for",
"key",
",",
"content",
"in",
"doc_contents",
".",
"items",
"(",
")",
":",
"doc_contents",
"[",
"key",
"]",
"=",
"replace_chars_for_svg_code",
"(",
"content",
")",
"return",
"super",
"(",
"... | 38.2 | 23.15 |
def get_traceback_stxt():
"""
Result is (bytes) str type on Python 2 and (unicode) str type on Python 3.
"""
#/
exc_cls, exc_obj, tb_obj = sys.exc_info()
#/
txt_s = traceback.format_exception(exc_cls, exc_obj, tb_obj)
#/
res = ''.join... | [
"def",
"get_traceback_stxt",
"(",
")",
":",
"#/",
"exc_cls",
",",
"exc_obj",
",",
"tb_obj",
"=",
"sys",
".",
"exc_info",
"(",
")",
"#/",
"txt_s",
"=",
"traceback",
".",
"format_exception",
"(",
"exc_cls",
",",
"exc_obj",
",",
"tb_obj",
")",
"#/",
"res",
... | 24.142857 | 23 |
def _update_page_resources(*, page, font, font_key, procset):
"""Update this page's fonts with a reference to the Glyphless font"""
if '/Resources' not in page:
page['/Resources'] = pikepdf.Dictionary({})
resources = page['/Resources']
try:
fonts = resources['/Font']
except KeyError... | [
"def",
"_update_page_resources",
"(",
"*",
",",
"page",
",",
"font",
",",
"font_key",
",",
"procset",
")",
":",
"if",
"'/Resources'",
"not",
"in",
"page",
":",
"page",
"[",
"'/Resources'",
"]",
"=",
"pikepdf",
".",
"Dictionary",
"(",
"{",
"}",
")",
"re... | 37.764706 | 16.882353 |
def expensive_task_gen(num=8700):
r"""
Runs a task that takes some time
Args:
num (int): (default = 8700)
CommandLine:
python -m utool.util_alg expensive_task_gen --show
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_alg import * # NOQA
>>> import utoo... | [
"def",
"expensive_task_gen",
"(",
"num",
"=",
"8700",
")",
":",
"import",
"utool",
"as",
"ut",
"#time_list = []",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"num",
")",
":",
"with",
"ut",
".",
"Timer",
"(",
"verbose",
"=",
"False",
")",
"as",
"t",
"... | 34.466667 | 14.4 |
def weekly_growth(self, weeks):
"""Calculate the weekly growth in percentage, and rounds
to one digit.
Parameters
----------
weeks
Number of weeks to calculate growth over.
Returns
-------
growth_factor
A real number such that... | [
"def",
"weekly_growth",
"(",
"self",
",",
"weeks",
")",
":",
"start",
",",
"end",
"=",
"self",
".",
"start_weight",
",",
"self",
".",
"final_weight",
"growth_factor",
"=",
"(",
"(",
"end",
"/",
"start",
")",
"**",
"(",
"1",
"/",
"weeks",
")",
"-",
... | 27.307692 | 21.115385 |
def auto_init(autofile, force_init=False):
"""
Initialize a repo-specific configuration file to execute dgit
Parameters
----------
autofile: Repo-specific configuration file (dgit.json)
force_init: Flag to force to re-initialization of the configuration file
"""
if os.path.exists(aut... | [
"def",
"auto_init",
"(",
"autofile",
",",
"force_init",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"autofile",
")",
"and",
"not",
"force_init",
":",
"try",
":",
"autooptions",
"=",
"json",
".",
"loads",
"(",
"open",
"(",
"au... | 31.610738 | 18.134228 |
def to_example(dictionary):
"""Helper: build tf.Example from (string -> int/float/str list) dictionary."""
features = {}
for (k, v) in six.iteritems(dictionary):
if not v:
raise ValueError("Empty generated field: %s" % str((k, v)))
if isinstance(v[0], six.integer_types):
features[k] = tf.train... | [
"def",
"to_example",
"(",
"dictionary",
")",
":",
"features",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"dictionary",
")",
":",
"if",
"not",
"v",
":",
"raise",
"ValueError",
"(",
"\"Empty generated field: %s\"",
... | 50.05 | 19.05 |
def env_set(context):
"""Set $ENVs to specified string. from the pypyr context.
Args:
context: is dictionary-like. context is mandatory.
context['env']['set'] must exist. It's a dictionary.
Values are strings to write to $ENV.
Keys are the names of the... | [
"def",
"env_set",
"(",
"context",
")",
":",
"env_set",
"=",
"context",
"[",
"'env'",
"]",
".",
"get",
"(",
"'set'",
",",
"None",
")",
"exists",
"=",
"False",
"if",
"env_set",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"for",
"k",
",",
"v... | 31.022222 | 22.177778 |
def new(self):
# type: () -> None
'''
A method to create a new UDF Logical Volume Implementation Use.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Imple... | [
"def",
"new",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'UDF Logical Volume Implementation Use already initialized'",
")",
"self",
".",
"impl_id",
"=",
"UDFEntityI... | 27.76 | 23.28 |
def route(cls, path):
"""A decorator to indicate that a method should be a routable HTTP endpoint.
.. code-block:: python
from compactor.process import Process
class WebProcess(Process):
@Process.route('/hello/world')
def hello_world(self, handler):
return hand... | [
"def",
"route",
"(",
"cls",
",",
"path",
")",
":",
"if",
"not",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"raise",
"ValueError",
"(",
"'Routes must start with \"/\"'",
")",
"def",
"wrap",
"(",
"fn",
")",
":",
"setattr",
"(",
"fn",
",",
"cls",
... | 27.931034 | 21.965517 |
def c32ToB58(c32string, version=-1):
"""
>>> c32ToB58('SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7')
'1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d'
>>> c32ToB58('SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G')
'3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y'
>>> c32ToB58('ST2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQYAC0RQ')
'mv... | [
"def",
"c32ToB58",
"(",
"c32string",
",",
"version",
"=",
"-",
"1",
")",
":",
"addr_version",
",",
"addr_hash160",
"=",
"c32addressDecode",
"(",
"c32string",
")",
"bitcoin_version",
"=",
"None",
"if",
"version",
"<",
"0",
":",
"bitcoin_version",
"=",
"addr_v... | 41.225806 | 16.193548 |
def get_audits():
"""Get OS hardening Secure TTY audits.
:returns: dictionary of audits
"""
audits = []
audits.append(TemplatedFile('/etc/securetty', SecureTTYContext(),
template_dir=TEMPLATES_DIR,
mode=0o0400, user='root', group='roo... | [
"def",
"get_audits",
"(",
")",
":",
"audits",
"=",
"[",
"]",
"audits",
".",
"append",
"(",
"TemplatedFile",
"(",
"'/etc/securetty'",
",",
"SecureTTYContext",
"(",
")",
",",
"template_dir",
"=",
"TEMPLATES_DIR",
",",
"mode",
"=",
"0o0400",
",",
"user",
"=",... | 33.3 | 19.6 |
def fig_network_input_structure(fig, params, bottom=0.1, top=0.9, transient=200, T=[800, 1000], Df= 0., mlab= True, NFFT=256, srate=1000,
window=plt.mlab.window_hanning, noverlap=256*3/4, letters='abcde', flim=(4, 400),
show_titles=True, show_xlabels=True, show_CSD=False):
'''
This fig... | [
"def",
"fig_network_input_structure",
"(",
"fig",
",",
"params",
",",
"bottom",
"=",
"0.1",
",",
"top",
"=",
"0.9",
",",
"transient",
"=",
"200",
",",
"T",
"=",
"[",
"800",
",",
"1000",
"]",
",",
"Df",
"=",
"0.",
",",
"mlab",
"=",
"True",
",",
"N... | 33.895911 | 21.828996 |
def colorbar(height, length, colormap):
"""Return the channels of a colorbar.
"""
cbar = np.tile(np.arange(length) * 1.0 / (length - 1), (height, 1))
cbar = (cbar * (colormap.values.max() - colormap.values.min())
+ colormap.values.min())
return colormap.colorize(cbar) | [
"def",
"colorbar",
"(",
"height",
",",
"length",
",",
"colormap",
")",
":",
"cbar",
"=",
"np",
".",
"tile",
"(",
"np",
".",
"arange",
"(",
"length",
")",
"*",
"1.0",
"/",
"(",
"length",
"-",
"1",
")",
",",
"(",
"height",
",",
"1",
")",
")",
"... | 36.75 | 13.5 |
def doigrf(lon, lat, alt, date, **kwargs):
"""
Calculates the interpolated (<2015) or extrapolated (>2015) main field and
secular variation coefficients and passes them to the Malin and Barraclough
routine (function pmag.magsyn) to calculate the field from the coefficients.
Parameters:
--------... | [
"def",
"doigrf",
"(",
"lon",
",",
"lat",
",",
"alt",
",",
"date",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
".",
"import",
"coefficients",
"as",
"cf",
"gh",
",",
"sv",
"=",
"[",
"]",
",",
"[",
"]",
"colat",
"=",
"90.",
"-",
"lat",
"#! convert ... | 39.818898 | 18.685039 |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscriptions
``super... | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"in",
"(",
"'add_subscriptions'",
",",
"'remove_subscriptions'",
")",
":",
"return",
"'{0}/{1}'",
".",
"format",
"(",
"super",
"(",
"HostSubscription",
",",
"self",
")",
".",
... | 30.095238 | 16.904762 |
def assign_objective_requisite(self, objective_id, requisite_objective_id):
"""Creates a requirement dependency between two ``Objectives``.
arg: objective_id (osid.id.Id): the ``Id`` of the dependent
``Objective``
arg: requisite_objective_id (osid.id.Id): the ``Id`` of the... | [
"def",
"assign_objective_requisite",
"(",
"self",
",",
"objective_id",
",",
"requisite_objective_id",
")",
":",
"requisite_type",
"=",
"Type",
"(",
"*",
"*",
"Relationship",
"(",
")",
".",
"get_type_data",
"(",
"'OBJECTIVE.REQUISITE'",
")",
")",
"ras",
"=",
"sel... | 51.321429 | 21.035714 |
def _nameFromHeaderInfo(headerInfo, isDecoy, decoyTag):
"""Generates a protein name from headerInfo. If "isDecoy" is True, the
"decoyTag" is added to beginning of the generated protein name.
:param headerInfo: dict, must contain a key "name" or "id"
:param isDecoy: bool, determines if the "decoyTag" is... | [
"def",
"_nameFromHeaderInfo",
"(",
"headerInfo",
",",
"isDecoy",
",",
"decoyTag",
")",
":",
"if",
"'name'",
"in",
"headerInfo",
":",
"proteinName",
"=",
"headerInfo",
"[",
"'name'",
"]",
"else",
":",
"proteinName",
"=",
"headerInfo",
"[",
"'id'",
"]",
"if",
... | 38.411765 | 19.176471 |
async def stream_frames(self, frames="allframes", components=None, on_packet=None):
"""Stream measured frames from QTM until :func:`~qtm.QRTConnection.stream_frames_stop`
is called.
:param frames: Which frames to receive, possible values are 'allframes',
'frequency:n' or 'freque... | [
"async",
"def",
"stream_frames",
"(",
"self",
",",
"frames",
"=",
"\"allframes\"",
",",
"components",
"=",
"None",
",",
"on_packet",
"=",
"None",
")",
":",
"if",
"components",
"is",
"None",
":",
"components",
"=",
"[",
"\"all\"",
"]",
"else",
":",
"_vali... | 41.074074 | 25.111111 |
def _onDeviceStatus(self, client, userdata, pahoMessage):
"""
Internal callback for device status messages, parses source device from topic string and
passes the information on to the registerd device status callback
"""
try:
status = Status(pahoMessage)
s... | [
"def",
"_onDeviceStatus",
"(",
"self",
",",
"client",
",",
"userdata",
",",
"pahoMessage",
")",
":",
"try",
":",
"status",
"=",
"Status",
"(",
"pahoMessage",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Received %s action from %s\"",
"%",
"(",
"status",... | 47.166667 | 16.666667 |
def pipe_tail(context=None, _INPUT=None, conf=None, **kwargs):
"""Returns a specified number of items from the bottom of a feed.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
kwargs -- terminal, if the truncation value is wi... | [
"def",
"pipe_tail",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conf",
"=",
"DotDict",
"(",
"conf",
")",
"limit",
"=",
"conf",
".",
"get",
"(",
"'count'",
",",
"func",
"="... | 29.736842 | 21.315789 |
def write_summary(page, args, ifos, skyError=None, ipn=False, ipnError=False):
"""
Write summary of information to markup.page object page
"""
from pylal import antenna
from lal.gpstime import gps_to_utc, LIGOTimeGPS
gps = args.start_time
grbdate = gps_to_utc(LIGOTimeGPS(gps))\
... | [
"def",
"write_summary",
"(",
"page",
",",
"args",
",",
"ifos",
",",
"skyError",
"=",
"None",
",",
"ipn",
"=",
"False",
",",
"ipnError",
"=",
"False",
")",
":",
"from",
"pylal",
"import",
"antenna",
"from",
"lal",
".",
"gpstime",
"import",
"gps_to_utc",
... | 36.588235 | 18.411765 |
def btc_script_deserialize(script):
"""
Given a script (hex or bin), decode it into its list of opcodes and data.
Return a list of strings and ints.
Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools)
by Vitalik Buterin
"""
if isinstance(script, str) and re.match('... | [
"def",
"btc_script_deserialize",
"(",
"script",
")",
":",
"if",
"isinstance",
"(",
"script",
",",
"str",
")",
"and",
"re",
".",
"match",
"(",
"'^[0-9a-fA-F]*$'",
",",
"script",
")",
":",
"script",
"=",
"binascii",
".",
"unhexlify",
"(",
"script",
")",
"#... | 30.109091 | 20.763636 |
def _representative_structure_setter(self, structprop, keep_chain, clean=True, keep_chemicals=None,
out_suffix='_clean', outdir=None, force_rerun=False):
"""Set the representative structure by 1) cleaning it and 2) copying over attributes of the original structure.
... | [
"def",
"_representative_structure_setter",
"(",
"self",
",",
"structprop",
",",
"keep_chain",
",",
"clean",
"=",
"True",
",",
"keep_chemicals",
"=",
"None",
",",
"out_suffix",
"=",
"'_clean'",
",",
"outdir",
"=",
"None",
",",
"force_rerun",
"=",
"False",
")",
... | 49.542373 | 31.305085 |
def set_writer(self, writer):
"""
Changes the writer function to handle writing to the text edit.
A writer function must have the following prototype:
.. code-block:: python
def write(text_edit, text, color)
:param writer: write function as described above.
... | [
"def",
"set_writer",
"(",
"self",
",",
"writer",
")",
":",
"if",
"self",
".",
"_writer",
"!=",
"writer",
"and",
"self",
".",
"_writer",
":",
"self",
".",
"_writer",
"=",
"None",
"if",
"writer",
":",
"self",
".",
"_writer",
"=",
"writer"
] | 27.9375 | 18.9375 |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
if not HAVE_ST:
raise RuntimeError(
"Trying to run fermipy analysis, but don't have ST")
workdir = os.path.dirname(args.config)
_config_file = self._clone_conf... | [
"def",
"run_analysis",
"(",
"self",
",",
"argv",
")",
":",
"args",
"=",
"self",
".",
"_parser",
".",
"parse_args",
"(",
"argv",
")",
"if",
"not",
"HAVE_ST",
":",
"raise",
"RuntimeError",
"(",
"\"Trying to run fermipy analysis, but don't have ST\"",
")",
"workdir... | 43.137255 | 20.019608 |
def namedb_get_namespace_by_preorder_hash( cur, preorder_hash, include_history=True ):
"""
Get a namespace by its preorder hash (regardless of whether or not it was expired.)
"""
select_query = "SELECT * FROM namespaces WHERE preorder_hash = ?;"
namespace_rows = namedb_query_execute( cur, select_qu... | [
"def",
"namedb_get_namespace_by_preorder_hash",
"(",
"cur",
",",
"preorder_hash",
",",
"include_history",
"=",
"True",
")",
":",
"select_query",
"=",
"\"SELECT * FROM namespaces WHERE preorder_hash = ?;\"",
"namespace_rows",
"=",
"namedb_query_execute",
"(",
"cur",
",",
"se... | 33.590909 | 24.772727 |
def is_stalemate(self) -> bool:
"""Checks if the current position is a stalemate."""
if self.is_check():
return False
if self.is_variant_end():
return False
return not any(self.generate_legal_moves()) | [
"def",
"is_stalemate",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"is_check",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"is_variant_end",
"(",
")",
":",
"return",
"False",
"return",
"not",
"any",
"(",
"self",
".",
"generate_lega... | 27.777778 | 16.888889 |
def join(self):
"""Wait until grid finishes computing."""
self._future = False
self._job.poll()
self._job = None | [
"def",
"join",
"(",
"self",
")",
":",
"self",
".",
"_future",
"=",
"False",
"self",
".",
"_job",
".",
"poll",
"(",
")",
"self",
".",
"_job",
"=",
"None"
] | 28 | 13.8 |
def _get_text(self):
"""
Get the current metadatas
"""
device = self._get_device()
if device is None:
return (UNKNOWN_DEVICE, self.py3.COLOR_BAD)
if not device["isReachable"] or not device["isTrusted"]:
return (
self.py3.safe_forma... | [
"def",
"_get_text",
"(",
"self",
")",
":",
"device",
"=",
"self",
".",
"_get_device",
"(",
")",
"if",
"device",
"is",
"None",
":",
"return",
"(",
"UNKNOWN_DEVICE",
",",
"self",
".",
"py3",
".",
"COLOR_BAD",
")",
"if",
"not",
"device",
"[",
"\"isReachab... | 29.485714 | 17.142857 |
def search_regexp(self):
"""
Define the regexp used for the search
"""
if ((self.season == "") and (self.episode == "")):
# Find serie
try:
print("%s has %s seasons (the serie is %s)" % (self.tvdb.data['seriesname'], self.tvdb.get_season_number(), ... | [
"def",
"search_regexp",
"(",
"self",
")",
":",
"if",
"(",
"(",
"self",
".",
"season",
"==",
"\"\"",
")",
"and",
"(",
"self",
".",
"episode",
"==",
"\"\"",
")",
")",
":",
"# Find serie",
"try",
":",
"print",
"(",
"\"%s has %s seasons (the serie is %s)\"",
... | 48 | 32.296296 |
def _find_frame_imports(name, frame):
"""
Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found.
"""
imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
for import_node in imp... | [
"def",
"_find_frame_imports",
"(",
"name",
",",
"frame",
")",
":",
"imports",
"=",
"frame",
".",
"nodes_of_class",
"(",
"(",
"astroid",
".",
"Import",
",",
"astroid",
".",
"ImportFrom",
")",
")",
"for",
"import_node",
"in",
"imports",
":",
"for",
"import_n... | 40.117647 | 12.352941 |
def read_file(self, container_name, blob_name, **kwargs):
"""
Read a file from Azure Blob Storage and return as a string.
:param container_name: Name of the container.
:type container_name: str
:param blob_name: Name of the blob.
:type blob_name: str
:param kwarg... | [
"def",
"read_file",
"(",
"self",
",",
"container_name",
",",
"blob_name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"connection",
".",
"get_blob_to_text",
"(",
"container_name",
",",
"blob_name",
",",
"*",
"*",
"kwargs",
")",
".",
"content"... | 42.133333 | 15.466667 |
def format(self):
"""PixelFormat: The raw format of the texture. The actual format may differ, but pixel transfers will use this
format.
"""
fmt = ffi.new('Uint32 *')
check_int_err(lib.SDL_QueryTexture(self._ptr, fmt, ffi.NULL, ffi.NULL, ffi.NULL))
return ... | [
"def",
"format",
"(",
"self",
")",
":",
"fmt",
"=",
"ffi",
".",
"new",
"(",
"'Uint32 *'",
")",
"check_int_err",
"(",
"lib",
".",
"SDL_QueryTexture",
"(",
"self",
".",
"_ptr",
",",
"fmt",
",",
"ffi",
".",
"NULL",
",",
"ffi",
".",
"NULL",
",",
"ffi",... | 47.571429 | 13.428571 |
def _fixup_perms2(self, remote_paths, remote_user=None, execute=True):
"""
Mitogen always executes ActionBase helper methods in the context of the
target user account, so it is never necessary to modify permissions
except to ensure the execute bit is set if requested.
"""
... | [
"def",
"_fixup_perms2",
"(",
"self",
",",
"remote_paths",
",",
"remote_user",
"=",
"None",
",",
"execute",
"=",
"True",
")",
":",
"LOG",
".",
"debug",
"(",
"'_fixup_perms2(%r, remote_user=%r, execute=%r)'",
",",
"remote_paths",
",",
"remote_user",
",",
"execute",
... | 55.181818 | 20.454545 |
def _incr_exceptions(self, conn):
"""Increment the number of exceptions for the current connection.
:param psycopg2.extensions.connection conn: the psycopg2 connection
"""
self._pool_manager.get_connection(self.pid, conn).exceptions += 1 | [
"def",
"_incr_exceptions",
"(",
"self",
",",
"conn",
")",
":",
"self",
".",
"_pool_manager",
".",
"get_connection",
"(",
"self",
".",
"pid",
",",
"conn",
")",
".",
"exceptions",
"+=",
"1"
] | 37.857143 | 22.142857 |
def buildProtocol(self, addr):
"""Get a new LLRP client protocol object.
Consult self.antenna_dict to look up antennas to use.
"""
self.resetDelay() # reset reconnection backoff state
clargs = self.client_args.copy()
# optionally configure antennas from self.antenna_di... | [
"def",
"buildProtocol",
"(",
"self",
",",
"addr",
")",
":",
"self",
".",
"resetDelay",
"(",
")",
"# reset reconnection backoff state",
"clargs",
"=",
"self",
".",
"client_args",
".",
"copy",
"(",
")",
"# optionally configure antennas from self.antenna_dict, which looks"... | 41.842105 | 18.684211 |
def cache_clean_handler(min_age_hours=1):
"""This periodically cleans up the ~/.astrobase cache to save us from
disk-space doom.
Parameters
----------
min_age_hours : int
Files older than this number of hours from the current time will be
deleted.
Returns
-------
Noth... | [
"def",
"cache_clean_handler",
"(",
"min_age_hours",
"=",
"1",
")",
":",
"# find the files to delete",
"cmd",
"=",
"(",
"\"find ~ec2-user/.astrobase -type f -mmin +{mmin} -exec rm -v '{{}}' \\;\"",
")",
"mmin",
"=",
"'%.1f'",
"%",
"(",
"min_age_hours",
"*",
"60.0",
")",
... | 26.65625 | 24.65625 |
def abort(self):
"""
Abort a running command.
@return: A new ApiCommand object with the updated information.
"""
if self.id == ApiCommand.SYNCHRONOUS_COMMAND_ID:
return self
path = self._path() + '/abort'
resp = self._get_resource_root().post(path)
return ApiCommand.from_json_dic... | [
"def",
"abort",
"(",
"self",
")",
":",
"if",
"self",
".",
"id",
"==",
"ApiCommand",
".",
"SYNCHRONOUS_COMMAND_ID",
":",
"return",
"self",
"path",
"=",
"self",
".",
"_path",
"(",
")",
"+",
"'/abort'",
"resp",
"=",
"self",
".",
"_get_resource_root",
"(",
... | 28.583333 | 18.25 |
def open_tensorboard(log_dir='/tmp/tensorflow', port=6006):
"""Open Tensorboard.
Parameters
----------
log_dir : str
Directory where your tensorboard logs are saved
port : int
TensorBoard port you want to open, 6006 is tensorboard default
"""
text = "[TL] Open tensorboard, ... | [
"def",
"open_tensorboard",
"(",
"log_dir",
"=",
"'/tmp/tensorflow'",
",",
"port",
"=",
"6006",
")",
":",
"text",
"=",
"\"[TL] Open tensorboard, go to localhost:\"",
"+",
"str",
"(",
"port",
")",
"+",
"\" to access\"",
"text2",
"=",
"\" not yet supported by this functi... | 39.428571 | 24.821429 |
def start_parent():
"""
Start the parent that will simply run the child forever until stopped.
"""
while True:
args = [sys.executable] + sys.argv
new_environ = environ.copy()
new_environ["_IN_CHILD"] = 'yes'
ret = subprocess.call(args, env=new_environ)
if ret !=... | [
"def",
"start_parent",
"(",
")",
":",
"while",
"True",
":",
"args",
"=",
"[",
"sys",
".",
"executable",
"]",
"+",
"sys",
".",
"argv",
"new_environ",
"=",
"environ",
".",
"copy",
"(",
")",
"new_environ",
"[",
"\"_IN_CHILD\"",
"]",
"=",
"'yes'",
"ret",
... | 27.538462 | 15.384615 |
def _get_types_from_sample(result_vars, sparql_results_json):
"""Return types if homogenous within sample
Compare up to 10 rows of results to determine homogeneity.
DESCRIBE and CONSTRUCT queries, for example,
:param result_vars:
:param sparql_results_json:
"""
total_bindings = len(sparql... | [
"def",
"_get_types_from_sample",
"(",
"result_vars",
",",
"sparql_results_json",
")",
":",
"total_bindings",
"=",
"len",
"(",
"sparql_results_json",
"[",
"'results'",
"]",
"[",
"'bindings'",
"]",
")",
"homogeneous_types",
"=",
"{",
"}",
"for",
"result_var",
"in",
... | 37.733333 | 18.466667 |
def wait_for_tasks(self):
"""
Wait for one or more tasks to finish or return empty list if we are done.
Starts new tasks if we have less than task_at_once currently running.
:return: [(Task,object)]: list of (task,result) for finished tasks
"""
finished_tasks_and_results ... | [
"def",
"wait_for_tasks",
"(",
"self",
")",
":",
"finished_tasks_and_results",
"=",
"[",
"]",
"while",
"len",
"(",
"finished_tasks_and_results",
")",
"==",
"0",
":",
"if",
"self",
".",
"is_done",
"(",
")",
":",
"break",
"self",
".",
"start_tasks",
"(",
")",... | 43.357143 | 15.357143 |
def fetchall(self, sql: str, *args) -> Sequence[Sequence[Any]]:
"""Executes SQL; returns all rows, or []."""
self.ensure_db_open()
cursor = self.db.cursor()
self.db_exec_with_cursor(cursor, sql, *args)
try:
rows = cursor.fetchall()
return rows
exce... | [
"def",
"fetchall",
"(",
"self",
",",
"sql",
":",
"str",
",",
"*",
"args",
")",
"->",
"Sequence",
"[",
"Sequence",
"[",
"Any",
"]",
"]",
":",
"self",
".",
"ensure_db_open",
"(",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"self... | 36 | 14 |
def p_end_function(p):
"""
top : top END_FUNCTION
"""
p[0] = p[1]
p[0].append(node.return_stmt(ret=ret_expr))
p[0].append(node.comment_stmt("\nif __name__ == '__main__':\n pass")) | [
"def",
"p_end_function",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"p",
"[",
"0",
"]",
".",
"append",
"(",
"node",
".",
"return_stmt",
"(",
"ret",
"=",
"ret_expr",
")",
")",
"p",
"[",
"0",
"]",
".",
"append",
"(",
"no... | 28.571429 | 14.285714 |
def summarize(text, sent_limit=None, char_limit=None, imp_require=None,
debug=False, **lexrank_params):
'''
Args:
text: text to be summarized (unicode string)
sent_limit: summary length (the number of sentences)
char_limit: summary length (the number of characters)
imp_requ... | [
"def",
"summarize",
"(",
"text",
",",
"sent_limit",
"=",
"None",
",",
"char_limit",
"=",
"None",
",",
"imp_require",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"*",
"*",
"lexrank_params",
")",
":",
"debug_info",
"=",
"{",
"}",
"sentences",
"=",
"lis... | 31.761905 | 20.857143 |
def get_format_extension(fmt):
'''
Returns the recommended extension for a given format
'''
if fmt is None:
return 'dict'
fmt = fmt.lower()
if fmt not in _converter_map:
raise RuntimeError('Unknown basis set format "{}"'.format(fmt))
return _converter_map[fmt]['extension'] | [
"def",
"get_format_extension",
"(",
"fmt",
")",
":",
"if",
"fmt",
"is",
"None",
":",
"return",
"'dict'",
"fmt",
"=",
"fmt",
".",
"lower",
"(",
")",
"if",
"fmt",
"not",
"in",
"_converter_map",
":",
"raise",
"RuntimeError",
"(",
"'Unknown basis set format \"{}... | 23.692308 | 24 |
def set_passport_data_errors(self, user_id, errors):
"""
Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must chan... | [
"def",
"set_passport_data_errors",
"(",
"self",
",",
"user_id",
",",
"errors",
")",
":",
"from",
"pytgbot",
".",
"api_types",
".",
"sendable",
".",
"passport",
"import",
"PassportElementError",
"assert_type_or_raise",
"(",
"user_id",
",",
"int",
",",
"parameter_na... | 49.275 | 36.925 |
def _validate_auths(self, path, obj, app):
""" make sure that apiKey and basicAuth are empty list
in Operation object.
"""
errs = []
for k, v in six.iteritems(obj.authorizations or {}):
if k not in app.raw.authorizations:
errs.append('auth {0} not fou... | [
"def",
"_validate_auths",
"(",
"self",
",",
"path",
",",
"obj",
",",
"app",
")",
":",
"errs",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"obj",
".",
"authorizations",
"or",
"{",
"}",
")",
":",
"if",
"k",
"not",
"in... | 39.285714 | 21.928571 |
def download(self, job_id, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES):
"""
Downloads all screenshots for given job_id to `destination` folder.
If `destination` is None, then screenshots will be saved in current directory.
"""
self._retries_num = 0
... | [
"def",
"download",
"(",
"self",
",",
"job_id",
",",
"destination",
"=",
"None",
",",
"timeout",
"=",
"DEFAULT_TIMEOUT",
",",
"retries",
"=",
"DEFAULT_RETRIES",
")",
":",
"self",
".",
"_retries_num",
"=",
"0",
"sleep",
"(",
"timeout",
")",
"self",
".",
"s... | 46.222222 | 22.222222 |
def fcomplete(text, state):
"""Readline completion function: Filenames"""
text = os.path.expanduser(text)
head, tail = os.path.split(text)
search_dir = os.path.join('.', head)
candidates = [s for s in os.listdir(search_dir) if s.startswith(tail)]
if state >= len(candidates):
return No... | [
"def",
"fcomplete",
"(",
"text",
",",
"state",
")",
":",
"text",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"text",
")",
"head",
",",
"tail",
"=",
"os",
".",
"path",
".",
"split",
"(",
"text",
")",
"search_dir",
"=",
"os",
".",
"path",
".",
... | 27.210526 | 18.315789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.