code
stringlengths 51
2.34k
| sequence
stringlengths 186
3.94k
| docstring
stringlengths 11
171
|
|---|---|---|
def on_backward_begin(self, last_loss:Rank0Tensor, last_input:Tensor, **kwargs):
"Apply AR and TAR to `last_loss`."
if self.alpha != 0.: last_loss += self.alpha * self.out[-1].float().pow(2).mean()
if self.beta != 0.:
h = self.raw_out[-1]
if len(h)>1: last_loss += self.beta * (h[:,1:] - h[:,:-1]).float().pow(2).mean()
return {'last_loss': last_loss}
|
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier dictionary_splat_pattern identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier float block expression_statement augmented_assignment identifier binary_operator attribute identifier identifier call attribute call attribute call attribute subscript attribute identifier identifier unary_operator integer identifier argument_list identifier argument_list integer identifier argument_list if_statement comparison_operator attribute identifier identifier float block expression_statement assignment identifier subscript attribute identifier identifier unary_operator integer if_statement comparison_operator call identifier argument_list identifier integer block expression_statement augmented_assignment identifier binary_operator attribute identifier identifier call attribute call attribute call attribute parenthesized_expression binary_operator subscript identifier slice slice integer subscript identifier slice slice unary_operator integer identifier argument_list identifier argument_list integer identifier argument_list return_statement dictionary pair string string_start string_content string_end identifier
|
Apply AR and TAR to `last_loss`.
|
def _lockstep_fcn(values):
numrequired, fcn, args = values
with _process_lock:
_numdone.value += 1
while 1:
if _numdone.value == numrequired:
return fcn(args)
|
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier identifier identifier with_statement with_clause with_item identifier block expression_statement augmented_assignment attribute identifier identifier integer while_statement integer block if_statement comparison_operator attribute identifier identifier identifier block return_statement call identifier argument_list identifier
|
Wrapper to ensure that all processes execute together
|
async def _unwatch(self, conn):
"Unwatches all previously specified keys"
await conn.send_command('UNWATCH')
res = await conn.read_response()
return self.watching and res or True
|
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement await call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier await call attribute identifier identifier argument_list return_statement boolean_operator boolean_operator attribute identifier identifier identifier true
|
Unwatches all previously specified keys
|
def fits(self, jobShape):
return jobShape.memory <= self.shape.memory and \
jobShape.cores <= self.shape.cores and \
jobShape.disk <= self.shape.disk and \
(jobShape.preemptable or not self.shape.preemptable)
|
module function_definition identifier parameters identifier identifier block return_statement boolean_operator boolean_operator boolean_operator comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier line_continuation comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier line_continuation comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier line_continuation parenthesized_expression boolean_operator attribute identifier identifier not_operator attribute attribute identifier identifier identifier
|
Check if a job shape's resource requirements will fit within this allocation.
|
def random(magnitude=1):
theta = random.uniform(0, 2 * math.pi)
return magnitude * Vector(math.cos(theta), math.sin(theta))
|
module function_definition identifier parameters default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list integer binary_operator integer attribute identifier identifier return_statement binary_operator identifier call identifier argument_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier
|
Create a unit vector pointing in a random direction.
|
def lookup_full_hashes(self, hash_values):
q =
output = []
with self.get_cursor() as dbc:
placeholders = ','.join(['?'] * len(hash_values))
dbc.execute(q.format(placeholders), [sqlite3.Binary(hv) for hv in hash_values])
for h in dbc.fetchall():
threat_type, platform_type, threat_entry_type, has_expired = h
threat_list = ThreatList(threat_type, platform_type, threat_entry_type)
output.append((threat_list, has_expired))
return output
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier assignment identifier list with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list binary_operator list string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment pattern_list identifier identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list tuple identifier identifier return_statement identifier
|
Query DB to see if hash is blacklisted
|
def state_to_wavefunction(state: State) -> pyquil.Wavefunction:
amplitudes = state.vec.asarray()
amplitudes = amplitudes.transpose()
amplitudes = amplitudes.reshape([amplitudes.size])
return pyquil.Wavefunction(amplitudes)
|
module function_definition identifier parameters typed_parameter identifier type identifier type attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list list attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier
|
Convert a QuantumFlow state to a pyQuil Wavefunction
|
def copy_uri_options(hosts, mongodb_uri):
if "?" in mongodb_uri:
options = mongodb_uri.split("?", 1)[1]
else:
options = None
uri = "mongodb://" + hosts
if options:
uri += "/?" + options
return uri
|
module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer else_clause block expression_statement assignment identifier none expression_statement assignment identifier binary_operator string string_start string_content string_end identifier if_statement identifier block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end identifier return_statement identifier
|
Returns a MongoDB URI to hosts with the options from mongodb_uri.
|
def _random_cycle(adj, random_state):
n = random_state.randint(len(adj))
for idx, v in enumerate(adj):
if idx == n:
break
start = v
walk = [start]
visited = {start: 0}
while True:
if len(walk) > 1:
previous = walk[-2]
neighbors = [u for u in adj[walk[-1]] if u != previous]
else:
neighbors = list(adj[walk[-1]])
if not neighbors:
return None
u = random_state.choice(neighbors)
if u in visited:
return walk[visited[u]:]
else:
walk.append(u)
visited[u] = len(visited)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator identifier identifier block break_statement expression_statement assignment identifier identifier expression_statement assignment identifier list identifier expression_statement assignment identifier dictionary pair identifier integer while_statement true block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier unary_operator integer expression_statement assignment identifier list_comprehension identifier for_in_clause identifier subscript identifier subscript identifier unary_operator integer if_clause comparison_operator identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list subscript identifier subscript identifier unary_operator integer if_statement not_operator identifier block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block return_statement subscript identifier slice subscript identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier call identifier argument_list identifier
|
Find a cycle using a random graph walk.
|
def init_celery(self, celery):
count = next(self.counter)
def task_with_hub(f, **opts):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(self, *args, **kwargs)
wrapper.__name__ = wrapper.__name__ + '_' + str(count)
return celery.task(**opts)(wrapper)
self.subscribe = task_with_hub(subscribe)
self.unsubscribe = task_with_hub(unsubscribe)
max_attempts = self.config.get('MAX_ATTEMPTS', 10)
make_req = task_with_hub(make_request_retrying, bind=True,
max_retries=max_attempts)
self.make_request_retrying = make_req
self.send_change = task_with_hub(send_change_notification)
@task_with_hub
def cleanup(hub):
self.storage.cleanup_expired_subscriptions()
self.cleanup = cleanup
def schedule(every_x_seconds=A_DAY):
celery.add_periodic_task(every_x_seconds,
self.cleanup_expired_subscriptions.s())
self.schedule = schedule
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier function_definition identifier parameters identifier dictionary_splat_pattern identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier binary_operator binary_operator attribute identifier identifier string string_start string_content string_end call identifier argument_list identifier return_statement call call attribute identifier identifier argument_list dictionary_splat identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier true keyword_argument identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier decorated_definition decorator identifier function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier function_definition identifier parameters default_parameter identifier identifier block expression_statement call attribute identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier
|
Registers the celery tasks on the hub object.
|
def _list_element_starts_with(items, needle):
for item in items:
if item.startswith(needle):
return True
return False
|
module function_definition identifier parameters identifier identifier block for_statement identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement true return_statement false
|
True of any of the list elements starts with needle
|
def _from_dict(cls, _dict):
args = {}
xtra = _dict.copy()
if 'log_messages' in _dict:
args['log_messages'] = [
LogMessage._from_dict(x) for x in (_dict.get('log_messages'))
]
del xtra['log_messages']
else:
raise ValueError(
'Required property \'log_messages\' not present in OutputData JSON'
)
if 'text' in _dict:
args['text'] = _dict.get('text')
del xtra['text']
else:
raise ValueError(
'Required property \'text\' not present in OutputData JSON')
if 'generic' in _dict:
args['generic'] = [
DialogRuntimeResponseGeneric._from_dict(x)
for x in (_dict.get('generic'))
]
del xtra['generic']
if 'nodes_visited' in _dict:
args['nodes_visited'] = _dict.get('nodes_visited')
del xtra['nodes_visited']
if 'nodes_visited_details' in _dict:
args['nodes_visited_details'] = [
DialogNodeVisitedDetails._from_dict(x)
for x in (_dict.get('nodes_visited_details'))
]
del xtra['nodes_visited_details']
args.update(xtra)
return cls(**args)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end delete_statement subscript identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end delete_statement subscript identifier string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end delete_statement subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end delete_statement subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end delete_statement subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list dictionary_splat identifier
|
Initialize a OutputData object from a json dictionary.
|
def post(self, url, data, params=None):
r = self.session.post(url, data=data, params=params)
return self._response_parser(r, expect_json=False)
|
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false
|
Initiate a POST request
|
def register_annotype_converter(cls, types, is_array=False,
is_mapping=False):
if not isinstance(types, Sequence):
types = [types]
def decorator(subclass):
for typ in types:
cls._annotype_lookup[(typ, is_array, is_mapping)] = subclass
return subclass
return decorator
|
module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier function_definition identifier parameters identifier block for_statement identifier identifier block expression_statement assignment subscript attribute identifier identifier tuple identifier identifier identifier identifier return_statement identifier return_statement identifier
|
Register this class as a converter for Anno instances
|
def administration(self):
url = self._url
res = search("/rest/", url).span()
addText = "admin/"
part1 = url[:res[1]]
part2 = url[res[1]:]
adminURL = "%s%s%s" % (part1, addText, part2)
res = AdminFeatureService(url=url,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port,
initialize=False)
return res
|
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute call identifier argument_list string string_start string_content string_end identifier identifier argument_list expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier slice subscript identifier integer expression_statement assignment identifier subscript identifier slice subscript identifier integer expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier false return_statement identifier
|
returns the hostservice object to manage the back-end functions
|
def fixPath(path):
path = os.path.abspath(os.path.expanduser(path))
if path.startswith("\\"):
return "C:" + path
return path
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end block return_statement binary_operator string string_start string_content string_end identifier return_statement identifier
|
Ensures paths are correct for linux and windows
|
def trace(self, n):
"Restore the position in the history of individual v's nodes"
trace_map = {}
self._trace(n, trace_map)
s = list(trace_map.keys())
s.sort()
return s
|
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement identifier
|
Restore the position in the history of individual v's nodes
|
def add_link(self):
"Create a new internal link"
n=len(self.links)+1
self.links[n]=(0,0)
return n
|
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier binary_operator call identifier argument_list attribute identifier identifier integer expression_statement assignment subscript attribute identifier identifier identifier tuple integer integer return_statement identifier
|
Create a new internal link
|
def spawn_batch_jobs(job, shared_ids, input_args):
samples = []
config = input_args['config']
with open(config, 'r') as f_in:
for line in f_in:
line = line.strip().split(',')
uuid = line[0]
urls = line[1:]
samples.append((uuid, urls))
for sample in samples:
job.addChildJobFn(alignment, shared_ids, input_args, sample, cores=32, memory='20 G', disk='100 G')
|
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier subscript identifier string string_start string_content string_end with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier subscript identifier slice integer expression_statement call attribute identifier identifier argument_list tuple identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier keyword_argument identifier integer keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end
|
Spawns an alignment job for every sample in the input configuration file
|
def _list_items(queue):
con = _conn(queue)
with con:
cur = con.cursor()
cmd = 'SELECT name FROM {0}'.format(queue)
log.debug('SQL Query: %s', cmd)
cur.execute(cmd)
contents = cur.fetchall()
return contents
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier with_statement with_clause with_item identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier
|
Private function to list contents of a queue
|
def dhcp_request(iface=None, **kargs):
if conf.checkIPaddr != 0:
warning("conf.checkIPaddr is not 0, I may not be able to match the answer")
if iface is None:
iface = conf.iface
fam, hw = get_if_raw_hwaddr(iface)
return srp1(Ether(dst="ff:ff:ff:ff:ff:ff") / IP(src="0.0.0.0", dst="255.255.255.255") / UDP(sport=68, dport=67) /
BOOTP(chaddr=hw) / DHCP(options=[("message-type", "discover"), "end"]), iface=iface, **kargs)
|
module function_definition identifier parameters default_parameter identifier none dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier return_statement call identifier argument_list binary_operator binary_operator binary_operator binary_operator call identifier argument_list keyword_argument identifier string string_start string_content string_end call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end call identifier argument_list keyword_argument identifier integer keyword_argument identifier integer call identifier argument_list keyword_argument identifier identifier call identifier argument_list keyword_argument identifier list tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end keyword_argument identifier identifier dictionary_splat identifier
|
Send a DHCP discover request and return the answer
|
def disablingBuidCache(self):
self.buidcache = s_cache.LruDict(0)
yield
self.buidcache = s_cache.LruDict(BUID_CACHE_SIZE)
|
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer expression_statement yield expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier
|
Disable and invalidate the layer buid cache for migration
|
def view_count(self):
views = self.list_views()
counts = defaultdict(lambda: 0)
for view in views:
counts[view.name] += 1
return dict(counts)
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list lambda integer for_statement identifier identifier block expression_statement augmented_assignment subscript identifier attribute identifier identifier integer return_statement call identifier argument_list identifier
|
Return the number of opened views.
|
def map_services(self):
self.get_simple_devices_info()
j = self.data_request({'id': 'status', 'output_format': 'json'}).json()
service_map = {}
items = j.get('devices')
for item in items:
service_map[item.get('id')] = item.get('states')
self.device_services_map = service_map
|
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end identifier argument_list expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement assignment subscript identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier
|
Get full Vera device service info.
|
def to_integer(value, ctx):
if isinstance(value, bool):
return 1 if value else 0
elif isinstance(value, int):
return value
elif isinstance(value, Decimal):
try:
val = int(value.to_integral_exact(ROUND_HALF_UP))
if isinstance(val, int):
return val
except ArithmeticError:
pass
elif isinstance(value, str):
try:
return int(value)
except ValueError:
pass
raise EvaluationError("Can't convert '%s' to an integer" % str(value))
|
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement conditional_expression integer identifier integer elif_clause call identifier argument_list identifier identifier block return_statement identifier elif_clause call identifier argument_list identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block return_statement identifier except_clause identifier block pass_statement elif_clause call identifier argument_list identifier identifier block try_statement block return_statement call identifier argument_list identifier except_clause identifier block pass_statement raise_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier
|
Tries conversion of any value to an integer
|
def loads(s, cls=BinaryQuadraticModel, vartype=None):
return load(s.split('\n'), cls=cls, vartype=vartype)
|
module function_definition identifier parameters identifier default_parameter identifier identifier default_parameter identifier none block return_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end keyword_argument identifier identifier keyword_argument identifier identifier
|
Load a COOrdinate formatted binary quadratic model from a string.
|
def layer_to_solr(self, layer):
success = True
message = 'Synced layer id %s to Solr' % layer.id
layer_dict, message = layer2dict(layer)
if not layer_dict:
success = False
else:
layer_json = json.dumps(layer_dict)
try:
url_solr_update = '%s/solr/hypermap/update/json/docs' % SEARCH_URL
headers = {"content-type": "application/json"}
params = {"commitWithin": 1500}
res = requests.post(url_solr_update, data=layer_json, params=params, headers=headers)
res = res.json()
if 'error' in res:
success = False
message = "Error syncing layer id %s to Solr: %s" % (layer.id, res["error"].get("msg"))
except Exception, e:
success = False
message = "Error syncing layer id %s to Solr: %s" % (layer.id, sys.exc_info()[1])
LOGGER.error(e, exc_info=True)
if success:
LOGGER.info(message)
else:
LOGGER.error(message)
return success, message
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier true expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement not_operator identifier block expression_statement assignment identifier false else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier try_statement block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier false expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end except_clause identifier identifier block expression_statement assignment identifier false expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier subscript call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier
|
Sync a layer in Solr.
|
def main():
parser = argparse.ArgumentParser(description='AFTV Server')
parser.add_argument('-p', '--port', type=int, help='listen port', default=5556)
parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?')
parser.add_argument('-c', '--config', type=str, help='Path to config file')
args = parser.parse_args()
if args.config:
_add_devices_from_config(args)
if args.default and not add('default', args.default):
exit('invalid hostname')
app.run(host='0.0.0.0', port=args.port)
|
module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list 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 string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier integer 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 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 string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list if_statement attribute identifier identifier block expression_statement call identifier argument_list identifier if_statement boolean_operator attribute identifier identifier not_operator call identifier argument_list string string_start string_content string_end attribute identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier
|
Set up the server.
|
def update_cursor(self, dc, grid, row, col):
old_row, old_col = self.old_cursor_row_col
bgcolor = get_color(config["background_color"])
self._draw_cursor(dc, grid, old_row, old_col,
pen=wx.Pen(bgcolor), brush=wx.Brush(bgcolor))
self._draw_cursor(dc, grid, row, col)
|
module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier keyword_argument identifier call attribute identifier identifier argument_list identifier keyword_argument identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier
|
Whites out the old cursor and draws the new one
|
def line(self, node, coords, close=False, **kwargs):
line_len = len(coords)
if len([c for c in coords if c[1] is not None]) < 2:
return
root = 'M%s L%s Z' if close else 'M%s L%s'
origin_index = 0
while origin_index < line_len and None in coords[origin_index]:
origin_index += 1
if origin_index == line_len:
return
if self.graph.horizontal:
coord_format = lambda xy: '%f %f' % (xy[1], xy[0])
else:
coord_format = lambda xy: '%f %f' % xy
origin = coord_format(coords[origin_index])
line = ' '.join([
coord_format(c) for c in coords[origin_index + 1:] if None not in c
])
return self.node(node, 'path', d=root % (origin, line), **kwargs)
|
module function_definition identifier parameters identifier identifier identifier default_parameter identifier false dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator subscript identifier integer none integer block return_statement expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier integer while_statement boolean_operator comparison_operator identifier identifier comparison_operator none subscript identifier identifier block expression_statement augmented_assignment identifier integer if_statement comparison_operator identifier identifier block return_statement if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier lambda lambda_parameters identifier binary_operator string string_start string_content string_end tuple subscript identifier integer subscript identifier integer else_clause block expression_statement assignment identifier lambda lambda_parameters identifier binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list subscript identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier subscript identifier slice binary_operator identifier integer if_clause comparison_operator none identifier return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier binary_operator identifier tuple identifier identifier dictionary_splat identifier
|
Draw a svg line
|
def load_lsa_information(self):
if not (49 < int(self.clustering_parameter) < 101):
raise Exception('Only LSA dimensionalities in the range 50-100' +
' are supported.')
if not self.quiet:
print "Loading LSA term vectors..."
with open(os.path.join(data_path, self.category + '_' +
os.path.join('term_vector_dictionaries',
'term_vectors_dict' +
str(self.clustering_parameter) + '_cpickle.dat')),
'rb') as infile:
self.term_vectors = pickle.load(infile)
|
module function_definition identifier parameters identifier block if_statement not_operator parenthesized_expression comparison_operator integer call identifier argument_list attribute identifier identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end string string_start string_content string_end if_statement not_operator attribute identifier identifier block print_statement string string_start string_content string_end with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier binary_operator binary_operator attribute identifier identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end binary_operator binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_content string_end as_pattern_target identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier
|
Loads a dictionary from disk that maps permissible words to their LSA term vectors.
|
def actually_mount(self, client):
a_obj = self.config.copy()
if 'description' in a_obj:
del a_obj['description']
try:
m_fun = getattr(client, self.mount_fun)
if self.description and a_obj:
m_fun(self.backend,
mount_point=self.path,
description=self.description,
config=a_obj)
elif self.description:
m_fun(self.backend,
mount_point=self.path,
description=self.description)
elif a_obj:
m_fun(self.backend,
mount_point=self.path,
config=a_obj)
else:
m_fun(self.backend,
mount_point=self.path)
except hvac.exceptions.InvalidRequest as exception:
match = re.match('existing mount at (?P<path>.+)', str(exception))
if match:
e_msg = "%s has a mountpoint conflict with %s" % \
(self.path, match.group('path'))
raise aomi_excep.VaultConstraint(e_msg)
else:
raise
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block delete_statement subscript identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier if_statement boolean_operator attribute identifier identifier identifier block expression_statement call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier elif_clause attribute identifier identifier block expression_statement call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier elif_clause identifier block expression_statement call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier else_clause block expression_statement call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end line_continuation tuple attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end raise_statement call attribute identifier identifier argument_list identifier else_clause block raise_statement
|
Actually mount something in Vault
|
def project_name_changed(self, widget, data=None):
if widget.get_text() != "":
self.run_btn.set_sensitive(True)
else:
self.run_btn.set_sensitive(False)
self.update_full_label()
|
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_end block expression_statement call attribute attribute identifier identifier identifier argument_list true else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list false expression_statement call attribute identifier identifier argument_list
|
Function controls whether run button is enabled
|
def disk_check_size(ctx, param, value):
if value:
if isinstance(value, tuple):
val = value[1]
else:
val = value
if val % 1024:
raise click.ClickException('Size must be a multiple of 1024.')
return value
|
module function_definition identifier parameters identifier identifier identifier block if_statement identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifier integer else_clause block expression_statement assignment identifier identifier if_statement binary_operator identifier integer block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier
|
Validation callback for disk size parameter.
|
def irreducible_causes(self):
return tuple(link for link in self
if link.direction is Direction.CAUSE)
|
module function_definition identifier parameters identifier block return_statement call identifier generator_expression identifier for_in_clause identifier identifier if_clause comparison_operator attribute identifier identifier attribute identifier identifier
|
The set of irreducible causes in this |Account|.
|
def isHandlerPresent(self, event_name):
if event_name not in self.handlers:
raise ValueError('{} is not a valid event'.format(event_name))
return self.handlers[event_name] is not None
|
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement comparison_operator subscript attribute identifier identifier identifier none
|
Check if an event has an handler.
|
def main():
alarm = XBeeAlarm('/dev/ttyUSB0', '\x56\x78')
routine = SimpleWakeupRoutine(alarm)
from time import sleep
while True:
try:
print "Waiting 5 seconds..."
sleep(5)
print "Firing"
routine.trigger()
except KeyboardInterrupt:
break
|
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment identifier call identifier argument_list identifier import_from_statement dotted_name identifier dotted_name identifier while_statement true block try_statement block print_statement string string_start string_content string_end expression_statement call identifier argument_list integer print_statement string string_start string_content string_end expression_statement call attribute identifier identifier argument_list except_clause identifier block break_statement
|
Run through simple demonstration of alarm concept
|
def _get_filtered_study_ids(shard, include_aliases=False):
from peyotl.phylesystem.helper import DIGIT_PATTERN
k = shard.get_doc_ids()
if shard.has_aliases and (not include_aliases):
x = []
for i in k:
if DIGIT_PATTERN.match(i) or ((len(i) > 1) and (i[-2] == '_')):
pass
else:
x.append(i)
return x
|
module function_definition identifier parameters identifier default_parameter identifier false block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator attribute identifier identifier parenthesized_expression not_operator identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement boolean_operator call attribute identifier identifier argument_list identifier parenthesized_expression boolean_operator parenthesized_expression comparison_operator call identifier argument_list identifier integer parenthesized_expression comparison_operator subscript identifier unary_operator integer string string_start string_content string_end block pass_statement else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
|
Optionally filters out aliases from standard doc-id list
|
def split_pdf(pdf_path):
pdf = PdfFileReader(pdf_path)
pdf_list = []
for page_num in range(pdf.numPages):
page = pdf.getPage(page_num)
pdf_writer = PdfFileWriter()
pdf_writer.addPage(page)
with NamedTemporaryFile(prefix='pyglass', suffix='.pdf', delete=False) as tempfileobj:
pdf_writer.write(tempfileobj)
page_path = tempfileobj.name
pdf_list.append(page_path)
return pdf_list
|
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier false as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
|
Splits a multi-page pdf into a list of single page pdfs
|
def _get_id(self):
return ''.join(map(str,
filter(is_not_None,
[self.Prefix, self.Name])))
|
module function_definition identifier parameters identifier block return_statement call attribute string string_start string_end identifier argument_list call identifier argument_list identifier call identifier argument_list identifier list attribute identifier identifier attribute identifier identifier
|
Construct and return the identifier
|
def __try_parse_number(self, string):
try:
return int(string)
except ValueError:
try:
return float(string)
except ValueError:
return False
|
module function_definition identifier parameters identifier identifier block try_statement block return_statement call identifier argument_list identifier except_clause identifier block try_statement block return_statement call identifier argument_list identifier except_clause identifier block return_statement false
|
Try to parse a string to a number, else return False.
|
def __add(self, token):
self.__symbols.append(token)
text = token.text
if text is not None and text not in self.__mapping:
self.__mapping[text] = token
|
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier
|
Unconditionally adds a token to the table.
|
def getProvStack(self, iden: bytes):
retn = self.slab.get(iden, db=self.db)
if retn is None:
return None
return s_msgpack.un(retn)
|
module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier if_statement comparison_operator identifier none block return_statement none return_statement call attribute identifier identifier argument_list identifier
|
Returns the provenance stack given the iden to it
|
def bootstrap_app():
from salt.netapi.rest_cherrypy import app
import salt.config
__opts__ = salt.config.client_config(
os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master'))
return app.get_app(__opts__)
|
module function_definition identifier parameters block import_from_statement dotted_name identifier identifier identifier dotted_name identifier import_statement dotted_name identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier
|
Grab the opts dict of the master config by trying to import Salt
|
def load(provider, config_location=DEFAULT_CONFIG_DIR):
auth = None
auth_file = None
try:
config_dir = os.path.join(config_location, NOIPY_CONFIG)
print("Loading stored auth info [%s]... " % config_dir, end="")
auth_file = os.path.join(config_dir, provider)
with open(auth_file) as f:
auth_key = f.read()
auth = ApiAuth.get_instance(auth_key.encode('utf-8'))
print("OK.")
except IOError as e:
print('{0}: "{1}"'.format(e.strerror, auth_file))
raise e
return auth
|
module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement assignment identifier none expression_statement assignment identifier none try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier string string_start string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier 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 expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier raise_statement identifier return_statement identifier
|
Load provider specific auth info from file
|
def validate(self):
valids = [getattr(self, valid)
for valid in sorted(dir(self.__class__))
if valid.startswith('is_valid_')]
for is_valid in valids:
if not is_valid():
docstring = '\n'.join(
line.strip() for line in is_valid.__doc__.splitlines())
doc = docstring.format(**vars(self))
raise ValueError(doc)
|
module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier identifier for_in_clause identifier call identifier argument_list call identifier argument_list attribute identifier identifier if_clause call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block if_statement not_operator call identifier argument_list block expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat call identifier argument_list identifier raise_statement call identifier argument_list identifier
|
Apply the `is_valid` methods to self and possibly raise a ValueError.
|
def next_batch(self, n=1):
if len(self.queue) == 0:
return []
batch = list(reversed((self.queue[-n:])))
self.queue = self.queue[:-n]
return batch
|
module function_definition identifier parameters identifier default_parameter identifier integer block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block return_statement list expression_statement assignment identifier call identifier argument_list call identifier argument_list parenthesized_expression subscript attribute identifier identifier slice unary_operator identifier expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice unary_operator identifier return_statement identifier
|
Return the next requests that should be dispatched.
|
def form_valid(self, form):
response = super(FormAjaxMixin, self).form_valid(form)
if self.request.is_ajax():
return self.json_to_response()
return response
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier if_statement call attribute attribute identifier identifier identifier argument_list block return_statement call attribute identifier identifier argument_list return_statement identifier
|
If form valid return response with action
|
def assume_role_credentials(self, arn):
log.info("Assuming role as %s", arn)
for name in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN']:
if name in os.environ and not os.environ[name]:
del os.environ[name]
sts = self.amazon.session.client("sts")
with self.catch_boto_400("Couldn't assume role", arn=arn):
creds = sts.assume_role(RoleArn=arn, RoleSessionName="aws_syncr")
return {
'AWS_ACCESS_KEY_ID': creds["Credentials"]["AccessKeyId"]
, 'AWS_SECRET_ACCESS_KEY': creds["Credentials"]["SecretAccessKey"]
, 'AWS_SECURITY_TOKEN': creds["Credentials"]["SessionToken"]
, 'AWS_SESSION_TOKEN': creds["Credentials"]["SessionToken"]
}
|
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier for_statement 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 block if_statement boolean_operator comparison_operator identifier attribute identifier identifier not_operator subscript attribute identifier identifier identifier block delete_statement subscript attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end return_statement dictionary pair string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end
|
Return the environment variables for an assumed role
|
def visit_UnaryOp(self, node: AST, dfltChaining: bool = True) -> str:
op = node.op
with self.op_man(op):
return self.visit(op) + self.visit(node.operand)
|
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier true type identifier block expression_statement assignment identifier attribute identifier identifier with_statement with_clause with_item call attribute identifier identifier argument_list identifier block return_statement binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list attribute identifier identifier
|
Return representation of `node`s operator and operand.
|
def iter_callback_properties(self):
for name in dir(self):
if self.is_callback_property(name):
yield name, getattr(type(self), name)
|
module function_definition identifier parameters identifier block for_statement identifier call identifier argument_list identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement yield expression_list identifier call identifier argument_list call identifier argument_list identifier identifier
|
Iterator to loop over all callback properties.
|
def input_file(self, _container):
p = local.path(_container)
if set_input_container(p, CFG):
return
p = find_hash(CFG["container"]["known"].value, container)
if set_input_container(p, CFG):
return
raise ValueError("The path '{0}' does not exist.".format(p))
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier identifier block return_statement expression_statement assignment identifier call identifier argument_list attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier identifier if_statement call identifier argument_list identifier identifier block return_statement raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier
|
Find the input path of a uchroot container.
|
def extract_secs(self, tx, tx_in_idx):
sc = tx.SolutionChecker(tx)
tx_context = sc.tx_context_for_idx(tx_in_idx)
solution_stack = []
for puzzle_script, solution_stack, flags, sighash_f in sc.puzzle_and_solution_iterator(tx_context):
for opcode, data, pc, new_pc in self._script_tools.get_opcodes(puzzle_script):
if data and is_sec(data):
yield data
for data in solution_stack:
if is_sec(data):
yield data
|
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier identifier call attribute identifier identifier argument_list identifier block for_statement pattern_list identifier identifier identifier identifier call attribute attribute identifier identifier identifier argument_list identifier block if_statement boolean_operator identifier call identifier argument_list identifier block expression_statement yield identifier for_statement identifier identifier block if_statement call identifier argument_list identifier block expression_statement yield identifier
|
For a given script solution, iterate yield its sec blobs
|
def modifie_many(self, dic: dict):
for i, v in dic.items():
self.modifie(i, v)
|
module function_definition identifier parameters identifier typed_parameter identifier type identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier identifier
|
Convenience function which calls modifie on each element of dic
|
def _parse_datetime_value(value):
if value.endswith('Z'):
value = value[:-1] + '+00:00'
return arrow.get(value, 'YYYY-MM-DDTHH:mm:ssZ').datetime
|
module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator subscript identifier slice unary_operator integer string string_start string_content string_end return_statement attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier
|
Deserialize a DateTime object from its proper ISO-8601 representation.
|
def add_ignore(self, depend):
try:
self._add_child(self.ignore, self.ignore_set, depend)
except TypeError as e:
e = e.args[0]
if SCons.Util.is_List(e):
s = list(map(str, e))
else:
s = str(e)
raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
|
module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier subscript attribute identifier identifier integer if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier raise_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple call identifier argument_list identifier identifier call identifier argument_list identifier
|
Adds dependencies to ignore.
|
def call_name_is(siter, name):
return (
isinstance(siter, ast.Call)
and hasattr(siter.func, 'attr')
and siter.func.attr == name
)
|
module function_definition identifier parameters identifier identifier block return_statement parenthesized_expression boolean_operator boolean_operator call identifier argument_list identifier attribute identifier identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end comparison_operator attribute attribute identifier identifier identifier identifier
|
Checks the function call name
|
def query_all():
recs = TabPost2Tag.select(
TabPost2Tag,
TabTag.kind.alias('tag_kind'),
).join(
TabTag,
on=(TabPost2Tag.tag_id == TabTag.uid)
)
return recs
|
module function_definition identifier parameters block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list identifier keyword_argument identifier parenthesized_expression comparison_operator attribute identifier identifier attribute identifier identifier return_statement identifier
|
Query all the records from TabPost2Tag.
|
def relative_path(self, key):
key = str(key)
key = key.replace(':', '/')
key = key[1:]
if not self.case_sensitive:
key = key.lower()
return os.path.normpath(key)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript identifier slice integer if_statement not_operator attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute attribute identifier identifier identifier argument_list identifier
|
Returns the relative path for given `key`
|
def get(self, uri, disable_proxy=False, stream=False):
response = requests.get(
uri,
headers=self.headers,
allow_redirects=True,
cookies={},
stream=stream,
proxies=self.proxy if not disable_proxy else False
)
if response.status_code in _PERMITTED_STATUS_CODES:
self.response_headers = response.headers
return response.content if not stream else response.iter_content()
else:
raise requests.exceptions.HTTPError(
"HTTP response did not have a permitted status code."
)
|
module function_definition identifier parameters identifier identifier default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true keyword_argument identifier dictionary keyword_argument identifier identifier keyword_argument identifier conditional_expression attribute identifier identifier not_operator identifier false if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement conditional_expression attribute identifier identifier not_operator identifier call attribute identifier identifier argument_list else_clause block raise_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end
|
Return Requests response to GET request.
|
def promote_s3app(self):
utils.banner("Promoting S3 App")
primary_region = self.configs['pipeline']['primary_region']
s3obj = s3.S3Deployment(
app=self.app,
env=self.env,
region=self.region,
prop_path=self.json_path,
artifact_path=self.artifact_path,
artifact_version=self.artifact_version,
primary_region=primary_region)
s3obj.promote_artifacts(promote_stage=self.promote_stage)
|
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier
|
promotes S3 deployment to LATEST
|
def insert_after(self, target):
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target) + 1, self)
|
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator call attribute attribute attribute identifier identifier identifier identifier argument_list identifier integer identifier
|
insert this widget into the targets parent container after the target
|
def flatten_container(self, container):
for names in ARG_MAP.values():
if names[TransformationTypes.CHRONOS.value]['name'] and \
'.' in names[TransformationTypes.CHRONOS.value]['name']:
chronos_dotted_name = names[TransformationTypes.CHRONOS.value]['name']
parts = chronos_dotted_name.split('.')
if parts[-2] == 'parameters':
common_type = names[TransformationTypes.CHRONOS.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[chronos_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[chronos_dotted_name] = result
return container
|
module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement boolean_operator subscript subscript identifier attribute attribute identifier identifier identifier string string_start string_content string_end comparison_operator string string_start string_content string_end subscript subscript identifier attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript subscript identifier attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator subscript identifier unary_operator integer string string_start string_content string_end block expression_statement assignment identifier call attribute subscript identifier attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript identifier unary_operator integer identifier if_statement identifier block expression_statement assignment subscript identifier identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier list_splat identifier if_statement identifier block expression_statement assignment subscript identifier identifier identifier return_statement identifier
|
Accepts a chronos container and pulls out the nested values into the top level
|
def _check_gle_response(result):
_check_command_response(result)
if result.get("wtimeout", False):
raise WTimeoutError(result.get("errmsg", result.get("err")),
result.get("code"),
result)
error_msg = result.get("err", "")
if error_msg is None:
return result
if error_msg.startswith("not master"):
raise NotMasterError(error_msg, result)
details = result
if "errObjects" in result:
for errobj in result["errObjects"]:
if errobj.get("err") == error_msg:
details = errobj
break
code = details.get("code")
if code in (11000, 11001, 12582):
raise DuplicateKeyError(details["err"], code, result)
raise OperationFailure(details["err"], code, result)
|
module function_definition identifier parameters identifier block expression_statement call identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end false block raise_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list 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 string string_start string_end if_statement comparison_operator identifier none block return_statement identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block raise_statement call identifier argument_list identifier identifier expression_statement assignment identifier identifier if_statement comparison_operator string string_start string_content string_end identifier block for_statement identifier subscript identifier string string_start string_content string_end block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end identifier block expression_statement assignment identifier identifier break_statement expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier tuple integer integer integer block raise_statement call identifier argument_list subscript identifier string string_start string_content string_end identifier identifier raise_statement call identifier argument_list subscript identifier string string_start string_content string_end identifier identifier
|
Return getlasterror response as a dict, or raise OperationFailure.
|
def _bg_combine(self, bgs):
out = np.ones(self.h5["raw"].shape, dtype=float)
for bg in bgs:
out *= bg[:]
return out
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute subscript attribute identifier identifier string string_start string_content string_end identifier keyword_argument identifier identifier for_statement identifier identifier block expression_statement augmented_assignment identifier subscript identifier slice return_statement identifier
|
Combine several background amplitude images
|
def delete(self):
if self._sheet.readonly:
raise ReadOnlyException
gd_client = self._sheet.client
assert gd_client is not None
return gd_client.DeleteRow(self._entry)
|
module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block raise_statement identifier expression_statement assignment identifier attribute attribute identifier identifier identifier assert_statement comparison_operator identifier none return_statement call attribute identifier identifier argument_list attribute identifier identifier
|
Delete the row from the spreadsheet
|
def setAttributesJson(self, attributesJson):
try:
self._attributes = json.loads(attributesJson)
except:
raise exceptions.InvalidJsonException(attributesJson)
return self
|
module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier except_clause block raise_statement call attribute identifier identifier argument_list identifier return_statement identifier
|
Sets the attributes dictionary from a JSON string.
|
def __wrap_docker_exec(func):
def call(*args, **kwargs):
try:
return func(*args, **kwargs)
except OSError as e:
if e.errno == errno.ENOENT:
raise DockerExecuteError('Failed to execute docker. Is it installed?')
raise
return call
|
module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end raise_statement return_statement identifier
|
Wrap a function to raise DockerExecuteError on ENOENT
|
def copy_resources(self):
if not os.path.isdir('resources'):
os.mkdir('resources')
resource_dir = os.path.join(os.getcwd(), 'resources', '')
copied_resources = []
for resource in self.resources:
src = os.path.join(EULER_DATA, 'resources', resource)
if os.path.isfile(src):
shutil.copy(src, resource_dir)
copied_resources.append(resource)
if copied_resources:
copied = ', '.join(copied_resources)
path = os.path.relpath(resource_dir, os.pardir)
msg = "Copied {} to {}.".format(copied, path)
click.secho(msg, fg='green')
|
module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier 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 identifier expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end
|
Copies the relevant resources to a resources subdirectory
|
def add_url(self, name: str, pattern: str, application: Callable) -> None:
self.urlmapper.add(name, self.prefix + pattern)
self.register_app(name, application)
|
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type none block expression_statement call attribute attribute identifier identifier identifier argument_list identifier binary_operator attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier
|
add url pattern dispatching to application
|
def summary_plotting_engine(**kwargs):
logging.debug(f"Using {prms.Batch.backend} for plotting")
experiments = kwargs["experiments"]
farms = kwargs["farms"]
barn = None
logging.debug(" - summary_plot_engine")
farms = _preparing_data_and_plotting(
experiments=experiments,
farms=farms
)
return farms, barn
|
module function_definition identifier parameters dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content interpolation attribute attribute identifier identifier identifier string_content string_end 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 none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier return_statement expression_list identifier identifier
|
creates plots of summary data.
|
def dragend(self, event):
x_range = [self.begin_drag.x//self.col_width, event.x//self.col_width]
y_range = [self.begin_drag.y//self.row_height,
event.y//self.row_height]
for i in range(2):
for ls in [x_range, y_range]:
if ls[i] < 0:
ls[i] = 0
if ls[i] >= self.rows:
ls[i] = self.rows-1
for x in range(min(x_range), max(x_range)+1):
for y in range(min(y_range), max(y_range)+1):
if x == self.begin_drag.x//self.col_width and \
y == self.begin_drag.y//self.row_height:
continue
self.color_square(x*self.col_width, y*self.row_height)
self.begin_drag = None
print(len(self.cells), "cells selected")
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list binary_operator attribute attribute identifier identifier identifier attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier list binary_operator attribute attribute identifier identifier identifier attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier for_statement identifier call identifier argument_list integer block for_statement identifier list identifier identifier block if_statement comparison_operator subscript identifier identifier integer block expression_statement assignment subscript identifier identifier integer if_statement comparison_operator subscript identifier identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier binary_operator attribute identifier identifier integer for_statement identifier call identifier argument_list call identifier argument_list identifier binary_operator call identifier argument_list identifier integer block for_statement identifier call identifier argument_list call identifier argument_list identifier binary_operator call identifier argument_list identifier integer block if_statement boolean_operator comparison_operator identifier binary_operator attribute attribute identifier identifier identifier attribute identifier identifier line_continuation comparison_operator identifier binary_operator attribute attribute identifier identifier identifier attribute identifier identifier block continue_statement expression_statement call attribute identifier identifier argument_list binary_operator identifier attribute identifier identifier binary_operator identifier attribute identifier identifier expression_statement assignment attribute identifier identifier none expression_statement call identifier argument_list call identifier argument_list attribute identifier identifier string string_start string_content string_end
|
Handles the end of a drag action.
|
def create_geotiff(name, Array, driver, ndv, xsize, ysize, geot, projection, datatype, band=1):
if isinstance(datatype, np.int) == False:
if datatype.startswith('gdal.GDT_') == False:
datatype = eval('gdal.GDT_'+datatype)
newfilename = name+'.tif'
Array[np.isnan(Array)] = ndv
DataSet = driver.Create(newfilename, xsize, ysize, 1, datatype)
DataSet.SetGeoTransform(geot)
DataSet.SetProjection(projection.ExportToWkt())
DataSet.GetRasterBand(band).WriteArray(Array)
DataSet.GetRasterBand(band).SetNoDataValue(ndv)
return newfilename
|
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier identifier identifier default_parameter identifier integer block if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier false block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end false block expression_statement assignment identifier call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier binary_operator identifier string string_start string_content string_end expression_statement assignment subscript identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier integer identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier return_statement identifier
|
Creates new geotiff from array
|
def subcommand(self, name, help):
if self._subcommands is None:
self._subcommands = self.add_subparsers(help='commands')
return self._subcommands.add_parser(name, description=help, help=help)
|
module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier
|
Creates a parser for a sub-command.
|
def handle_token(cls, parser, token):
tag_error = "Accepted formats {%% %(tagname)s %(args)s %%} or " \
"{%% %(tagname)s %(args)s as [var] %%}"
bits = token.split_contents()
args_count = len(bits) - 1
if args_count >= 2 and bits[-2] == 'as':
as_var = bits[-1]
args_count -= 2
else:
as_var = None
if args_count != cls.args_count:
arg_list = ' '.join(['[arg]' * cls.args_count])
raise TemplateSyntaxError(tag_error % {'tagname': bits[0],
'args': arg_list})
args = [parser.compile_filter(tkn)
for tkn in bits[1:args_count + 1]]
return cls(args, varname=as_var)
|
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator call identifier argument_list identifier integer if_statement boolean_operator comparison_operator identifier integer comparison_operator subscript identifier unary_operator integer string string_start string_content string_end block expression_statement assignment identifier subscript identifier unary_operator integer expression_statement augmented_assignment identifier integer else_clause block expression_statement assignment identifier none if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list binary_operator string string_start string_content string_end attribute identifier identifier raise_statement call identifier argument_list binary_operator identifier dictionary pair string string_start string_content string_end subscript identifier integer pair string string_start string_content string_end identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier subscript identifier slice integer binary_operator identifier integer return_statement call identifier argument_list identifier keyword_argument identifier identifier
|
Class method to parse and return a Node.
|
def _create_default_config_file(self):
logger.info('Initialize Maya launcher, creating config file...\n')
self.add_section(self.DEFAULTS)
self.add_section(self.PATTERNS)
self.add_section(self.ENVIRONMENTS)
self.add_section(self.EXECUTABLES)
self.set(self.DEFAULTS, 'executable', None)
self.set(self.DEFAULTS, 'environment', None)
self.set(self.PATTERNS, 'exclude', ', '.join(self.EXLUDE_PATTERNS))
self.set(self.PATTERNS, 'icon_ext', ', '.join(self.ICON_EXTENSIONS))
self.config_file.parent.mkdir(exist_ok=True)
self.config_file.touch()
with self.config_file.open('wb') as f:
self.write(f)
sys.exit('Maya launcher has successfully created config file at:\n'
' "{}"'.format(str(self.config_file)))
|
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end none expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end none expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier true expression_statement call attribute attribute identifier identifier identifier argument_list with_statement with_clause with_item as_pattern call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end identifier argument_list call identifier argument_list attribute identifier identifier
|
If config file does not exists create and set default values.
|
def all_states(self) -> Tuple[State, ...]:
return tuple(self._transform_list_of_states_to_state(states)
for states in self._cartesian_product_of_every_states_of_each_genes())
|
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier type ellipsis block return_statement call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list
|
Return all the possible states of this influence graph.
|
def _average_called_depth(in_file):
import cyvcf2
depths = []
for rec in cyvcf2.VCF(str(in_file)):
d = rec.INFO.get("DP")
if d is not None:
depths.append(int(d))
if len(depths) > 0:
return int(math.ceil(numpy.mean(depths)))
else:
return 0
|
module function_definition identifier parameters identifier block import_statement dotted_name identifier expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list call identifier argument_list identifier 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 call attribute identifier identifier argument_list call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement call identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier else_clause block return_statement integer
|
Retrieve the average depth of called reads in the provided VCF.
|
def start_subscribe(self):
if not self.conn:
raise ValueError('Not connected')
elif not self.pubsub_conn:
raise ValueError('PubSub not enabled')
return Subscription(self)
|
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end elif_clause not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement call identifier argument_list identifier
|
Create a new Subscription context manager.
|
def check_dependencies(self):
deadlocks = []
for task in self.iflat_tasks():
for dep in task.deps:
if dep.node.depends_on(task):
deadlocks.append((task, dep.node))
if deadlocks:
lines = ["Detect wrong list of dependecies that will lead to a deadlock:"]
lines.extend(["%s <--> %s" % nodes for nodes in deadlocks])
raise RuntimeError("\n".join(lines))
|
module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block for_statement identifier attribute identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list tuple identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list_comprehension binary_operator string string_start string_content string_end identifier for_in_clause identifier identifier raise_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier
|
Test the dependencies of the nodes for possible deadlocks.
|
def qstd(x,quant=0.05,top=False,bottom=False):
s = np.sort(x)
n = np.size(x)
lo = s[int(n*quant)]
hi = s[int(n*(1-quant))]
if top:
w = np.where(x>=lo)
elif bottom:
w = np.where(x<=hi)
else:
w = np.where((x>=lo)&(x<=hi))
return np.std(x[w])
|
module function_definition identifier parameters identifier default_parameter identifier float default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript identifier call identifier argument_list binary_operator identifier identifier expression_statement assignment identifier subscript identifier call identifier argument_list binary_operator identifier parenthesized_expression binary_operator integer identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list comparison_operator identifier identifier elif_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list comparison_operator identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator parenthesized_expression comparison_operator identifier identifier parenthesized_expression comparison_operator identifier identifier return_statement call attribute identifier identifier argument_list subscript identifier identifier
|
returns std, ignoring outer 'quant' pctiles
|
def bound_symbols(self):
if self._bound_symbols is None:
res = set.union(
set([]),
*[_bound_symbols(val) for val in self.kwargs.values()])
res.update(
set([]),
*[_bound_symbols(arg) for arg in self.args])
self._bound_symbols = res
return self._bound_symbols
|
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list list list_splat list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list list list_splat list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement attribute identifier identifier
|
Set of bound SymPy symbols in the expression
|
def _decoder(self, obj):
if '__class__' in obj:
elem = eval(obj['__class__'])()
elem.ident = obj['ident']
elem.group = str(obj['group'])
elem.name = str(obj['name'])
elem.ctype = str(obj['ctype'])
elem.pytype = str(obj['pytype'])
elem.access = obj['access']
return elem
return obj
|
module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call call identifier argument_list subscript identifier string string_start string_content string_end argument_list expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end return_statement identifier return_statement identifier
|
Decode a toc element leaf-node
|
def load(self, callback):
if callback is None:
def callb():
pass
callback = callb
if len(self._loaded_callbacks) == 0:
self._request_module_status()
self._request_channel_name()
else:
print("++++++++++++++++++++++++++++++++++")
self._loaded_callbacks.append(callback)
self._load()
|
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block function_definition identifier parameters block pass_statement expression_statement assignment identifier identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list else_clause block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list
|
Retrieve names of channels
|
def cleanPolyline(elem, options):
pts = parseListOfPoints(elem.getAttribute('points'))
elem.setAttribute('points', scourCoordinates(pts, options, True))
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier identifier true
|
Scour the polyline points attribute
|
def send_ack(self):
if self.last_ack == self.proto.max_id:
return
LOGGER.debug("ack (%d)", self.proto.max_id)
self.last_ack = self.proto.max_id
self.send_message(f"4{to_json([self.proto.max_id])}")
|
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content interpolation call identifier argument_list list attribute attribute identifier identifier identifier string_end
|
Send an ack message
|
def pack(content):
if isinstance(content, six.text_type):
content = content.encode("utf-8")
return struct.pack('i', len(content)) + content
|
module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement binary_operator call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier identifier
|
content should be str
|
def redirect(self, url, status=None):
self.status_code = 302 if status is None else status
self.headers = Headers([('location', url)])
self.message = ''
self.end()
|
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment attribute identifier identifier conditional_expression integer comparison_operator identifier none identifier expression_statement assignment attribute identifier identifier call identifier argument_list list tuple string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier string string_start string_end expression_statement call attribute identifier identifier argument_list
|
Redirect to the specified url, optional status code defaults to 302.
|
def _start_thread(self):
self._stopping_event = Event()
self._enqueueing_thread = Thread(target=self._enqueue_batches, args=(self._stopping_event,))
self._enqueueing_thread.start()
|
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier tuple attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list
|
Start an enqueueing thread.
|
def cprint(msg, *args, **kw):
if len(args) or len(kw):
msg = msg.format(*args, **kw)
print(fmt('{}<0>'.format(msg)))
|
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement boolean_operator call identifier argument_list identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier expression_statement call identifier argument_list call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier
|
Print colored message to stdout.
|
def existing(self):
catalog = api.portal.get_tool('portal_catalog')
results = []
layout_path = self._get_layout_path(
self.request.form.get('layout', '')
)
for brain in catalog(layout=layout_path):
results.append({
'title': brain.Title,
'url': brain.getURL()
})
return json.dumps({
'total': len(results),
'data': results
})
|
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 expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end for_statement identifier call identifier argument_list keyword_argument identifier identifier block expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end call identifier argument_list identifier pair string string_start string_content string_end identifier
|
find existing content assigned to this layout
|
def union(a: Iterable[Any], b: Iterable[Any]) -> List[Any]:
u = []
for item in a:
if item not in u:
u.append(item)
for item in b:
if item not in u:
u.append(item)
return u
|
module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier identifier block if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
|
Return a list of items that are in `a` or `b`
|
def setup(self, environ):
json_handler = Root().putSubHandler('calc', Calculator())
middleware = wsgi.Router('/', post=json_handler,
accept_content_types=JSON_CONTENT_TYPES)
response = [wsgi.GZipMiddleware(200)]
return wsgi.WsgiHandler(middleware=[wsgi.wait_for_body_middleware,
middleware],
response_middleware=response)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list string string_start string_content string_end call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier list call attribute identifier identifier argument_list integer return_statement call attribute identifier identifier argument_list keyword_argument identifier list attribute identifier identifier identifier keyword_argument identifier identifier
|
Called once to setup the list of wsgi middleware.
|
def init(lang, domain):
translations_dir = _get_translations_dir()
domain = _get_translations_domain(domain)
pot = os.path.join(translations_dir, f'{domain}.pot')
return _run(f'init -i {pot} -d {translations_dir} -l {lang} --domain={domain}')
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start interpolation identifier string_content string_end return_statement call identifier argument_list string string_start string_content interpolation identifier string_content interpolation identifier string_content interpolation identifier string_content interpolation identifier string_end
|
Initialize translations for a language code.
|
def partition_version_classifiers(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]:
versions_min, versions_only = [], []
for classifier in classifiers:
version = classifier.replace(version_prefix, '')
versions = versions_min
if version.endswith(only_suffix):
version = version.replace(only_suffix, '')
versions = versions_only
try:
versions.append(tuple([int(_) for _ in version.split('.')]))
except ValueError:
pass
return versions_min, versions_only
|
module function_definition identifier parameters typed_parameter identifier type subscript attribute identifier identifier identifier typed_default_parameter identifier type identifier string string_start string_content string_end typed_default_parameter identifier type identifier string string_start string_content string_end type subscript attribute identifier identifier subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier block expression_statement assignment pattern_list identifier identifier expression_list list list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_end expression_statement assignment identifier identifier if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_end expression_statement assignment identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block pass_statement return_statement expression_list identifier identifier
|
Find version number classifiers in given list and partition them into 2 groups.
|
def main(args):
random.seed()
temp_dir = tempfile.mkdtemp()
logging.info('Created temporary directory: %s', temp_dir)
validator = SubmissionValidator(
source_dir=args.source_dir,
target_dir=args.target_dir,
temp_dir=temp_dir,
do_copy=args.copy,
use_gpu=args.use_gpu,
containers_file=args.containers_file)
validator.run()
logging.info('Deleting temporary directory: %s', temp_dir)
subprocess.call(['rm', '-rf', temp_dir])
|
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end 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
|
Validate all submissions and copy them into place
|
def sentence_texts(self):
if not self.is_tagged(SENTENCES):
self.tokenize_sentences()
return self.texts(SENTENCES)
|
module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier
|
The list of texts representing ``sentences`` layer elements.
|
def _wipe_www_page(self, slug):
wd = os.path.join(self._dirs['www'], slug)
if os.path.isdir(wd):
shutil.rmtree(wd)
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier 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
|
Remove all data in www about the page identified by slug.
|
def stylize(txt, bold=False, underline=False):
setting = ''
setting += _SET_BOLD if bold is True else ''
setting += _SET_UNDERLINE if underline is True else ''
return setting + str(txt) + _STYLE_RESET
|
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier string string_start string_end expression_statement augmented_assignment identifier conditional_expression identifier comparison_operator identifier true string string_start string_end expression_statement augmented_assignment identifier conditional_expression identifier comparison_operator identifier true string string_start string_end return_statement binary_operator binary_operator identifier call identifier argument_list identifier identifier
|
Changes style of the text.
|
def _calculate(self, field):
base_offset = 0
if self.base_field is not None:
base_offset = self.base_field.offset
target_offset = self._field.offset
if (target_offset is None) or (base_offset is None):
return 0
return target_offset - base_offset
|
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement boolean_operator parenthesized_expression comparison_operator identifier none parenthesized_expression comparison_operator identifier none block return_statement integer return_statement binary_operator identifier identifier
|
If the offset is unknown, return 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.