code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def GetRendererForValueOrClass(cls, value, limit_lists=-1):
if inspect.isclass(value):
value_cls = value
else:
value_cls = value.__class__
cache_key = "%s_%d" % (value_cls.__name__, limit_lists)
try:
renderer_cls = cls._renderers_cache[cache_key]
except KeyError:
candidates = []
for candidate in itervalues(ApiValueRenderer.classes):
if candidate.value_class:
candidate_class = candidate.value_class
else:
continue
if inspect.isclass(value):
if issubclass(value_cls, candidate_class):
candidates.append((candidate, candidate_class))
else:
if isinstance(value, candidate_class):
candidates.append((candidate, candidate_class))
if not candidates:
raise RuntimeError(
"No renderer found for value %s." % value.__class__.__name__)
candidates = sorted(
candidates, key=lambda candidate: len(candidate[1].mro()))
renderer_cls = candidates[-1][0]
cls._renderers_cache[cache_key] = renderer_cls
return renderer_cls(limit_lists=limit_lists) | module function_definition identifier parameters identifier identifier default_parameter identifier unary_operator integer block if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier try_statement block expression_statement assignment identifier subscript attribute identifier identifier identifier except_clause identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block continue_statement if_statement call attribute identifier identifier argument_list identifier block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier else_clause block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier if_statement not_operator identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier call identifier argument_list call attribute subscript identifier integer identifier argument_list expression_statement assignment identifier subscript subscript identifier unary_operator integer integer expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement call identifier argument_list keyword_argument identifier identifier | Returns renderer corresponding to a given value and rendering args. |
def delete_connector_c_pool(name, target='server', cascade=True, server=None):
data = {'target': target, 'cascade': cascade}
return _delete_element(name, 'resources/connector-connection-pool', data, server) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier true default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier return_statement call identifier argument_list identifier string string_start string_content string_end identifier identifier | Delete a connection pool |
def _register_inet(self, oid=None, conn_or_curs=None):
from psycopg2 import extensions as _ext
if not oid:
oid = 869
_ext.INET = _ext.new_type((oid, ), "INET",
lambda data, cursor: data and Inet(data) or None)
_ext.register_type(_ext.INET, self._con_pg)
return _ext.INET | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block import_from_statement dotted_name identifier aliased_import dotted_name identifier identifier if_statement not_operator identifier block expression_statement assignment identifier integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list tuple identifier string string_start string_content string_end lambda lambda_parameters identifier identifier boolean_operator boolean_operator identifier call identifier argument_list identifier none expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier return_statement attribute identifier identifier | Create the INET type and an Inet adapter. |
def extract_keyhandle(path, filepath):
keyhandle = filepath.lstrip(path)
keyhandle = keyhandle.split("/")
return keyhandle[0] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement subscript identifier integer | extract keyhandle value from the path |
def skip_cycles(self) -> int:
return sum((int(re.sub(r'\D', '', op)) for op in self.skip_tokens)) | module function_definition identifier parameters identifier type identifier block return_statement call identifier argument_list generator_expression call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier for_in_clause identifier attribute identifier identifier | The number of cycles dedicated to skips. |
def rate_limits(self):
if not self._rate_limits:
self._rate_limits = utilities.get_rate_limits(self.response)
return self._rate_limits | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement attribute identifier identifier | Returns a list of rate limit details. |
def move(name, entry_name, config=None):
storm_ = get_storm_instance(config)
try:
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
storm_.clone_entry(name, entry_name, keep_original=False)
print(
get_formatted_message(
'{0} moved in ssh config. you can '
'connect it by typing "ssh {0}".'.format(
entry_name
),
'success')
)
except ValueError as error:
print(get_formatted_message(error, 'error'), file=sys.stderr)
sys.exit(1) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier try_statement block if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier false expression_statement call identifier argument_list call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list call identifier argument_list identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer | Move an entry to the sshconfig. |
def numval(token):
if token.type == 'INTEGER':
return int(token.value)
elif token.type == 'FLOAT':
return float(token.value)
else:
return token.value | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call identifier argument_list attribute identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block return_statement call identifier argument_list attribute identifier identifier else_clause block return_statement attribute identifier identifier | Return the numerical value of token.value if it is a number |
def parse_oxi_states(self, data):
try:
oxi_states = {
data["_atom_type_symbol"][i]:
str2float(data["_atom_type_oxidation_number"][i])
for i in range(len(data["_atom_type_symbol"]))}
for i, symbol in enumerate(data["_atom_type_symbol"]):
oxi_states[re.sub(r"\d?[\+,\-]?$", "", symbol)] = \
str2float(data["_atom_type_oxidation_number"][i])
except (ValueError, KeyError):
oxi_states = None
return oxi_states | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier dictionary_comprehension pair subscript subscript identifier string string_start string_content string_end identifier call identifier argument_list subscript subscript identifier string string_start string_content string_end identifier for_in_clause identifier call identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end for_statement pattern_list identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier line_continuation call identifier argument_list subscript subscript identifier string string_start string_content string_end identifier except_clause tuple identifier identifier block expression_statement assignment identifier none return_statement identifier | Parse oxidation states from data dictionary |
def _get_serv(ret=None):
_options = _get_options(ret)
global REDIS_POOL
if REDIS_POOL:
return REDIS_POOL
elif _options.get('cluster_mode'):
REDIS_POOL = StrictRedisCluster(startup_nodes=_options.get('startup_nodes'),
skip_full_coverage_check=_options.get('skip_full_coverage_check'),
decode_responses=True)
else:
REDIS_POOL = redis.StrictRedis(host=_options.get('host'),
port=_options.get('port'),
unix_socket_path=_options.get('unix_socket_path', None),
db=_options.get('db'),
decode_responses=True,
password=_options.get('password'))
return REDIS_POOL | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier global_statement identifier if_statement identifier block return_statement identifier elif_clause call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end none keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Return a redis server object |
def register_form_factory(Form):
class CsrfDisabledProfileForm(ProfileForm):
def __init__(self, *args, **kwargs):
kwargs = _update_with_csrf_disabled(kwargs)
super(CsrfDisabledProfileForm, self).__init__(*args, **kwargs)
class RegisterForm(Form):
profile = FormField(CsrfDisabledProfileForm, separator='.')
return RegisterForm | module function_definition identifier parameters identifier block class_definition identifier argument_list identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier class_definition identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end return_statement identifier | Factory for creating an extended user registration form. |
def _create_new(self, request):
self.prefix = "{}_Pull_Request_{}".format(request.repo.name, request.pull.number)
head = list(self._newpage_head)
head.append(request.repo.testing.wiki(False))
if not self.testmode:
page = self.site.Pages[self.newpage]
result = page.save('\n'.join(head), summary='Created by CI bot for unit test details.', bot=True)
return result[u'result'] == u'Success'
else:
return '\n'.join(head) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list false if_statement not_operator attribute identifier identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier true return_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end else_clause block return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | Creates the new wiki page that houses the details of the unit testing runs. |
def without_edge(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]':
return BipartiteGraph((e2, v) for e2, v in self._edges.items() if edge != e2) | module function_definition identifier parameters identifier typed_parameter identifier type identifier type string string_start string_content string_end block return_statement call identifier generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list if_clause comparison_operator identifier identifier | Returns a copy of this bipartite graph with the given edge removed. |
def process_request(self, request_object):
entity = request_object.entity_cls.get(request_object.identifier)
resource = entity.update(request_object.data)
return ResponseSuccess(Status.SUCCESS, resource) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement call identifier argument_list attribute identifier identifier identifier | Process Update Resource Request |
def _filter(self, dict, keep):
if not keep:
return dict
result = {}
for key, value in dict.iteritems():
if key in keep:
result[key] = value
return result | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator identifier block return_statement identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier identifier return_statement identifier | Remove any keys not in 'keep' |
def Auth(email=None, password=None):
gd_client = SpreadsheetsService()
gd_client.source = "texastribune-ttspreadimporter-1"
if email is None:
email = os.environ.get('GOOGLE_ACCOUNT_EMAIL')
if password is None:
password = os.environ.get('GOOGLE_ACCOUNT_PASSWORD')
if email and password:
gd_client.ClientLogin(email, password)
return gd_client | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier return_statement identifier | Get a reusable google data client. |
def _process_tokens(self, char):
if (char in self.WHITESPACE or char == self.COMMENT_START or
char in self.QUOTES or char in self.TOKENS):
add_token = True
if char == self.SPACE or char in self.TOKENS:
if self._escaped:
add_token = False
elif char == self.COMMENT_START:
self._state = self.ST_COMMENT
elif char in self.QUOTES:
if self._escaped:
add_token = False
else:
self._state = self.ST_STRING
self._last_quote = char
if add_token:
self._new_token()
if char in self.TOKENS:
self._new_token([char])
return
self._token_chars.append(char) | module function_definition identifier parameters identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier true if_statement boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier false elif_clause comparison_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier elif_clause comparison_operator identifier attribute identifier identifier block if_statement attribute identifier identifier block expression_statement assignment identifier false else_clause block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list list identifier return_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Process a token character. |
def modified_on(self):
timestamp = self._info.get('lastModifiedTime')
return _parser.Parser.parse_timestamp(timestamp) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argument_list identifier | The timestamp for when the table was last modified. |
def play(self):
if self.state == PygAnimation.PLAYING:
pass
elif self.state == PygAnimation.STOPPED:
self.index = 0
self.elapsed = 0
self.playingStartTime = time.time()
self.elapsedStopTime = self.endTimesList[-1]
self.nextElapsedThreshold = self.endTimesList[0]
self.nIterationsLeft = self.nTimes
elif self.state == PygAnimation.PAUSED:
self.playingStartTime = time.time() - self.elapsedAtPause
self.elapsed = self.elapsedAtPause
self.elapsedStopTime = self.endTimesList[-1]
self.nextElapsedThreshold = self.endTimesList[self.index]
self.state = PygAnimation.PLAYING | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block pass_statement elif_clause comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier subscript attribute identifier identifier unary_operator integer expression_statement assignment attribute identifier identifier subscript attribute identifier identifier integer expression_statement assignment attribute identifier identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier binary_operator call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier subscript attribute identifier identifier unary_operator integer expression_statement assignment attribute identifier identifier subscript attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier | Starts an animation playing. |
def tabset(titles, contents):
tabs = []
for no, title in enumerate(titles):
tab = {
'title': title,
}
content = contents[no]
if isinstance(content, list):
tab['items'] = content
else:
tab['items'] = [content]
tabs.append(tab)
result = {
'type': 'tabs',
'tabs': tabs
}
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier subscript identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier else_clause block expression_statement assignment subscript identifier string string_start string_content string_end list identifier expression_statement call attribute identifier identifier argument_list identifier 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 return_statement identifier | A tabbed container widget |
def post_public(self, path, data, is_json=True):
return self._post(path, data, is_json) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier true block return_statement call attribute identifier identifier argument_list identifier identifier identifier | Make a post request requiring no auth. |
def _make_attr_element(parent, attr_i):
attr = etree.SubElement(parent, "attribute")
attr_name = etree.SubElement(attr, 'name')
attr_name.text = attr_i.name
attr_desc = etree.SubElement(attr, 'description')
attr_desc.text = attr_i.description
attr_dimension = etree.SubElement(attr, 'dimension')
attr_dimension.text = units.get_dimension(attr_i.dimension_id, do_accept_dimension_id_none=True).name
return attr | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier attribute call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier true identifier return_statement identifier | create an attribute element from an attribute DB object |
def atlas_peer_dequeue_all( peer_queue=None ):
peers = []
with AtlasPeerQueueLocked(peer_queue) as pq:
while len(pq) > 0:
peers.append( pq.pop(0) )
return peers | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier list with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block while_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer return_statement identifier | Get all queued peers |
def _adjust_probability_vec_best(population, fitnesses, probability_vec,
adjust_rate):
best_solution = max(zip(fitnesses, population))[1]
return _adjust(probability_vec, best_solution, adjust_rate) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript call identifier argument_list call identifier argument_list identifier identifier integer return_statement call identifier argument_list identifier identifier identifier | Shift probabilities towards the best solution. |
def init_with_uid(self, uid):
self._uid = uid
self._brain = None
self._catalog = None
self._instance = None | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none | Initialize with an UID |
def reset(stick):
nulls = (pyhsm.defines.YSM_MAX_PKT_SIZE - 1) * '\x00'
res = YHSM_Cmd(stick, pyhsm.defines.YSM_NULL, payload = nulls).execute(read_response = False)
unlock = stick.acquire()
try:
stick.drain()
stick.flush()
finally:
unlock()
return res == 0 | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator attribute attribute identifier identifier identifier integer string string_start string_content escape_sequence string_end expression_statement assignment identifier call attribute call identifier argument_list identifier attribute attribute identifier identifier identifier keyword_argument identifier identifier identifier argument_list keyword_argument identifier false expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list finally_clause block expression_statement call identifier argument_list return_statement comparison_operator identifier integer | Send a bunch of zero-bytes to the YubiHSM, and flush the input buffer. |
def copy(self):
return Limit(self.scan_limit, self.item_limit, self.min_scan_limit,
self.strict, self.filter) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Return a copy of the limit |
def create(self, filename, filedata):
attributes = {'filename': filename,
'source': filedata}
return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data') | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end | Create a file from raw data |
def word_intersection( word_a, word_b ):
positions = []
word_a_letters = get_letters( word_a )
word_b_letters = get_letters( word_b )
for idx,wa in enumerate(word_a_letters):
for idy,wb in enumerate(word_b_letters):
if ( wa == wb ):
positions.append( (idx, idy) )
return positions | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement parenthesized_expression comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier return_statement identifier | return a list of tuples where word_a, word_b intersect |
def next(self):
if self.s:
self.s -= 1
else:
self.s = self.stride - 1
self.i = (self.i + 1) % self.l
return self.iterables[self.i].next() | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer else_clause block expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier integer expression_statement assignment attribute identifier identifier binary_operator parenthesized_expression binary_operator attribute identifier identifier integer attribute identifier identifier return_statement call attribute subscript attribute identifier identifier attribute identifier identifier identifier argument_list | Returns the next result from the chained iterables given ``"stride"``. |
def process_shell(self, creator, entry, config):
self.logger.info("Processing Bash code: start")
output = []
shell = creator(entry, config)
for line in shell.process():
output.append(line)
self.logger.info(" | %s", line)
if shell.success:
self.logger.info("Processing Bash code: finished")
return {'success': True, 'output': output}
for line in self.run_cleanup(config.env, shell.exit_code):
output.append(line)
self.logger.error("Pipeline has failed: leaving as soon as possible!")
self.event.failed()
return {'success': False, 'output': output} | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list identifier identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement dictionary pair string string_start string_content string_end true pair string string_start string_content string_end identifier for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list return_statement dictionary pair string string_start string_content string_end false pair string string_start string_content string_end identifier | Processing a shell entry. |
def read_and_hash(fname, **kw):
return [addhash(frame, **kw) for frame in read(fname, **kw)]; | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block return_statement list_comprehension call identifier argument_list identifier dictionary_splat identifier for_in_clause identifier call identifier argument_list identifier dictionary_splat identifier | Read and and addhash each frame. |
def clean_super_features(self):
if self.super_features:
self.super_features = [int(sf) for sf in self.super_features
if sf is not None and is_valid_digit(sf)] | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier if_clause boolean_operator comparison_operator identifier none call identifier argument_list identifier | Removes any null & non-integer values from the super feature list |
def Flush(self):
while self._age:
node = self._age.PopLeft()
self.KillObject(node.data)
self._hash = dict() | module function_definition identifier parameters identifier block while_statement attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list | Flush all items from cache. |
def body(self):
for chunk in self.gen_chunks(self.envelope.file_open(self.name)):
yield chunk
for chunk in self.gen_chunks(self.data):
yield chunk
for chunk in self.gen_chunks(self.envelope.file_close()):
yield chunk
for chunk in self.close():
yield chunk | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement yield identifier for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier block expression_statement yield identifier for_statement identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement yield identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement yield identifier | Yields the encoded body. |
def release_address(self, address, vpnid):
query = address + "?action=releaseAddress&vpnId=" + vpnid
request_url = self._build_url(['Lease', query])
return self._do_request('DELETE', request_url) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list list string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Release a specific lease, called after delete_client_entry |
def max_sharpe(self):
if not self.w:
self.solve()
w_sr, sr = [], []
for i in range(len(self.w) - 1):
w0 = np.copy(self.w[i])
w1 = np.copy(self.w[i + 1])
kargs = {"minimum": False, "args": (w0, w1)}
a, b = self.golden_section(self.eval_sr, 0, 1, **kargs)
w_sr.append(a * w0 + (1 - a) * w1)
sr.append(b)
self.weights = w_sr[sr.index(max(sr))].reshape((self.n_assets,))
return dict(zip(self.tickers, self.weights)) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment pattern_list identifier identifier expression_list list list for_statement identifier call identifier argument_list binary_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier binary_operator identifier integer expression_statement assignment identifier dictionary pair string string_start string_content string_end false pair string string_start string_content string_end tuple identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list attribute identifier identifier integer integer dictionary_splat identifier expression_statement call attribute identifier identifier argument_list binary_operator binary_operator identifier identifier binary_operator parenthesized_expression binary_operator integer identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute subscript identifier call attribute identifier identifier argument_list call identifier argument_list identifier identifier argument_list tuple attribute identifier identifier return_statement call identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier | Get the max Sharpe ratio portfolio |
def overlaps(self, canvas, exclude=[]):
try:
exclude = list(exclude)
except TypeError:
exclude = [exclude]
exclude.append(self)
for selfY, row in enumerate(self.image.image()):
for selfX, pixel in enumerate(row):
canvasPixelOn = canvas.testPixel(
(selfX + self.position[0], selfY + self.position[1]),
excludedSprites=exclude
)
if pixel and canvasPixelOn:
return True
return False | module function_definition identifier parameters identifier identifier default_parameter identifier list block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block expression_statement assignment identifier list identifier expression_statement call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple binary_operator identifier subscript attribute identifier identifier integer binary_operator identifier subscript attribute identifier identifier integer keyword_argument identifier identifier if_statement boolean_operator identifier identifier block return_statement true return_statement false | Returns True if sprite is touching any other sprite. |
def status(config):
with open(config) as fh:
config = yaml.safe_load(fh.read())
jsonschema.validate(config, CONFIG_SCHEMA)
last_index = get_incremental_starts(config, None)
accounts = {}
for (a, region), last in last_index.items():
accounts.setdefault(a, {})[region] = last
print(yaml.safe_dump(accounts, default_flow_style=False)) | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier none expression_statement assignment identifier dictionary for_statement pattern_list tuple_pattern identifier identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript call attribute identifier identifier argument_list identifier dictionary identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier false | time series lastest record time by account. |
def uuid(dataset_uri):
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
click.secho(dataset.uuid) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Return the UUID of the dataset. |
def de_blank(val):
ret = list(val)
if type(val) == list:
for idx, item in enumerate(val):
if item.strip() == '':
ret.remove(item)
else:
ret[idx] = item.strip()
return ret | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_end block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list return_statement identifier | Remove blank elements in `val` and return `ret` |
def parse(self, title, pageid=None):
qry = self.PARSE.substitute(
WIKI=self.uri,
ENDPOINT=self.endpoint,
PAGE=safequote(title) or pageid)
if pageid and not title:
qry = qry.replace('&page=', '&pageid=').replace('&redirects', '')
if self.variant:
qry += '&variant=' + self.variant
self.set_status('parse', pageid or title)
return qry | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier boolean_operator call identifier argument_list identifier identifier if_statement boolean_operator identifier not_operator 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 string string_start string_end if_statement attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end boolean_operator identifier identifier return_statement identifier | Returns Mediawiki action=parse query string |
def chunks(iterable, size=1):
iterator = iter(iterable)
for element in iterator:
yield chain([element], islice(iterator, size - 1)) | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement yield call identifier argument_list list identifier call identifier argument_list identifier binary_operator identifier integer | Splits iterator in chunks. |
async def _async_get_data(self, resource, id=None):
if id:
url = urljoin(self._api_url, "spc/{}/{}".format(resource, id))
else:
url = urljoin(self._api_url, "spc/{}".format(resource))
data = await async_request(self._session.get, url)
if not data:
return False
if id and isinstance(data['data'][resource], list):
return data['data'][resource][0]
elif id:
return data['data'][resource]
return [item for item in data['data'][resource]] | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier await call identifier argument_list attribute attribute identifier identifier identifier identifier if_statement not_operator identifier block return_statement false if_statement boolean_operator identifier call identifier argument_list subscript subscript identifier string string_start string_content string_end identifier identifier block return_statement subscript subscript subscript identifier string string_start string_content string_end identifier integer elif_clause identifier block return_statement subscript subscript identifier string string_start string_content string_end identifier return_statement list_comprehension identifier for_in_clause identifier subscript subscript identifier string string_start string_content string_end identifier | Get the data from the resource. |
def add_house(self, complex: str, **kwargs):
self.check_complex(complex)
self.post('developers/{developer}/complexes/{complex}/houses/'.format(developer=self.developer, complex=complex), data=kwargs) | module function_definition identifier parameters identifier typed_parameter identifier type identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Add a new house to the rumetr db |
def add_state(self):
sid = len(self.states)
self.states.append(SFAState(sid)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier | This function adds a new state |
def delete_by_id(self, del_id):
if self.check_post_role()['DELETE']:
pass
else:
return False
if self.is_p:
if MLink.delete(del_id):
output = {'del_link': 1}
else:
output = {'del_link': 0}
return json.dump(output, self)
else:
is_deleted = MLink.delete(del_id)
if is_deleted:
self.redirect('/link/list') | module function_definition identifier parameters identifier identifier block if_statement subscript call attribute identifier identifier argument_list string string_start string_content string_end block pass_statement else_clause block return_statement false if_statement attribute identifier identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end integer else_clause block expression_statement assignment identifier dictionary pair string string_start string_content string_end integer return_statement call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Delete a link by id. |
def alien_filter(name, location, size, unsize):
(fname, flocation, fsize, funsize) = ([] for i in range(4))
for n, l, s, u in zip(name, location, size, unsize):
if "slackbuilds" != l:
fname.append(n)
flocation.append(l)
fsize.append(s)
funsize.append(u)
return [fname, flocation, fsize, funsize] | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment tuple_pattern identifier identifier identifier identifier generator_expression list for_in_clause identifier call identifier argument_list integer for_statement pattern_list identifier identifier identifier identifier call identifier argument_list identifier identifier identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement list identifier identifier identifier identifier | Fix to avoid packages include in slackbuilds folder |
def timeshift(self):
if self.tune and self.tune.get('@src'):
return True if self.tune.get('@src').startswith('timeshift') else False
else:
raise PyMediaroomError("No information in <node> about @src") | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block return_statement conditional_expression true call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list string string_start string_content string_end false else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Return if the stream is a timeshift. |
def destroy(self):
if self._running is False:
return
self._running = False
if hasattr(self, 'schedule'):
del self.schedule
if hasattr(self, 'pub_channel') and self.pub_channel is not None:
self.pub_channel.on_recv(None)
if hasattr(self.pub_channel, 'close'):
self.pub_channel.close()
del self.pub_channel
if hasattr(self, 'periodic_callbacks'):
for cb in six.itervalues(self.periodic_callbacks):
cb.stop() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier false block return_statement expression_statement assignment attribute identifier identifier false if_statement call identifier argument_list identifier string string_start string_content string_end block delete_statement attribute identifier identifier if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator attribute identifier identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list none if_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list delete_statement attribute identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Tear down the minion |
def search_list(kb, from_=None, match_type=None,
page=None, per_page=None, unique=False):
page = page or 1
per_page = per_page or 10
if kb.kbtype == models.KnwKB.KNWKB_TYPES['written_as']:
query = api.query_kb_mappings(
kbid=kb.id,
key=from_ or '',
match_type=match_type or 's'
).with_entities(models.KnwKBRVAL.m_key)
if unique:
query = query.distinct()
return [item.m_key for item in
pagination.RestfulSQLAlchemyPagination(
query, page=page or 1,
per_page=per_page or 10
).items]
return [] | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier false block expression_statement assignment identifier boolean_operator identifier integer expression_statement assignment identifier boolean_operator identifier integer if_statement comparison_operator attribute identifier identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier boolean_operator identifier string string_start string_end keyword_argument identifier boolean_operator identifier string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement list_comprehension attribute identifier identifier for_in_clause identifier attribute call attribute identifier identifier argument_list identifier keyword_argument identifier boolean_operator identifier integer keyword_argument identifier boolean_operator identifier integer identifier return_statement list | Search "mapping from" for knowledge. |
def single_frame_plot(obj):
obj = Layout.from_values(obj) if isinstance(obj, AdjointLayout) else obj
backend = Store.current_backend
renderer = Store.renderers[backend]
plot_cls = renderer.plotting_class(obj)
plot = plot_cls(obj, **renderer.plot_options(obj, renderer.size))
fmt = renderer.params('fig').objects[0] if renderer.fig == 'auto' else renderer.fig
return plot, renderer, fmt | module function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier dictionary_splat call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier conditional_expression subscript attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier integer comparison_operator attribute identifier identifier string string_start string_content string_end attribute identifier identifier return_statement expression_list identifier identifier identifier | Returns plot, renderer and format for single frame export. |
def update_widget_attrs(self, bound_field, attrs):
if bound_field.field.has_subwidgets() is False:
widget_classes = getattr(self, 'widget_css_classes', None)
if widget_classes:
if 'class' in attrs:
attrs['class'] += ' ' + widget_classes
else:
attrs.update({'class': widget_classes})
return attrs | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list false block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement augmented_assignment subscript identifier string string_start string_content string_end binary_operator string string_start string_content string_end identifier else_clause block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier return_statement identifier | Updated the widget attributes which shall be added to the widget when rendering this field. |
def message(self, category, subject, msg_file):
users = getattr(self.sub, category)
if not users:
print('There are no {} users on {}.'.format(category, self.sub))
return
if msg_file:
try:
msg = open(msg_file).read()
except IOError as error:
print(str(error))
return
else:
print('Enter message:')
msg = sys.stdin.read()
print('You are about to send the following message to the users {}:'
.format(', '.join([str(x) for x in users])))
print('---BEGIN MESSAGE---\n{}\n---END MESSAGE---'.format(msg))
if input('Are you sure? yes/[no]: ').lower() not in ['y', 'yes']:
print('Message sending aborted.')
return
for user in users:
user.send_message(subject, msg)
print('Sent to: {}'.format(user)) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier if_statement not_operator identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier attribute identifier identifier return_statement if_statement identifier block try_statement block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list call identifier argument_list identifier return_statement else_clause block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier if_statement comparison_operator call attribute call identifier argument_list string string_start string_content string_end identifier argument_list list string string_start string_content string_end string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content string_end return_statement for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Send message to all users in `category`. |
def _update_conda_packages():
conda_bin = _get_conda_bin()
channels = _get_conda_channels(conda_bin)
assert conda_bin, ("Could not find anaconda distribution for upgrading bcbio.\n"
"Using python at %s but could not find conda." % (os.path.realpath(sys.executable)))
req_file = "bcbio-update-requirements.txt"
if os.path.exists(req_file):
os.remove(req_file)
subprocess.check_call(["wget", "-O", req_file, "--no-check-certificate", REMOTES["requirements"]])
subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] + channels +
["--file", req_file])
if os.path.exists(req_file):
os.remove(req_file)
return os.path.dirname(os.path.dirname(conda_bin)) | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier assert_statement identifier parenthesized_expression binary_operator concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end parenthesized_expression call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator binary_operator list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier list string string_start string_content string_end identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier | If installed in an anaconda directory, upgrade conda packages. |
def one_cycle_scheduler(lr_max:float, **kwargs:Any)->OneCycleScheduler:
"Instantiate a `OneCycleScheduler` with `lr_max`."
return partial(OneCycleScheduler, lr_max=lr_max, **kwargs) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter dictionary_splat_pattern identifier type identifier type identifier block expression_statement string string_start string_content string_end return_statement call identifier argument_list identifier keyword_argument identifier identifier dictionary_splat identifier | Instantiate a `OneCycleScheduler` with `lr_max`. |
def _no_duplicates_constructor(loader, node, deep=False):
mapping = {}
for key_node, value_node in node.value:
key = loader.construct_object(key_node, deep=deep)
value = loader.construct_object(value_node, deep=deep)
if key in mapping:
raise ConstructorError("while constructing a mapping",
node.start_mark,
"found duplicate key (%s)" % key,
key_node.start_mark)
mapping[key] = value
return loader.construct_mapping(node, deep) | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end identifier attribute identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier | Check for duplicate keys. |
def com_google_fonts_check_fvar_name_entries(ttFont):
failed = False
for instance in ttFont["fvar"].instances:
entries = [entry for entry in ttFont["name"].names if entry.nameID == instance.subfamilyNameID]
if len(entries) == 0:
failed = True
yield FAIL, (f"Named instance with coordinates {instance.coordinates}"
f" lacks an entry on the name table (nameID={instance.subfamilyNameID}).")
if not failed:
yield PASS, "OK" | module function_definition identifier parameters identifier block expression_statement assignment identifier false for_statement identifier attribute subscript identifier string string_start string_content string_end identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute subscript identifier string string_start string_content string_end identifier if_clause comparison_operator attribute identifier identifier attribute identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier true expression_statement yield expression_list identifier parenthesized_expression concatenated_string string string_start string_content interpolation attribute identifier identifier string_end string string_start string_content interpolation attribute identifier identifier string_content string_end if_statement not_operator identifier block expression_statement yield expression_list identifier string string_start string_content string_end | All name entries referenced by fvar instances exist on the name table? |
def MySend(request_path, payload=None,
content_type="application/octet-stream",
timeout=None, force_auth=True,
**kwargs):
try:
return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs)
except Exception, e:
if type(e) != urllib2.HTTPError or e.code != 500:
raise
print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds."
time.sleep(2)
return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier true dictionary_splat_pattern identifier block try_statement block return_statement call identifier argument_list identifier identifier identifier identifier identifier dictionary_splat identifier except_clause identifier identifier block if_statement boolean_operator comparison_operator call identifier argument_list identifier attribute identifier identifier comparison_operator attribute identifier identifier integer block raise_statement print_statement chevron attribute identifier identifier binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer return_statement call identifier argument_list identifier identifier identifier identifier identifier dictionary_splat identifier | Run MySend1 maybe twice, because Rietveld is unreliable. |
def step_indices(group_idx):
ilen = step_count(group_idx) + 1
indices = np.empty(ilen, np.int64)
indices[0] = 0
indices[-1] = group_idx.size
cmp_pos = 0
ri = 1
for i in range(len(group_idx)):
if group_idx[cmp_pos] != group_idx[i]:
cmp_pos = i
indices[ri] = i
ri += 1
return indices | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment subscript identifier integer integer expression_statement assignment subscript identifier unary_operator integer attribute identifier identifier expression_statement assignment identifier integer expression_statement assignment identifier integer for_statement identifier call identifier argument_list call identifier argument_list identifier block if_statement comparison_operator subscript identifier identifier subscript identifier identifier block expression_statement assignment identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement augmented_assignment identifier integer return_statement identifier | Return the edges of areas within group_idx, which are filled with the same value. |
def blob_counter(self):
import aa
from ROOT import EventFile
try:
event_file = EventFile(self.filename)
except Exception:
raise SystemExit("Could not open file")
num_blobs = 0
for event in event_file:
num_blobs += 1
return num_blobs | module function_definition identifier parameters identifier block import_statement dotted_name identifier import_from_statement dotted_name identifier dotted_name identifier try_statement block expression_statement assignment identifier call identifier argument_list attribute identifier identifier except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier integer for_statement identifier identifier block expression_statement augmented_assignment identifier integer return_statement identifier | Create a blob counter. |
def cli(obj):
client = obj['client']
timezone = obj['timezone']
screen = Screen(client, timezone)
screen.run() | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list | Display alerts like unix "top" command. |
def unescape_all(string):
def escape_single(matchobj):
return _unicode_for_entity_with_name(matchobj.group(1))
return entities.sub(escape_single, string) | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list integer return_statement call attribute identifier identifier argument_list identifier identifier | Resolve all html entities to their corresponding unicode character |
def network_size(value, options=None, version=None):
ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
if not ipaddr_filter_out:
return
if not isinstance(value, (list, tuple, types.GeneratorType)):
return _network_size(ipaddr_filter_out[0])
return [
_network_size(ip_a)
for ip_a in ipaddr_filter_out
] | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement not_operator identifier block return_statement if_statement not_operator call identifier argument_list identifier tuple identifier identifier attribute identifier identifier block return_statement call identifier argument_list subscript identifier integer return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier identifier | Get the size of a network. |
def _check_reach_env():
path_to_reach = get_config('REACHPATH')
if path_to_reach is None:
path_to_reach = environ.get('REACHPATH', None)
if path_to_reach is None or not path.exists(path_to_reach):
raise ReachError(
'Reach path unset or invalid. Check REACHPATH environment var '
'and/or config file.'
)
logger.debug('Using REACH jar at: %s' % path_to_reach)
reach_version = get_config('REACH_VERSION')
if reach_version is None:
reach_version = environ.get('REACH_VERSION', None)
if reach_version is None:
logger.debug('REACH version not set in REACH_VERSION')
m = re.match('reach-(.*?)\.jar', path.basename(path_to_reach))
reach_version = re.sub('-SNAP.*?$', '', m.groups()[0])
logger.debug('Using REACH version: %s' % reach_version)
return path_to_reach, reach_version | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement boolean_operator comparison_operator identifier none not_operator call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier none block expression_statement 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 call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end subscript call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier return_statement expression_list identifier identifier | Check that the environment supports runnig reach. |
def dnd_endDnd(self, **kwargs) -> SlackResponse:
self._validate_xoxp_token()
return self.api_call("dnd.endDnd", json=kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier type identifier block expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier | Ends the current user's Do Not Disturb session immediately. |
def add_object(self, nidm_object, export_file=True):
if not export_file:
export_dir = None
else:
export_dir = self.export_dir
if not isinstance(nidm_object, NIDMFile):
nidm_object.export(self.version, export_dir)
else:
nidm_object.export(self.version, export_dir, self.prepend_path)
if nidm_object.prov_type == PROV['Activity']:
self.bundle.activity(nidm_object.id,
other_attributes=nidm_object.attributes)
elif nidm_object.prov_type == PROV['Entity']:
self.bundle.entity(nidm_object.id,
other_attributes=nidm_object.attributes)
elif nidm_object.prov_type == PROV['Agent']:
self.bundle.agent(nidm_object.id,
other_attributes=nidm_object.attributes) | module function_definition identifier parameters identifier identifier default_parameter identifier true block if_statement not_operator identifier block expression_statement assignment identifier none else_clause block expression_statement assignment identifier attribute identifier identifier if_statement not_operator call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier subscript identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier subscript identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier subscript identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier | Add a NIDMObject to a NIDM-Results export. |
def _is_qstring(message):
my_class = str(message.__class__)
my_class_name = my_class.replace('<class \'', '').replace('\'>', '')
if my_class_name == 'PyQt5.QtCore.QString':
return True
return False | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end string string_start string_end identifier argument_list string string_start string_content escape_sequence string_end string string_start string_end if_statement comparison_operator identifier string string_start string_content string_end block return_statement true return_statement false | Check if its a QString without adding any dep to PyQt5. |
def autosave(self):
if self.button_autosave.is_checked():
self.save_file(_os.path.join(self._autosave_directory, "%04d " % (self.number_file.get_value()) + self._label_path.get_text()))
self.number_file.increment() | module function_definition identifier parameters identifier block if_statement call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier binary_operator binary_operator string string_start string_content string_end parenthesized_expression call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Autosaves the currently stored data, but only if autosave is checked! |
def window_size(self, window_size):
BasePlotter.window_size.fset(self, window_size)
self.app_window.setBaseSize(*window_size) | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list list_splat identifier | set the render window size |
def addPolygonAnnot(self, points):
CheckParent(self)
val = _fitz.Page_addPolygonAnnot(self, points)
if not val: return
val.thisown = True
val.parent = weakref.proxy(self)
self._annot_refs[id(val)] = val
return val | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement not_operator identifier block return_statement expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier call identifier argument_list identifier identifier return_statement identifier | Add a 'Polygon' annotation for a sequence of points. |
def all_row_ids(data_batch):
all_users = mx.nd.arange(0, MOVIELENS['max_user'], dtype='int64')
all_movies = mx.nd.arange(0, MOVIELENS['max_movie'], dtype='int64')
return {'user_weight': all_users, 'item_weight': all_movies} | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end return_statement dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Generate row ids for all rows |
def check_auth(self, name):
if name in self.auths:
auth = self.auths[name]
if self.args.auth is None:
raise exceptions.ArgParseInatorAuthorizationRequired
elif ((auth is True and self.args.auth != self.auth_phrase) or
(auth is not True and self.args.auth != auth)):
raise exceptions.ArgParseInatorNotValidAuthorization
return True | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier none block raise_statement attribute identifier identifier elif_clause parenthesized_expression boolean_operator parenthesized_expression boolean_operator comparison_operator identifier true comparison_operator attribute attribute identifier identifier identifier attribute identifier identifier parenthesized_expression boolean_operator comparison_operator identifier true comparison_operator attribute attribute identifier identifier identifier identifier block raise_statement attribute identifier identifier return_statement true | Check the authorization for the command |
def generate(self, name: str, **kwargs: Dict[str, str]) -> str:
template = self.patterns[name]
return template.substitute(kwargs) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter dictionary_splat_pattern identifier type generic_type identifier type_parameter type identifier type identifier type identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier | generate url for named url pattern with kwargs |
def modify(self, vals):
self.vals = vals.view(np.ndarray).copy()
y = self.model.predict(self.vals)[0]
self.data_visualize.modify(y)
self.latent_handle.set_data(self.vals[0,self.latent_index[0]], self.vals[0,self.latent_index[1]])
self.axes.figure.canvas.draw() | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list attribute identifier identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier integer subscript attribute identifier identifier integer subscript attribute identifier identifier integer subscript attribute identifier identifier integer expression_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list | When latent values are modified update the latent representation and ulso update the output visualization. |
def show(self, username):
filter = ['(objectclass=posixAccount)', "(uid={})".format(username)]
return self.client.search(filter) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Return a specific user's info in LDIF format. |
def setup(self):
super(CleanCSSFilter, self).setup()
self.root = current_app.config.get('COLLECT_STATIC_ROOT') | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | Initialize filter just before it will be used. |
def _is_video(filepath) -> bool:
if os.path.exists(filepath):
extension = os.path.splitext(filepath)[1]
return extension in ('.mkv', '.mp4', '.avi')
else:
return False | module function_definition identifier parameters identifier type identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list identifier integer return_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end else_clause block return_statement false | Check filename extension to see if it's a video file. |
def length(
cls, request,
vector: (Ptypes.body,
Vector('The vector to analyse.'))) -> [
(200, 'Ok', Float),
(400, 'Wrong vector format')]:
log.info('Computing the length of vector {}'.format(vector))
try:
Respond(200, sqrt(vector['x'] ** 2 +
vector['y'] ** 2 +
vector.get('z', 0) ** 2))
except ValueError:
Respond(400) | module function_definition identifier parameters identifier identifier typed_parameter identifier type tuple attribute identifier identifier call identifier argument_list string string_start string_content string_end type list tuple integer string string_start string_content string_end identifier tuple integer string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier try_statement block expression_statement call identifier argument_list integer call identifier argument_list binary_operator binary_operator binary_operator subscript identifier string string_start string_content string_end integer binary_operator subscript identifier string string_start string_content string_end integer binary_operator call attribute identifier identifier argument_list string string_start string_content string_end integer integer except_clause identifier block expression_statement call identifier argument_list integer | Return the modulo of a vector. |
def combine_results(self, results):
result = {}
for key in results[0]:
result[key] = numpy.concatenate([r[key] for r in results])
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier subscript identifier integer block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list list_comprehension subscript identifier identifier for_in_clause identifier identifier return_statement identifier | Combine results from different batches of filtering |
def merge_dict(a, b, path=None):
if not path:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dict(a[key], b[key], path + [str(key)])
else:
continue
else:
a[key] = b[key]
return a | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator identifier identifier block if_statement boolean_operator call identifier argument_list subscript identifier identifier identifier call identifier argument_list subscript identifier identifier identifier block expression_statement call identifier argument_list subscript identifier identifier subscript identifier identifier binary_operator identifier list call identifier argument_list identifier else_clause block continue_statement else_clause block expression_statement assignment subscript identifier identifier subscript identifier identifier return_statement identifier | Merge dict b into a |
def create_app(app_id, app_name, source_id, region, app_data):
try:
create_at = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
conn = get_conn()
c = conn.cursor()
c.execute("SELECT count(*) FROM app WHERE name='{0}' ".format(app_name))
old_app = c.fetchone()
if old_app[0] > 0:
print 'app name (%s) already existed, clear old app and container info ...' % app_name
c.execute("DELETE FROM container WHERE app_id='{0}'".format(app_id))
c.execute("DELETE FROM app WHERE name='{0}'".format(app_name))
conn.commit()
c.execute("INSERT INTO app (id,name,source_id,region,state,create_at,change_at,app_data) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')"
.format(app_id, app_name, source_id, region, constant.STATE_APP_RUNNING, create_at, create_at, app_data))
conn.commit()
conn.close()
print 'create app %s succeed!' % app_id
except Exception, e:
raise RuntimeError('create app %s failed! %s' % (app_id,e)) | module function_definition identifier parameters identifier identifier identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator subscript identifier integer integer block print_statement binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier identifier attribute identifier identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list print_statement binary_operator string string_start string_content string_end identifier except_clause identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier | insert app record when stack run as a app |
def index(config):
client = Client()
client.prepare_connection()
user_api = API(client)
CLI.show_user(user_api.index()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list | Display user info in LDIF format. |
def create_alert_policy(self, policy_name):
policy_data = { 'policy': { 'incident_preference': 'PER_POLICY', 'name': policy_name } }
create_policy = requests.post(
'https://api.newrelic.com/v2/alerts_policies.json',
headers=self.auth_header,
data=json.dumps(policy_data))
create_policy.raise_for_status()
policy_id = create_policy.json()['policy']['id']
self.refresh_all_alerts()
return policy_id | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end 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 expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier subscript subscript call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list return_statement identifier | Creates an alert policy in NewRelic |
def run_parse(self):
parsedset = {}
parsedset['data_set'] = []
for log in self.input_files:
parsemodule = self.parse_modules[self.args.parser]
try:
if self.args.tzone:
parsemodule.tzone = self.args.tzone
except NameError: pass
parsedset['data_set'].append(parsemodule.parse_file(log))
self.data_set = parsedset
del(parsedset) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end list for_statement identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute attribute identifier identifier identifier try_statement block if_statement attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier except_clause identifier block pass_statement expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier delete_statement parenthesized_expression identifier | Parse one or more log files |
def parse_at_root(
self,
root,
state
):
parsed_dict = {}
dict_element = _element_find_from_root(root, self.element_path)
if dict_element is not None:
parsed_dict = self.parse_at_element(dict_element, state)
elif self.required:
raise MissingValue('Missing required root aggregate "{}"'.format(self.element_path))
return parsed_dict | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier elif_clause attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier return_statement identifier | Parse the root XML element as a dictionary. |
def check_obj(keys, name, obj):
msg = validate_obj(keys, obj)
if msg:
raise aomi.exceptions.AomiData("object check : %s in %s" % (msg, name)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement identifier block raise_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier | Do basic validation on an object |
def _do_timeout_for_query(self, timeout, datapath):
dpid = datapath.id
hub.sleep(timeout)
outport = self._to_querier[dpid]['port']
remove_dsts = []
for dst in self._to_hosts[dpid]:
if not self._to_hosts[dpid][dst]['replied']:
self._remove_multicast_group(datapath, outport, dst)
remove_dsts.append(dst)
for dst in remove_dsts:
del self._to_hosts[dpid][dst] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript subscript attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment identifier list for_statement identifier subscript attribute identifier identifier identifier block if_statement not_operator subscript subscript subscript attribute identifier identifier identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block delete_statement subscript subscript attribute identifier identifier identifier identifier | the process when the QUERY from the querier timeout expired. |
def upcoming(self, chamber, congress=CURRENT_CONGRESS):
"Shortcut for upcoming bills"
path = "bills/upcoming/{chamber}.json".format(chamber=chamber)
return self.fetch(path) | module function_definition identifier parameters identifier identifier default_parameter identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier | Shortcut for upcoming bills |
def kill(self):
self._killed.set()
if not self.is_alive():
logging.debug('Cannot kill thread that is no longer running.')
return
if not self._is_thread_proc_running():
logging.debug("Thread's _thread_proc function is no longer running, "
'will not kill; letting thread exit gracefully.')
return
self.async_raise(ThreadTerminationError) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end return_statement expression_statement call attribute identifier identifier argument_list identifier | Terminates the current thread by raising an error. |
def add_data_to_df(self, data: np.array):
col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi']
data = np.array(data).reshape(-1, len(col_names) + 1)
df = pd.DataFrame(data=data[:, 1:], index=data[:, 0],
columns=col_names)
df.index = pd.to_datetime(df.index)
df.sort_index(ascending=True, inplace=True)
df[['high_p', 'low_p', 'open_p', 'close_p']] = df[
['high_p', 'low_p', 'open_p', 'close_p']].astype(float)
df[['volume', 'oi']] = df[['volume', 'oi']].astype(int)
if self._ndf.empty:
self._ndf = df
else:
self._ndf = self._ndf.append(df) | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier block 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 string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list unary_operator integer binary_operator call identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier subscript identifier slice slice integer keyword_argument identifier subscript identifier slice integer keyword_argument identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier true keyword_argument identifier true expression_statement assignment subscript 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 call attribute subscript 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 identifier argument_list identifier expression_statement assignment subscript identifier list string string_start string_content string_end string string_start string_content string_end call attribute subscript identifier list string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier else_clause block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier | Build Pandas Dataframe in memory |
def build_strain_specific_models(self, joblib=False, cores=1, force_rerun=False):
if len(self.df_orthology_matrix) == 0:
raise RuntimeError('Empty orthology matrix, please calculate first!')
ref_functional_genes = [g.id for g in self.reference_gempro.functional_genes]
log.info('Building strain specific models...')
if joblib:
result = DictList(Parallel(n_jobs=cores)(delayed(self._build_strain_specific_model)(s, ref_functional_genes, self.df_orthology_matrix, force_rerun=force_rerun) for s in self.strain_ids))
else:
result = []
for s in tqdm(self.strain_ids):
result.append(self._build_strain_specific_model(s, ref_functional_genes, self.df_orthology_matrix, force_rerun=force_rerun))
for strain_id, gp_noseqs_path in result:
self.strain_infodict[strain_id]['gp_noseqs_path'] = gp_noseqs_path | module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier integer default_parameter identifier false block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call identifier argument_list call call identifier argument_list keyword_argument identifier identifier generator_expression call call identifier argument_list attribute identifier identifier argument_list identifier identifier attribute identifier identifier keyword_argument identifier identifier for_in_clause identifier attribute identifier identifier else_clause block expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier attribute identifier identifier keyword_argument identifier identifier for_statement pattern_list identifier identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier | Wrapper function for _build_strain_specific_model |
def dict_hash(dct):
dct_s = json.dumps(dct, sort_keys=True)
try:
m = md5(dct_s)
except TypeError:
m = md5(dct_s.encode())
return m.hexdigest() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list | Return a hash of the contents of a dictionary |
def filter(cls, **items):
client = cls._new_api_client(subpath='/search')
items_dict = dict((k, v) for k, v in list(items.items()))
json_data = json.dumps(items_dict, sort_keys=True, indent=4)
return client.make_request(cls, 'post', post_data=json_data) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call identifier generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true keyword_argument identifier integer return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier identifier | Returns multiple Union objects with search params |
def prepare_socket(bind_addr, family, type, proto, nodelay, ssl_adapter):
sock = socket.socket(family, type, proto)
prevent_socket_inheritance(sock)
host, port = bind_addr[:2]
IS_EPHEMERAL_PORT = port == 0
if not (IS_WINDOWS or IS_EPHEMERAL_PORT):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if nodelay and not isinstance(bind_addr, str):
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if ssl_adapter is not None:
sock = ssl_adapter.bind(sock)
listening_ipv6 = (
hasattr(socket, 'AF_INET6')
and family == socket.AF_INET6
and host in ('::', '::0', '::0.0.0.0')
)
if listening_ipv6:
try:
sock.setsockopt(
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0,
)
except (AttributeError, socket.error):
pass
return sock | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier subscript identifier slice integer expression_statement assignment identifier comparison_operator identifier integer if_statement not_operator parenthesized_expression boolean_operator identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer if_statement boolean_operator identifier not_operator call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier parenthesized_expression boolean_operator boolean_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator identifier attribute identifier identifier comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement identifier block try_statement block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier integer except_clause tuple identifier attribute identifier identifier block pass_statement return_statement identifier | Create and prepare the socket object. |
def logout_oauth2(self):
url = "https://api.robinhood.com/oauth2/revoke_token/"
data = {
"client_id": CLIENT_ID,
"token": self.refresh_token,
}
res = self.post(url, payload=data)
if res is None:
self.account_id = None
self.account_url = None
self.access_token = None
self.refresh_token = None
self.mfa_code = None
self.scope = None
self.authenticated = False
return True
else:
raise AuthenticationError("fast_arrow could not log out.") | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier false return_statement true else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Logout for given Oauth2 bearer token |
def disasm_symbol_app(_parser, _, args):
parser = argparse.ArgumentParser(
prog=_parser.prog,
description=_parser.description,
)
parser.add_argument(
'--syntax', '-s',
choices=AsmSyntax.__members__.keys(),
default=None,
)
parser.add_argument('file', help='ELF file to extract a symbol from')
parser.add_argument('symbol', help='the symbol to disassemble')
args = parser.parse_args(args)
if args.syntax is not None:
syntax = AsmSyntax.__members__[args.syntax]
else:
syntax = None
elf = ELF(args.file)
symbol = elf.get_symbol(args.symbol)
print('\n'.join(disasm(symbol.content, symbol.value, syntax=syntax, target=elf))) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier else_clause block expression_statement assignment identifier none expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Disassemble a symbol from an ELF file. |
def _load_config(self):
self._config = ConfigParser.SafeConfigParser()
self._config.read(self.config_path) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Read the configuration file and load it into memory. |
def from_urlencode(self, data, options=None):
qs = dict((k, v if len(v) > 1 else v[0])
for k, v in urlparse.parse_qs(data).iteritems())
return qs | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call identifier generator_expression tuple identifier conditional_expression identifier comparison_operator call identifier argument_list identifier integer subscript identifier integer for_in_clause pattern_list identifier identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list return_statement identifier | handles basic formencoded url posts |
def can_view(self, user):
return user.is_admin or user in self.users \
or self.project.class_ in user.admin_for | module function_definition identifier parameters identifier identifier block return_statement boolean_operator boolean_operator attribute identifier identifier comparison_operator identifier attribute identifier identifier line_continuation comparison_operator attribute attribute identifier identifier identifier attribute identifier identifier | Return whether or not `user` can view info about the group. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.