code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def line(y, thickness, gaussian_width):
distance_from_line = abs(y)
gaussian_y_coord = distance_from_line - thickness/2.0
sigmasq = gaussian_width*gaussian_width
if sigmasq==0.0:
falloff = y*0.0
else:
with float_error_ignore():
falloff = np.exp(np.divide(-gaussian_y_coord*gaussian_y_coord,2*sigmasq))
return np.where(gaussian_y_coord<=0, 1.0, falloff) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier binary_operator identifier float expression_statement assignment identifier binary_operator identifier identifier if_statement comparison_operator identifier float block expression_statement assignment identifier binary_operator identifier float else_clause block with_statement with_clause with_item call identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator unary_operator identifier identifier binary_operator integer identifier return_statement call attribute identifier identifier argument_list comparison_operator identifier integer float identifier | Infinite-length line with a solid central region, then Gaussian fall-off at the edges. |
def add_cat(self, arg=None):
try:
self.done_callback(self.cat)
self.visible = False
except Exception as e:
self.validator.object = ICONS['error']
raise e | module function_definition identifier parameters identifier default_parameter identifier none block try_statement block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier false except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment attribute attribute identifier identifier identifier subscript identifier string string_start string_content string_end raise_statement identifier | Add cat and close panel |
def resolve_extensions(bot: commands.Bot, name: str) -> list:
if name.endswith('.*'):
module_parts = name[:-2].split('.')
path = pathlib.Path(module_parts.pop(0))
for part in module_parts:
path = path / part
return find_extensions_in(path)
if name == '~':
return list(bot.extensions.keys())
return [name] | module function_definition identifier parameters typed_parameter identifier type attribute identifier identifier typed_parameter identifier type identifier type identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute subscript identifier slice unary_operator integer identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer for_statement identifier identifier block expression_statement assignment identifier binary_operator identifier identifier return_statement call identifier argument_list identifier if_statement comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list return_statement list identifier | Tries to resolve extension queries into a list of extension names. |
def upload_gallery_photo(self, gallery_id, source_amigo_id, file_obj,
chunk_size=CHUNK_SIZE, force_chunked=False,
metadata=None):
simple_upload_url = 'related_tables/%s/upload' % gallery_id
chunked_upload_url = 'related_tables/%s/chunked_upload' % gallery_id
data = {'source_amigo_id': source_amigo_id}
if isinstance(file_obj, basestring):
data['filename'] = os.path.basename(file_obj)
else:
data['filename'] = os.path.basename(file_obj.name)
if metadata:
data.update(metadata)
return self.upload_file(simple_upload_url, chunked_upload_url,
file_obj, chunk_size=chunk_size,
force_chunked=force_chunked, extra_data=data) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier identifier default_parameter identifier false default_parameter identifier none block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Upload a photo to a dataset's gallery. |
def foreign(self, value, context=None):
if self.separator is None:
separator = ' '
else:
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = self._clean(value)
try:
value = separator.join(value)
except Exception as e:
raise Concern("{0} caught, failed to convert to string: {1}", e.__class__.__name__, str(e))
return super().foreign(value) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier conditional_expression call attribute attribute identifier identifier identifier argument_list boolean_operator attribute identifier identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier call identifier argument_list identifier return_statement call attribute call identifier argument_list identifier argument_list identifier | Construct a string-like representation for an iterable of string-like objects. |
def chat(self, message):
if message:
action_chat = sc_pb.ActionChat(
channel=sc_pb.ActionChat.Broadcast, message=message)
action = sc_pb.Action(action_chat=action_chat)
return self.act(action) | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier | Send chat message as a broadcast. |
def exit(status=0):
if status == 0:
lab.io.printf(lab.io.Colours.GREEN, "Done.")
else:
lab.io.printf(lab.io.Colours.RED, "Error {0}".format(status))
sys.exit(status) | module function_definition identifier parameters default_parameter identifier integer block if_statement comparison_operator identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier string string_start string_content string_end else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list attribute attribute attribute identifier identifier identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Terminate the program with the given status code. |
def parse_template(self, template, **context):
required_blocks = ["subject", "body"]
optional_blocks = ["text_body", "html_body", "return_path", "format"]
if self.template_context:
context = dict(self.template_context.items() + context.items())
blocks = self.template.render_blocks(template, **context)
for rb in required_blocks:
if rb not in blocks:
raise AttributeError("Template error: block '%s' is missing from '%s'" % (rb, template))
mail_params = {
"subject": blocks["subject"].strip(),
"body": blocks["body"]
}
for ob in optional_blocks:
if ob in blocks:
if ob == "format" and mail_params[ob].lower() not in ["html", "text"]:
continue
mail_params[ob] = blocks[ob]
return mail_params | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier dictionary_splat identifier for_statement identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute subscript identifier string string_start string_content string_end identifier argument_list pair string string_start string_content string_end subscript identifier string string_start string_content string_end for_statement identifier identifier block if_statement comparison_operator identifier identifier block if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator call attribute subscript identifier identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end block continue_statement expression_statement assignment subscript identifier identifier subscript identifier identifier return_statement identifier | To parse a template and return all the blocks |
def validate_geotweet(self, record):
if record and self._validate('user', record) \
and self._validate('coordinates', record):
return True
return False | module function_definition identifier parameters identifier identifier block if_statement boolean_operator boolean_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier line_continuation call attribute identifier identifier argument_list string string_start string_content string_end identifier block return_statement true return_statement false | check that stream record is actual tweet with coordinates |
def _update_name(self):
self._name = self._json_state.get('name')
if not self._name:
self._name = self.type + ' ' + self.device_id | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier binary_operator binary_operator attribute identifier identifier string string_start string_content string_end attribute identifier identifier | Set the device name from _json_state, with a sensible default. |
def _parse_bare_key(self):
key_type = None
dotted = False
self.mark()
while self._current.is_bare_key_char() and self.inc():
pass
key = self.extract()
if self._current == ".":
self.inc()
dotted = True
key += "." + self._parse_key().as_string()
key_type = KeyType.Bare
return Key(key, key_type, "", dotted) | module function_definition identifier parameters identifier block expression_statement assignment identifier none expression_statement assignment identifier false expression_statement call attribute identifier identifier argument_list while_statement boolean_operator call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list block pass_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier true expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement assignment identifier attribute identifier identifier return_statement call identifier argument_list identifier identifier string string_start string_end identifier | Parses a bare key. |
def _set_lastpage(self):
self.last_page = (len(self._page_data) - 1) // self.screen.page_size | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier binary_operator parenthesized_expression binary_operator call identifier argument_list attribute identifier identifier integer attribute attribute identifier identifier identifier | Calculate value of class attribute ``last_page``. |
def next_token(self, tokenum, value, scol):
self.current.set(tokenum, value, scol)
if self.current.tokenum == INDENT and self.current.value:
self.indent_type = self.current.value[0]
if not self.ignore_token():
self.determine_if_whitespace()
self.determine_inside_container()
self.determine_indentation()
if self.forced_insert():
return
if self.inserted_line and self.current.tokenum == NEWLINE:
self.inserted_line = False
if self.result and not self.is_space and self.inserted_line:
if self.current.tokenum != COMMENT:
self.result.append((OP, ';'))
self.inserted_line = False
self.progress()
if self.single and self.single.skipped:
self.single.skipped = False
self.result.append((NEWLINE, '\n'))
self.after_space = self.is_space | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier if_statement boolean_operator comparison_operator attribute attribute identifier identifier identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier subscript attribute attribute identifier identifier identifier integer if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list block return_statement if_statement boolean_operator attribute identifier identifier comparison_operator attribute attribute identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier false if_statement boolean_operator boolean_operator attribute identifier identifier not_operator attribute identifier identifier attribute identifier identifier block if_statement comparison_operator attribute attribute identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list if_statement boolean_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier false expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier string string_start string_content escape_sequence string_end expression_statement assignment attribute identifier identifier attribute identifier identifier | Determine what to do with the next token |
def plot_neff(self, ax, xt_labelsize, titlesize, markersize):
for plotter in self.plotters.values():
for y, ess, color in plotter.ess():
if ess is not None:
ax.plot(
ess,
y,
"o",
color=color,
clip_on=False,
markersize=markersize,
markeredgecolor="k",
)
ax.set_xlim(left=0)
ax.set_title("ess", fontsize=titlesize, wrap=True)
ax.tick_params(labelsize=xt_labelsize)
return ax | module function_definition identifier parameters identifier identifier identifier identifier identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier false keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement identifier | Draw effective n for each plotter. |
def inspect_filter_calculation(self):
try:
node = self.ctx.cif_filter
self.ctx.cif = node.outputs.cif
except exceptions.NotExistent:
self.report('aborting: CifFilterCalculation<{}> did not return the required cif output'.format(node.uuid))
return self.exit_codes.ERROR_CIF_FILTER_FAILED | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier except_clause attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier return_statement attribute attribute identifier identifier identifier | Inspect the result of the CifFilterCalculation, verifying that it produced a CifData output node. |
def for_name(modpath, classname):
module = __import__(modpath, fromlist=[classname])
classobj = getattr(module, classname)
return classobj() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier list identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call identifier argument_list | Returns a class of "classname" from module "modname". |
def decrypt(data, key):
data_len = len(data)
data = ffi.from_buffer(data)
key = ffi.from_buffer(__tobytes(key))
out_len = ffi.new('size_t *')
result = lib.xxtea_decrypt(data, data_len, key, out_len)
ret = ffi.buffer(result, out_len[0])[:]
lib.free(result)
return ret | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier subscript identifier integer slice expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | decrypt the data with the key |
def reenqueue(self, batch):
now = time.time()
batch.attempts += 1
batch.last_attempt = now
batch.last_append = now
batch.set_retry()
assert batch.topic_partition in self._tp_locks, 'TopicPartition not in locks dict'
assert batch.topic_partition in self._batches, 'TopicPartition not in batches'
dq = self._batches[batch.topic_partition]
with self._tp_locks[batch.topic_partition]:
dq.appendleft(batch) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list assert_statement comparison_operator attribute identifier identifier attribute identifier identifier string string_start string_content string_end assert_statement comparison_operator attribute identifier identifier attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier with_statement with_clause with_item subscript attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Re-enqueue the given record batch in the accumulator to retry. |
def list_feeds():
with Database("feeds") as feeds, Database("aliases") as aliases_db:
for feed in feeds:
name = feed
url = feeds[feed]
aliases = []
for k, v in zip(list(aliases_db.keys()), list(aliases_db.values())):
if v == name:
aliases.append(k)
if aliases:
print(name, " : %s Aliases: %s" % (url, aliases))
else:
print(name, " : %s" % url) | module function_definition identifier parameters block with_statement with_clause with_item as_pattern call identifier argument_list string string_start string_content string_end as_pattern_target identifier with_item as_pattern call identifier argument_list string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call identifier argument_list identifier binary_operator string string_start string_content string_end tuple identifier identifier else_clause block expression_statement call identifier argument_list identifier binary_operator string string_start string_content string_end identifier | List all feeds in plain text and give their aliases |
def _format_list(self, data):
dataset = "["
i = 0
for el in data:
if pd.isnull(el):
dataset += "null"
else:
dtype = type(data[i])
if dtype == int or dtype == float:
dataset += str(el)
else:
dataset += '"' + el + '"'
if i < len(data) - 1:
dataset += ', '
dataset += "]"
return dataset | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier integer for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement augmented_assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list subscript identifier identifier if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block expression_statement augmented_assignment identifier call identifier argument_list identifier else_clause block expression_statement augmented_assignment identifier binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end if_statement comparison_operator identifier binary_operator call identifier argument_list identifier integer block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier string string_start string_content string_end return_statement identifier | Format a list to use in javascript |
def isfinite(self):
"Test whether the predicted values are finite"
if self._multiple_outputs:
if self.hy_test is not None:
r = [(hy.isfinite() and (hyt is None or hyt.isfinite()))
for hy, hyt in zip(self.hy, self.hy_test)]
else:
r = [hy.isfinite() for hy in self.hy]
return np.all(r)
return self.hy.isfinite() and (self.hy_test is None or
self.hy_test.isfinite()) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement attribute identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier list_comprehension parenthesized_expression boolean_operator call attribute identifier identifier argument_list parenthesized_expression boolean_operator comparison_operator identifier none call attribute identifier identifier argument_list for_in_clause pattern_list identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier else_clause block expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier return_statement boolean_operator call attribute attribute identifier identifier identifier argument_list parenthesized_expression boolean_operator comparison_operator attribute identifier identifier none call attribute attribute identifier identifier identifier argument_list | Test whether the predicted values are finite |
def fetch_from(self, year: int, month: int):
self.raw_data = []
self.data = []
today = datetime.datetime.today()
for year, month in self._month_year_iter(month, year, today.month, today.year):
self.raw_data.append(self.fetcher.fetch(year, month, self.sid))
self.data.extend(self.raw_data[-1]['data'])
return self.data | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list subscript subscript attribute identifier identifier unary_operator integer string string_start string_content string_end return_statement attribute identifier identifier | Fetch data from year, month to current year month data |
def unicode2str(content):
if isinstance(content, dict):
result = {}
for key in content.keys():
result[unicode2str(key)] = unicode2str(content[key])
return result
elif isinstance(content, list):
return [unicode2str(element) for element in content]
elif isinstance(content, int) or isinstance(content, float):
return content
else:
return content.encode("utf-8") | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier call identifier argument_list identifier call identifier argument_list subscript identifier identifier return_statement identifier elif_clause call identifier argument_list identifier identifier block return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier identifier elif_clause boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block return_statement identifier else_clause block return_statement call attribute identifier identifier argument_list string string_start string_content string_end | Convert the unicode element of the content to str recursively. |
def build_stats(counts):
stats = {
'status': 0,
'reportnum': counts['reportnum'],
'title': counts['title'],
'author': counts['auth_group'],
'url': counts['url'],
'doi': counts['doi'],
'misc': counts['misc'],
}
stats_str = "%(status)s-%(reportnum)s-%(title)s-%(author)s-%(url)s-%(doi)s-%(misc)s" % stats
stats["old_stats_str"] = stats_str
stats["date"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
stats["version"] = version
return stats | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Return stats information from counts structure. |
def _disks_equal(disk1, disk2):
target1 = disk1.find('target')
target2 = disk2.find('target')
source1 = ElementTree.tostring(disk1.find('source')) if disk1.find('source') is not None else None
source2 = ElementTree.tostring(disk2.find('source')) if disk2.find('source') is not None else None
return source1 == source2 and \
target1 is not None and target2 is not None and \
target1.get('bus') == target2.get('bus') and \
disk1.get('device', 'disk') == disk2.get('device', 'disk') and \
target1.get('dev') == target2.get('dev') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end none none expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end none none return_statement boolean_operator boolean_operator boolean_operator boolean_operator boolean_operator comparison_operator identifier identifier line_continuation comparison_operator identifier none comparison_operator identifier none line_continuation comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end line_continuation comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end line_continuation comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end | Test if two disk elements should be considered like the same device |
def find(self, searchText, layers,
contains=True, searchFields="",
sr="", layerDefs="",
returnGeometry=True, maxAllowableOffset="",
geometryPrecision="", dynamicLayers="",
returnZ=False, returnM=False, gdbVersion=""):
url = self._url + "/find"
params = {
"f" : "json",
"searchText" : searchText,
"contains" : self._convert_boolean(contains),
"searchFields": searchFields,
"sr" : sr,
"layerDefs" : layerDefs,
"returnGeometry" : self._convert_boolean(returnGeometry),
"maxAllowableOffset" : maxAllowableOffset,
"geometryPrecision" : geometryPrecision,
"dynamicLayers" : dynamicLayers,
"returnZ" : self._convert_boolean(returnZ),
"returnM" : self._convert_boolean(returnM),
"gdbVersion" : gdbVersion,
"layers" : layers
}
res = self._get(url, params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
qResults = []
for r in res['results']:
qResults.append(Feature(r))
return qResults | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier true default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier false default_parameter identifier false default_parameter identifier string string_start string_end block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier list for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier | performs the map service find operation |
def clone(self, config, **kwargs):
gta = GTAnalysis(config, **kwargs)
gta._roi = copy.deepcopy(self.roi)
return gta | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Make a clone of this analysis instance. |
def rustcall(func, *args):
lib.semaphore_err_clear()
rv = func(*args)
err = lib.semaphore_err_get_last_code()
if not err:
return rv
msg = lib.semaphore_err_get_last_message()
cls = exceptions_by_code.get(err, SemaphoreError)
exc = cls(decode_str(msg))
backtrace = decode_str(lib.semaphore_err_get_backtrace())
if backtrace:
exc.rust_info = backtrace
raise exc | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list list_splat identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator identifier block return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment attribute identifier identifier identifier raise_statement identifier | Calls rust method and does some error handling. |
def unique_(self, col):
try:
df = self.df.drop_duplicates(subset=[col], inplace=False)
return list(df[col])
except Exception as e:
self.err(e, "Can not select unique data") | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier list identifier keyword_argument identifier false return_statement call identifier argument_list subscript identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end | Returns unique values in a column |
def insert(self, resourcetype, source, insert_date=None):
caller = inspect.stack()[1][3]
if caller == 'transaction':
hhclass = 'Layer'
source = resourcetype
resourcetype = resourcetype.csw_schema
else:
hhclass = 'Service'
if resourcetype not in HYPERMAP_SERVICE_TYPES.keys():
raise RuntimeError('Unsupported Service Type')
return self._insert_or_update(resourcetype, source, mode='insert', hhclass=hhclass) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier subscript subscript call attribute identifier identifier argument_list integer integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier identifier expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier call attribute identifier identifier argument_list block raise_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier | Insert a record into the repository |
def load_stock_quantity(self):
info = StocksInfo(self.config)
for stock in self.model.stocks:
stock.quantity = info.load_stock_quantity(stock.symbol)
info.gc_book.close() | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Loads quantities for all stocks |
def peek(self):
try:
self._fetch()
pkt = self.pkt_queue[0]
return pkt
except IndexError:
raise StopIteration() | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier subscript attribute identifier identifier integer return_statement identifier except_clause identifier block raise_statement call identifier argument_list | Get the current packet without consuming it. |
def execute(self, *args, **kwargs):
try:
return self.client.execute(*args, **kwargs)
except requests.exceptions.HTTPError as err:
res = err.response
logger.error("%s response executing GraphQL." % res.status_code)
logger.error(res.text)
self.display_gorilla_error_if_found(res)
six.reraise(*sys.exc_info()) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block return_statement call attribute attribute identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list list_splat call attribute identifier identifier argument_list | Wrapper around execute that logs in cases of failure. |
def _compute_std_0(self, c1, c2, mag):
if mag < 5:
return c1
elif mag >= 5 and mag <= 7:
return c1 + (c2 - c1) * (mag - 5) / 2
else:
return c2 | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier integer block return_statement identifier elif_clause boolean_operator comparison_operator identifier integer comparison_operator identifier integer block return_statement binary_operator identifier binary_operator binary_operator parenthesized_expression binary_operator identifier identifier parenthesized_expression binary_operator identifier integer integer else_clause block return_statement identifier | Common part of equations 27 and 28, pag 82. |
def search_mode_provides(self, product, pipeline='default'):
pipeline = self.pipelines[pipeline]
for obj, mode, field in self.iterate_mode_provides(self.modes, pipeline):
if obj.name() == product:
return ProductEntry(obj.name(), mode.key, field)
else:
raise ValueError('no mode provides %s' % product) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier subscript attribute identifier identifier identifier for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Search the mode that provides a given product |
def scan(self, t, dt=None, aggfunc=None):
return self.data.scan(t, dt, aggfunc) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier | Returns the spectrum from a specific time or range of times. |
def balance(output):
lines = map(pattern.search, output.splitlines())
stack = []
top = []
for item in map(match_to_dict, itertools.takewhile(lambda x: x, lines)):
while stack and item['indent'] <= stack[-1]['indent']:
stack.pop()
if not stack:
stack.append(item)
top.append(item)
else:
item['parent'] = stack[-1]
stack[-1]['children'].append(item)
stack.append(item)
return top | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier call attribute identifier identifier argument_list lambda lambda_parameters identifier identifier identifier block while_statement boolean_operator identifier comparison_operator subscript identifier string string_start string_content string_end subscript subscript identifier unary_operator integer string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier unary_operator integer expression_statement call attribute subscript subscript identifier unary_operator integer string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Convert `ledger balance` output into an hierarchical data structure. |
def setup_cache(app: Flask, cache_config) -> Optional[Cache]:
if cache_config and cache_config.get('CACHE_TYPE') != 'null':
return Cache(app, config=cache_config)
return None | module function_definition identifier parameters typed_parameter identifier type identifier identifier type generic_type identifier type_parameter type identifier block if_statement boolean_operator identifier comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block return_statement call identifier argument_list identifier keyword_argument identifier identifier return_statement none | Setup the flask-cache on a flask app |
def frame(*msgs):
res = io.BytesIO()
for msg in msgs:
res.write(msg)
msg = res.getvalue()
return pack('L', len(msg)) + msg | module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement binary_operator call identifier argument_list string string_start string_content string_end call identifier argument_list identifier identifier | Serialize MSB-first length-prefixed frame. |
def ports(self):
with self._mutex:
if not self._ports:
self._ports = [ports.parse_port(port, self) \
for port in self._obj.get_ports()]
return self._ports | module function_definition identifier parameters identifier block with_statement with_clause with_item attribute identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension call attribute identifier identifier argument_list identifier identifier line_continuation for_in_clause identifier call attribute attribute identifier identifier identifier argument_list return_statement attribute identifier identifier | The list of all ports belonging to this component. |
def deactivate(self, request, queryset):
selected_cats = self.model.objects.filter(
pk__in=[int(x) for x in request.POST.getlist('_selected_action')])
for item in selected_cats:
if item.active:
item.active = False
item.save()
item.children.all().update(active=False) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list keyword_argument identifier false | Set active to False for selected items |
def find_pkg_dist(pkg_name, working_set=None):
working_set = working_set or default_working_set
req = Requirement.parse(pkg_name)
return working_set.find(req) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Locate a package's distribution by its name. |
def _cache_index(self, dbname, collection, index, cache_for):
now = datetime.datetime.utcnow()
expire = datetime.timedelta(seconds=cache_for) + now
with self.__index_cache_lock:
if dbname not in self.__index_cache:
self.__index_cache[dbname] = {}
self.__index_cache[dbname][collection] = {}
self.__index_cache[dbname][collection][index] = expire
elif collection not in self.__index_cache[dbname]:
self.__index_cache[dbname][collection] = {}
self.__index_cache[dbname][collection][index] = expire
else:
self.__index_cache[dbname][collection][index] = expire | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list keyword_argument identifier identifier identifier with_statement with_clause with_item attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier dictionary expression_statement assignment subscript subscript attribute identifier identifier identifier identifier dictionary expression_statement assignment subscript subscript subscript attribute identifier identifier identifier identifier identifier identifier elif_clause comparison_operator identifier subscript attribute identifier identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier identifier identifier dictionary expression_statement assignment subscript subscript subscript attribute identifier identifier identifier identifier identifier identifier else_clause block expression_statement assignment subscript subscript subscript attribute identifier identifier identifier identifier identifier identifier | Add an index to the index cache for ensure_index operations. |
def update_token(self):
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64.b64encode(
(self._key + ':' + self._secret).encode()).decode()
}
data = {'grant_type': 'client_credentials'}
response = requests.post(TOKEN_URL, data=data, headers=headers)
obj = json.loads(response.content.decode('UTF-8'))
self._token = obj['access_token']
self._token_expire_date = (
datetime.now() +
timedelta(minutes=self._expiery)) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end binary_operator string string_start string_content string_end call attribute call attribute identifier identifier argument_list call attribute parenthesized_expression binary_operator binary_operator attribute identifier identifier string string_start string_content string_end attribute identifier identifier identifier argument_list identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier parenthesized_expression binary_operator call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier attribute identifier identifier | Get token from key and secret |
def data(self):
header = struct.pack('>BLB',
4,
self.created,
self.algo_id)
oid = util.prefix_len('>B', self.curve_info['oid'])
blob = self.curve_info['serialize'](self.verifying_key)
return header + oid + blob + self.ecdh_packet | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call subscript attribute identifier identifier string string_start string_content string_end argument_list attribute identifier identifier return_statement binary_operator binary_operator binary_operator identifier identifier identifier attribute identifier identifier | Data for packet creation. |
def _get_binding_info(hostheader='', ipaddress='*', port=80):
ret = r'{0}:{1}:{2}'.format(ipaddress, port, hostheader.replace(' ', ''))
return ret | module function_definition identifier parameters default_parameter identifier string string_start string_end default_parameter identifier string string_start string_content string_end default_parameter identifier integer block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end return_statement identifier | Combine the host header, IP address, and TCP port into bindingInformation format. |
def astensor(array: TensorLike) -> BKTensor:
array = np.asarray(array, dtype=CTYPE)
return array | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Converts a numpy array to the backend's tensor object |
def rdb_repository(_context, name=None, make_default=False,
aggregate_class=None, repository_class=None,
db_string=None, metadata_factory=None):
cnf = {}
if not db_string is None:
cnf['db_string'] = db_string
if not metadata_factory is None:
cnf['metadata_factory'] = metadata_factory
_repository(_context, name, make_default,
aggregate_class, repository_class,
REPOSITORY_TYPES.RDB, 'add_rdb_repository', cnf) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary if_statement not_operator comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement not_operator comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call identifier argument_list identifier identifier identifier identifier identifier attribute identifier identifier string string_start string_content string_end identifier | Directive for registering a RDBM based repository. |
def head(self) -> Any:
lambda_list = self._get_value()
return lambda_list(lambda head, _: head) | module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list lambda lambda_parameters identifier identifier identifier | Retrive first element in List. |
def get(identifier, value=None):
if value is None:
value = identifier
if identifier is None:
return None
elif isinstance(identifier, dict):
try:
return deserialize(identifier)
except ValueError:
return value
elif isinstance(identifier, six.string_types):
config = {'class_name': str(identifier), 'config': {}}
try:
return deserialize(config)
except ValueError:
return value
elif callable(identifier):
return identifier
return value | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier if_statement comparison_operator identifier none block return_statement none elif_clause call identifier argument_list identifier identifier block try_statement block return_statement call identifier argument_list identifier except_clause identifier block return_statement identifier elif_clause call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end call identifier argument_list identifier pair string string_start string_content string_end dictionary try_statement block return_statement call identifier argument_list identifier except_clause identifier block return_statement identifier elif_clause call identifier argument_list identifier block return_statement identifier return_statement identifier | Getter for loading from strings; returns value if can't load. |
def save_ufunc(self, obj):
name = obj.__name__
numpy_tst_mods = ['numpy', 'scipy.special']
for tst_mod_name in numpy_tst_mods:
tst_mod = sys.modules.get(tst_mod_name, None)
if tst_mod and name in tst_mod.__dict__:
return self.save_reduce(_getobject, (tst_mod_name, name))
raise pickle.PicklingError('cannot save %s. Cannot resolve what module it is defined in'
% str(obj)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none if_statement boolean_operator identifier comparison_operator identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier tuple identifier identifier raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier | Hack function for saving numpy ufunc objects |
def create_model(samples_x, samples_y_aggregation,
n_restarts_optimizer=250, is_white_kernel=False):
kernel = gp.kernels.ConstantKernel(constant_value=1,
constant_value_bounds=(1e-12, 1e12)) * \
gp.kernels.Matern(nu=1.5)
if is_white_kernel is True:
kernel += gp.kernels.WhiteKernel(noise_level=1, noise_level_bounds=(1e-12, 1e12))
regressor = gp.GaussianProcessRegressor(kernel=kernel,
n_restarts_optimizer=n_restarts_optimizer,
normalize_y=True,
alpha=1e-10)
regressor.fit(numpy.array(samples_x), numpy.array(samples_y_aggregation))
model = {}
model['model'] = regressor
model['kernel_prior'] = str(kernel)
model['kernel_posterior'] = str(regressor.kernel_)
model['model_loglikelihood'] = regressor.log_marginal_likelihood(regressor.kernel_.theta)
return model | module function_definition identifier parameters identifier identifier default_parameter identifier integer default_parameter identifier false block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier tuple float float line_continuation call attribute attribute identifier identifier identifier argument_list keyword_argument identifier float if_statement comparison_operator identifier true block expression_statement augmented_assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier tuple float float expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier true keyword_argument identifier float expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute attribute identifier identifier identifier return_statement identifier | Trains GP regression model |
def list_pubs(self, buf):
assert not buf.read()
keys = self.conn.parse_public_keys()
code = util.pack('B', msg_code('SSH2_AGENT_IDENTITIES_ANSWER'))
num = util.pack('L', len(keys))
log.debug('available keys: %s', [k['name'] for k in keys])
for i, k in enumerate(keys):
log.debug('%2d) %s', i+1, k['fingerprint'])
pubs = [util.frame(k['blob']) + util.frame(k['name']) for k in keys]
return util.frame(code, num, *pubs) | module function_definition identifier parameters identifier identifier block assert_statement not_operator call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator identifier integer subscript identifier string string_start string_content string_end expression_statement assignment identifier list_comprehension binary_operator call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end for_in_clause identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier list_splat identifier | SSH v2 public keys are serialized and returned. |
def add_item(c, name, item):
if isinstance(item, MenuItem):
if name not in c.items:
c.items[name] = []
c.items[name].append(item)
c.sorted[name] = False | module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier list expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier false | add_item adds MenuItems to the menu identified by 'name' |
def GetGRRVersionString(self):
client_info = self.startup_info.client_info
client_name = client_info.client_description or client_info.client_name
if client_info.client_version > 0:
client_version = str(client_info.client_version)
else:
client_version = _UNKNOWN_GRR_VERSION
return " ".join([client_name, client_version]) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier boolean_operator attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier identifier return_statement call attribute string string_start string_content string_end identifier argument_list list identifier identifier | Returns the client installation-name and GRR version as a string. |
def register_plugins(self):
registered = set()
for plugin_fqdn in chain(self.APP_PLUGINS, self.config["PLUGINS"]):
if plugin_fqdn not in registered:
self.register_plugin(plugin_fqdn)
registered.add(plugin_fqdn) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call identifier argument_list attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Load plugins listed in config variable 'PLUGINS'. |
def remove(self, transport):
if transport.uid in self.transports:
del (self.transports[transport.uid]) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block delete_statement parenthesized_expression subscript attribute identifier identifier attribute identifier identifier | removes a transport if a member of this group |
def pop(self):
root = self.heap[1]
del self.rank[root]
x = self.heap.pop()
if self:
self.heap[1] = x
self.rank[x] = 1
self.down(1)
return root | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier integer delete_statement subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement identifier block expression_statement assignment subscript attribute identifier identifier integer identifier expression_statement assignment subscript attribute identifier identifier identifier integer expression_statement call attribute identifier identifier argument_list integer return_statement identifier | Remove and return smallest element |
def validate_args(args):
if not any([args.environment, args.stage, args.account]):
sys.exit(NO_ACCT_OR_ENV_ERROR)
if args.environment and args.account:
sys.exit(ENV_AND_ACCT_ERROR)
if args.environment and args.role:
sys.exit(ENV_AND_ROLE_ERROR) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list list attribute identifier identifier attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement boolean_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement boolean_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier | Validate command-line arguments. |
def flush(self):
if os.path.isdir(self._directory):
for root, dirs, files in os.walk(self._directory, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name)) | module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier false block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier | Remove all items from the cache. |
def insert_attachments(self, volumeID, attachments):
log.debug("adding new attachments to volume '{}': {}".format(volumeID, attachments))
if not attachments:
return
rawVolume = self._req_raw_volume(volumeID)
attsID = list()
for index, a in enumerate(attachments):
try:
rawAttachment = self._assemble_attachment(a['file'], a)
rawVolume['_source']['_attachments'].append(rawAttachment)
attsID.append(rawAttachment['id'])
except Exception:
log.exception("Error while elaborating attachments array at index: {}".format(index))
raise
self._db.modify_book(volumeID, rawVolume['_source'], version=rawVolume['_version'])
return attsID | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement not_operator identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier expression_statement call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier raise_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end return_statement identifier | add attachments to an already existing volume |
def render_property(property):
if 'type' in property and property['type'] in PROPERTY_FIELDS:
fields = {}
for field in PROPERTY_FIELDS[property['type']]:
if type(field) is tuple:
fields[field[0]] = '(( .properties.{}.{} ))'.format(property['name'], field[1])
else:
fields[field] = '(( .properties.{}.{} ))'.format(property['name'], field)
out = { property['name']: fields }
else:
if property.get('is_reference', False):
out = { property['name']: property['default'] }
else:
out = { property['name']: '(( .properties.{}.value ))'.format(property['name']) }
return out | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier dictionary for_statement identifier subscript identifier subscript identifier string string_start string_content string_end block if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement assignment subscript identifier subscript identifier integer call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end subscript identifier integer else_clause block expression_statement assignment subscript identifier identifier call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier dictionary pair subscript identifier string string_start string_content string_end identifier else_clause block if_statement call attribute identifier identifier argument_list string string_start string_content string_end false block expression_statement assignment identifier dictionary pair subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier dictionary pair subscript identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier | Render a property for bosh manifest, according to its type. |
def load_csv(self):
if path.exists(self.csv_filepath):
self.results = self.results.append(
pandas.read_csv(self.csv_filepath)) | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier | Load old benchmark results from CSV. |
def create(self):
out = helm(
"repo",
"add",
"jupyterhub",
self.helm_repo
)
out = helm("repo", "update")
secret_yaml = self.get_security_yaml()
out = helm(
"upgrade",
"--install",
self.release,
"jupyterhub/jupyterhub",
namespace=self.namespace,
version=self.version,
input=secret_yaml
)
if out.returncode != 0:
print(out.stderr)
else:
print(out.stdout) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end attribute identifier identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement call identifier argument_list attribute identifier identifier else_clause block expression_statement call identifier argument_list attribute identifier identifier | Create a single instance of notebook. |
def commit(self):
self._addFlushBatch()
for core in self.endpoints:
self._send_solr_command(self.endpoints[core], "{ \"commit\":{} }") | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identifier string string_start string_content escape_sequence escape_sequence string_end | Flushes all pending changes and commits Solr changes |
def samples_to_batches(samples: Iterable, batch_size: int):
it = iter(samples)
while True:
with suppress(StopIteration):
batch_in, batch_out = [], []
for i in range(batch_size):
sample_in, sample_out = next(it)
batch_in.append(sample_in)
batch_out.append(sample_out)
if not batch_in:
raise StopIteration
yield np.array(batch_in), np.array(batch_out) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier call identifier argument_list identifier while_statement true block with_statement with_clause with_item call identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier expression_list list list for_statement identifier call identifier argument_list identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator identifier block raise_statement identifier expression_statement yield expression_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier | Chunk a series of network inputs and outputs into larger batches |
def _dump_model(model, attrs=None):
fields = []
for field in model._meta.fields:
fields.append((field.name, str(getattr(model, field.name))))
if attrs is not None:
for attr in attrs:
fields.append((attr, str(getattr(model, attr))))
for field in model._meta.many_to_many:
vals = getattr(model, field.name)
fields.append((field.name, '{val} ({count})'.format(
val=', '.join(map(str, vals.all())),
count=vals.count(),
)))
print(', '.join(
'{0}={1}'.format(field, value)
for field, value in fields
)) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list for_statement identifier attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list tuple attribute identifier identifier call identifier argument_list call identifier argument_list identifier attribute identifier identifier if_statement comparison_operator identifier none block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list tuple identifier call identifier argument_list call identifier argument_list identifier identifier for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list tuple attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier generator_expression call attribute string string_start string_content string_end identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier identifier | Dump the model fields for debugging. |
def total_consumption(self):
if self.use_legacy_protocol:
return 'N/A'
res = 'N/A'
try:
res = self.SOAPAction("GetPMWarningThreshold", "TotalConsumption", self.moduleParameters("2"))
except:
return 'N/A'
if res is None:
return 'N/A'
try:
float(res)
except ValueError:
_LOGGER.error("Failed to retrieve total power consumption from SmartPlug")
return res | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end except_clause block return_statement string string_start string_content string_end if_statement comparison_operator identifier none block return_statement string string_start string_content string_end try_statement block expression_statement call identifier argument_list identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Get the total power consumpuntion in the device lifetime. |
def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment:
"Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`."
x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8))
x = x.view(shape[1], shape[0], -1)
return ImageSegment(x.permute(2,0,1)) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier type identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute call identifier argument_list call identifier argument_list identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer unary_operator integer return_statement call identifier argument_list call attribute identifier identifier argument_list integer integer integer | Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`. |
def isNewerThan(self, other):
if self.getValue("name") == other.getValue("name"):
if other.getValue("version"):
if not other.getValue("version"):
return False
else:
return LooseVersion(self.getValue("version")) > LooseVersion(other.getValue("version"))
else:
return True
else:
return False | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block if_statement not_operator call attribute identifier identifier argument_list string string_start string_content string_end block return_statement false else_clause block return_statement comparison_operator call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end else_clause block return_statement true else_clause block return_statement false | Compare if the version of this app is newer that the other |
def _send_view_change_done_message(self):
new_primary_name = self.provider.next_primary_name()
ledger_summary = self.provider.ledger_summary()
message = ViewChangeDone(self.view_no,
new_primary_name,
ledger_summary)
logger.info("{} is sending ViewChangeDone msg to all : {}".format(self, message))
self.send(message)
self._on_verified_view_change_done_msg(message, self.name) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier | Sends ViewChangeDone message to other protocol participants |
def ask_dir(self):
args ['directory'] = askdirectory(**self.dir_opt)
self.dir_text.set(args ['directory']) | module function_definition identifier parameters identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list dictionary_splat attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end | dialogue box for choosing directory |
def _clean_for_xml(data):
if data:
data = data.encode("ascii", "xmlcharrefreplace").decode("ascii")
return _illegal_xml_chars_re.sub("", data)
return data | module function_definition identifier parameters identifier block if_statement identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list string string_start string_end identifier return_statement identifier | Sanitize any user-submitted data to ensure that it can be used in XML |
def power_status_update(self, POWER_STATUS):
now = time.time()
Vservo = POWER_STATUS.Vservo * 0.001
Vcc = POWER_STATUS.Vcc * 0.001
self.high_servo_voltage = max(self.high_servo_voltage, Vservo)
if self.high_servo_voltage > 1 and Vservo < self.settings.servowarn:
if now - self.last_servo_warn_time > 30:
self.last_servo_warn_time = now
self.say("Servo volt %.1f" % Vservo)
if Vservo < 1:
self.high_servo_voltage = Vservo
if Vcc > 0 and Vcc < self.settings.vccwarn:
if now - self.last_vcc_warn_time > 30:
self.last_vcc_warn_time = now
self.say("Vcc %.1f" % Vcc) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator attribute identifier identifier float expression_statement assignment identifier binary_operator attribute identifier identifier float expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator identifier attribute attribute identifier identifier identifier block if_statement comparison_operator binary_operator identifier attribute identifier identifier integer block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier if_statement comparison_operator identifier integer block expression_statement assignment attribute identifier identifier identifier if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier attribute attribute identifier identifier identifier block if_statement comparison_operator binary_operator identifier attribute identifier identifier integer block expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier | update POWER_STATUS warnings level |
def add(self, modpath, name, origin):
self.map.setdefault(modpath, {}).setdefault(name, set()).add(origin) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier dictionary identifier argument_list identifier call identifier argument_list identifier argument_list identifier | Adds a possible origin for the given name in the given module. |
def parameter_struct_dict(self):
if self._parameter_struct_dict is None:
self._parameter_struct_dict = self._make_ff_params_dict()
elif self.auto_update_f_params:
new_hash = hash(
tuple([tuple(item)
for sublist in self.values()
for item in sublist.values()]))
if self._old_hash != new_hash:
self._parameter_struct_dict = self._make_ff_params_dict()
self._old_hash = new_hash
return self._parameter_struct_dict | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list elif_clause attribute identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier return_statement attribute identifier identifier | Dictionary containing PyAtomData structs for the force field. |
def output_cert(gandi, cert, output_keys, justify=13):
output = list(output_keys)
display_altnames = False
if 'altnames' in output:
display_altnames = True
output.remove('altnames')
display_output = False
if 'cert' in output:
display_output = True
output.remove('cert')
output_generic(gandi, cert, output, justify)
if display_output:
crt = gandi.certificate.pretty_format_cert(cert)
if crt:
output_line(gandi, 'cert', '\n' + crt, justify)
if display_altnames:
for altname in cert['altnames']:
output_line(gandi, 'altname', altname, justify) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier false if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier false if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list identifier identifier identifier identifier if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block expression_statement call identifier argument_list identifier string string_start string_content string_end binary_operator string string_start string_content escape_sequence string_end identifier identifier if_statement identifier block for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier string string_start string_content string_end identifier identifier | Helper to output a certificate information. |
def _config_drag_cols(self, drag_cols):
self._drag_cols = drag_cols
if self._drag_cols:
self._im_drag.paste(self._im_draggable)
else:
self._im_drag.paste(self._im_not_draggable)
self.focus_set()
self.update_idletasks() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Configure a new drag_cols state |
def clean_text(self, domain, **kwargs):
try:
domain = urlparse(domain).hostname or domain
domain = domain.lower()
domain = domain.rsplit(':', 1)[0]
domain = domain.rstrip('.')
domain = domain.encode("idna").decode('ascii')
except ValueError:
return None
if self.validate(domain):
return domain | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier boolean_operator attribute call identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content string_end except_clause identifier block return_statement none if_statement call attribute identifier identifier argument_list identifier block return_statement identifier | Try to extract only the domain bit from the |
def kill_cursor(self, cursor):
text = cursor.selectedText()
if text:
cursor.removeSelectedText()
self.kill(text) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier | Kills the text selected by the give cursor. |
def stop(self):
with self._operational_lock:
self._bidi_rpc.close()
if self._thread is not None:
self.resume()
self._thread.join()
self._thread = None | module function_definition identifier parameters identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none | Stop consuming the stream and shutdown the background thread. |
def require_minimum_pyarrow_version():
minimum_pyarrow_version = "0.12.1"
from distutils.version import LooseVersion
try:
import pyarrow
have_arrow = True
except ImportError:
have_arrow = False
if not have_arrow:
raise ImportError("PyArrow >= %s must be installed; however, "
"it was not found." % minimum_pyarrow_version)
if LooseVersion(pyarrow.__version__) < LooseVersion(minimum_pyarrow_version):
raise ImportError("PyArrow >= %s must be installed; however, "
"your version was %s." % (minimum_pyarrow_version, pyarrow.__version__)) | module function_definition identifier parameters block expression_statement assignment identifier string string_start string_content string_end import_from_statement dotted_name identifier identifier dotted_name identifier try_statement block import_statement dotted_name identifier expression_statement assignment identifier true except_clause identifier block expression_statement assignment identifier false if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier call identifier argument_list identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end tuple identifier attribute identifier identifier | Raise ImportError if minimum version of pyarrow is not installed |
def on_finish(self, exc=None):
super(GarbageCollector, self).on_finish(exc)
self._cycles_left -= 1
if self._cycles_left <= 0:
num_collected = gc.collect()
self._cycles_left = self.collection_cycle
LOGGER.debug('garbage collection run, %d objects evicted',
num_collected) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Used to initiate the garbage collection |
def exception_class(self, exception):
cls = type(exception)
if cls.__module__ == 'exceptions':
return cls.__name__
return "%s.%s" % (cls.__module__, cls.__name__) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement attribute identifier identifier return_statement binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier | Return a name representing the class of an exception. |
async def get_playback_settings(self) -> List[Setting]:
return [
Setting.make(**x)
for x in await self.services["avContent"]["getPlaybackModeSettings"]({})
] | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block return_statement list_comprehension call attribute identifier identifier argument_list dictionary_splat identifier for_in_clause identifier await call subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end argument_list dictionary | Get playback settings such as shuffle and repeat. |
def write (self, data):
self.tmpbuf.append(data)
self.pos += len(data) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier call identifier argument_list identifier | Write data to buffer. |
def dump (env, form):
for var, value in env.items():
log(env, var+"="+value)
for key in form:
log(env, str(formvalue(form, key))) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list identifier binary_operator binary_operator identifier string string_start string_content string_end identifier for_statement identifier identifier block expression_statement call identifier argument_list identifier call identifier argument_list call identifier argument_list identifier identifier | Log environment and form. |
def analysis_question_report(feature, parent):
_ = feature, parent
project_context_scope = QgsExpressionContextUtils.projectScope()
key = provenance_layer_analysis_impacted['provenance_key']
if not project_context_scope.hasVariable(key):
return None
analysis_dir = dirname(project_context_scope.variable(key))
complete_html_report = get_impact_report_as_string(analysis_dir)
requested_html_report = get_report_section(
complete_html_report, component_id=analysis_question_component['key'])
return requested_html_report | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier expression_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement not_operator call attribute identifier identifier argument_list identifier block return_statement none expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier subscript identifier string string_start string_content string_end return_statement identifier | Retrieve the analysis question section from InaSAFE report. |
def _rds_cluster_tags(model, dbs, session_factory, generator, retry):
client = local_session(session_factory).client('rds')
def process_tags(db):
try:
db['Tags'] = retry(
client.list_tags_for_resource,
ResourceName=generator(db[model.id]))['TagList']
return db
except client.exceptions.DBClusterNotFoundFault:
return None
return list(filter(None, map(process_tags, dbs))) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end function_definition identifier parameters identifier block try_statement block expression_statement assignment subscript identifier string string_start string_content string_end subscript call identifier argument_list attribute identifier identifier keyword_argument identifier call identifier argument_list subscript identifier attribute identifier identifier string string_start string_content string_end return_statement identifier except_clause attribute attribute identifier identifier identifier block return_statement none return_statement call identifier argument_list call identifier argument_list none call identifier argument_list identifier identifier | Augment rds clusters with their respective tags. |
def correction(sentence, pos):
"Most probable spelling correction for word."
word = sentence[pos]
cands = candidates(word)
if not cands:
cands = candidates(word, False)
if not cands:
return word
cands = sorted(cands, key=lambda w: P(w, sentence, pos), reverse=True)
cands = [c[0] for c in cands]
return cands | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list identifier false if_statement not_operator identifier block return_statement identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier call identifier argument_list identifier identifier identifier keyword_argument identifier true expression_statement assignment identifier list_comprehension subscript identifier integer for_in_clause identifier identifier return_statement identifier | Most probable spelling correction for word. |
def _node_runner():
env.host_string = lib.get_env_host_string()
node = lib.get_node(env.host_string)
_configure_fabric_for_platform(node.get("platform"))
if __testing__:
print "TEST: would now configure {0}".format(env.host_string)
else:
lib.print_header("Configuring {0}".format(env.host_string))
if env.autodeploy_chef and not chef.chef_test():
deploy_chef(ask="no")
chef.sync_node(node) | module function_definition identifier parameters block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block print_statement call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement boolean_operator attribute identifier identifier not_operator call attribute identifier identifier argument_list block expression_statement call identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | This is only used by node so that we can execute in parallel |
def family_directory(fonts):
if fonts:
dirname = os.path.dirname(fonts[0])
if dirname == '':
dirname = '.'
return dirname | module function_definition identifier parameters identifier block if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript identifier integer if_statement comparison_operator identifier string string_start string_end block expression_statement assignment identifier string string_start string_content string_end return_statement identifier | Get the path of font project directory. |
def reset_small(self, eq):
assert eq in ('f', 'g')
for idx, var in enumerate(self.__dict__[eq]):
if abs(var) <= 1e-12:
self.__dict__[eq][idx] = 0 | module function_definition identifier parameters identifier identifier block assert_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end for_statement pattern_list identifier identifier call identifier argument_list subscript attribute identifier identifier identifier block if_statement comparison_operator call identifier argument_list identifier float block expression_statement assignment subscript subscript attribute identifier identifier identifier identifier integer | Reset numbers smaller than 1e-12 in f and g equations |
def smoothness(self):
energies = self.energies
try:
sp = self.spline()
except:
print("Energy spline failed.")
return None
spline_energies = sp(range(len(energies)))
diff = spline_energies - energies
rms = np.sqrt(np.sum(np.square(diff)) / len(energies))
return rms | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause block expression_statement call identifier argument_list string string_start string_content string_end return_statement none expression_statement assignment identifier call identifier argument_list call identifier argument_list call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier call identifier argument_list identifier return_statement identifier | Get rms average difference between spline and energy trend. |
def send_stdout(cls, sock, payload):
cls.write_chunk(sock, ChunkType.STDOUT, payload) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier identifier | Send the Stdout chunk over the specified socket. |
def implements(obj, protocol):
if isinstance(obj, type):
raise TypeError("First argument to implements must be an instance. "
"Got %r." % obj)
return isinstance(obj, protocol) or issubclass(AnyType, protocol) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier return_statement boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier | Does the object 'obj' implement the 'prococol'? |
def load_from_local(cls):
try:
with open(cls.LOCAL_DB_PATH, 'rb') as f:
b = f.read()
s = security.protege_data(b, False)
except (FileNotFoundError, KeyError):
logging.exception(cls.__name__)
raise StructureError(
"Erreur dans le chargement de la sauvegarde locale !")
else:
return cls(cls.decode_json_str(s)) | module function_definition identifier parameters identifier block try_statement block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier false except_clause tuple identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier raise_statement call identifier argument_list string string_start string_content string_end else_clause block return_statement call identifier argument_list call attribute identifier identifier argument_list identifier | Load datas from local file. |
def pick_monomials_up_to_degree(monomials, degree):
ordered_monomials = []
if degree >= 0:
ordered_monomials.append(S.One)
for deg in range(1, degree + 1):
ordered_monomials.extend(pick_monomials_of_degree(monomials, deg))
return ordered_monomials | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier call identifier argument_list integer binary_operator identifier integer block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier return_statement identifier | Collect monomials up to a given degree. |
def unlock(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
self.object.status = Topic.TOPIC_UNLOCKED
self.object.save()
messages.success(self.request, self.success_message)
return HttpResponseRedirect(success_url) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier return_statement call identifier argument_list identifier | Unlocks the considered topic and retirects the user to the success URL. |
def option_changed(self, option, value):
setattr(self, to_text_string(option), value)
self.shellwidget.set_namespace_view_settings()
if self.setup_in_progress is False:
self.sig_option_changed.emit(option, value) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier call identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier false block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier | Handle when the value of an option has changed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.