code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def coordinates(self, x, y):
state = self.state
return state.mt.coord_from_area(x, y, state.lat, state.lon, state.width, state.ground_width) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | return coordinates of a pixel in the map |
def summary(self):
out = {}
for bench in self.runner.runned:
key = self.key(bench)
runs = {}
for method, results in bench.results.items():
mean = results.total / bench.times
name = bench.label_for(method)
runs[method] = {
'name': name,
'total': results.total,
'mean': mean
}
out[key] = {
'name': bench.label,
'times': bench.times,
'runs': runs
}
return out | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier expression_statement assignment subscript identifier identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier return_statement identifier | Compute the execution summary |
def clear(self):
self._undos.clear()
self._redos.clear()
self._savepoint = None
self._receiver = self._undos | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier attribute identifier identifier | Clear the undo list. |
def from_call(cls, call_node):
callcontext = contextmod.CallContext(call_node.args, call_node.keywords)
return cls(callcontext) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier return_statement call identifier argument_list identifier | Get a CallSite object from the given Call node. |
def choose_args(metadata, config):
return dict(
connect_args=choose_connect_args(metadata, config),
echo=config.echo,
max_overflow=config.max_overflow,
pool_size=config.pool_size,
pool_timeout=config.pool_timeout,
) | module function_definition identifier parameters identifier identifier block return_statement call identifier argument_list keyword_argument identifier call identifier argument_list 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 | Choose database connection arguments. |
def convert_to_ik_angles(self, joints):
if len(joints) != len(self.motors):
raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors)))
raw_joints = [(j + m.offset) * (1 if m.direct else -1)
for j, m in zip(joints, self.motors)]
raw_joints *= self._reversed
return [0] + [deg2rad(j) for j in raw_joints] + [0] | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list attribute identifier identifier expression_statement assignment identifier list_comprehension binary_operator parenthesized_expression binary_operator identifier attribute identifier identifier parenthesized_expression conditional_expression integer attribute identifier identifier unary_operator integer for_in_clause pattern_list identifier identifier call identifier argument_list identifier attribute identifier identifier expression_statement augmented_assignment identifier attribute identifier identifier return_statement binary_operator binary_operator list integer list_comprehension call identifier argument_list identifier for_in_clause identifier identifier list integer | Convert from poppy representation to IKPY internal representation. |
def updateFromKwargs(self, properties, kwargs, collector, **unused):
properties[self.name] = self.getFromKwargs(kwargs) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier attribute identifier identifier call attribute identifier identifier argument_list identifier | Primary entry point to turn 'kwargs' into 'properties |
def visit_Name(self, node: AST, dfltChaining: bool = True) -> str:
return node.id | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier true type identifier block return_statement attribute identifier identifier | Return `node`s id. |
def session(self):
engine = self.engine
connection = engine.connect()
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=True, bind=engine))
yield db_session
db_session.close()
connection.close() | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call identifier argument_list keyword_argument identifier false keyword_argument identifier true keyword_argument identifier identifier expression_statement yield identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Creates a context with an open SQLAlchemy session. |
def setup_temp_logger(log_level='error'):
if is_temp_logging_configured():
logging.getLogger(__name__).warning(
'Temporary logging is already configured'
)
return
if log_level is None:
log_level = 'warning'
level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)
handler = None
for handler in logging.root.handlers:
if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER):
continue
if not hasattr(handler, 'stream'):
continue
if handler.stream is sys.stderr:
break
else:
handler = LOGGING_TEMP_HANDLER
handler.setLevel(level)
formatter = logging.Formatter(
'[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S'
)
handler.setFormatter(formatter)
logging.root.addHandler(handler)
if LOGGING_NULL_HANDLER is not None:
LOGGING_NULL_HANDLER.sync_with_handlers([handler])
else:
logging.getLogger(__name__).debug(
'LOGGING_NULL_HANDLER is already None, can\'t sync messages '
'with it'
)
__remove_null_logging_handler()
global __TEMP_LOGGING_CONFIGURED
__TEMP_LOGGING_CONFIGURED = True | module function_definition identifier parameters default_parameter identifier string string_start string_content string_end block if_statement call identifier argument_list block expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end return_statement if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier none for_statement identifier attribute attribute identifier identifier identifier block if_statement comparison_operator identifier tuple identifier identifier block continue_statement if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block continue_statement if_statement comparison_operator attribute identifier identifier attribute identifier identifier block break_statement else_clause block expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list list identifier else_clause block expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end expression_statement call identifier argument_list global_statement identifier expression_statement assignment identifier true | Setup the temporary console logger |
def iso_string_to_python_datetime(
isostring: str) -> Optional[datetime.datetime]:
if not isostring:
return None
return dateutil.parser.parse(isostring) | module function_definition identifier parameters typed_parameter identifier type identifier type generic_type identifier type_parameter type attribute identifier identifier block if_statement not_operator identifier block return_statement none return_statement call attribute attribute identifier identifier identifier argument_list identifier | Takes an ISO-8601 string and returns a ``datetime``. |
def children(self, vertex):
return [self.head(edge) for edge in self.out_edges(vertex)] | module function_definition identifier parameters identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list identifier | Return the list of immediate children of the given vertex. |
def connect(self):
logger.info("Connecting to %s:%s", self._host, self._port)
reader, writer = yield from asyncio.open_connection(
self._host, self._port, loop=self._loop)
self._ioloop_future = ensure_future(
self._ioloop(reader, writer), loop=self._loop)
logger.info("Connected") | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier yield call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list call attribute identifier identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Connect to the controller and start processing responses. |
def find_by_b64id(self, _id, **kwargs):
return self.find_one({"_id": ObjectId(base64.b64decode(_id))}, **kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list identifier dictionary_splat identifier | Pass me a base64-encoded ObjectId |
def reply_bytes(self, request):
flags = struct.pack("<i", self._flags)
cursor_id = struct.pack("<q", self._cursor_id)
starting_from = struct.pack("<i", self._starting_from)
number_returned = struct.pack("<i", len(self._docs))
reply_id = random.randint(0, 1000000)
response_to = request.request_id
data = b''.join([flags, cursor_id, starting_from, number_returned])
data += b''.join([bson.BSON.encode(doc) for doc in self._docs])
message = struct.pack("<i", 16 + len(data))
message += struct.pack("<i", reply_id)
message += struct.pack("<i", response_to)
message += struct.pack("<i", OP_REPLY)
return message + data | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list integer integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_end identifier argument_list list identifier identifier identifier identifier expression_statement augmented_assignment identifier call attribute string string_start string_end identifier argument_list list_comprehension call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end binary_operator integer call identifier argument_list identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement augmented_assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement binary_operator identifier identifier | Take a `Request` and return an OP_REPLY message as bytes. |
def GetMethodConfig(self, method):
method_config = self._method_configs.get(method)
if method_config:
return method_config
func = getattr(self, method, None)
if func is None:
raise KeyError(method)
method_config = getattr(func, 'method_config', None)
if method_config is None:
raise KeyError(method)
self._method_configs[method] = config = method_config()
return config | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block return_statement identifier expression_statement assignment identifier call identifier argument_list identifier identifier none if_statement comparison_operator identifier none block raise_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement comparison_operator identifier none block raise_statement call identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier assignment identifier call identifier argument_list return_statement identifier | Returns service cached method config for given method. |
def copy(self):
attrs = {k: self.__dict__[k].copy() for k in self.containers}
attrs.update({k: cp.deepcopy(self.__dict__[k]) for k in self.shared})
return self.__class__(**attrs) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary_comprehension pair identifier call attribute subscript attribute identifier identifier identifier identifier argument_list for_in_clause identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list dictionary_comprehension pair identifier call attribute identifier identifier argument_list subscript attribute identifier identifier identifier for_in_clause identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Returns a copy of the object. |
def generate(size, output, schema):
pii_data = randomnames.NameList(size)
if schema is not None:
raise NotImplementedError
randomnames.save_csv(
pii_data.names,
[f.identifier for f in pii_data.SCHEMA.fields],
output) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block raise_statement identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute attribute identifier identifier identifier identifier | Generate fake PII data for testing |
def make_connector(self, app=None, bind=None):
return _EngineConnector(self, self.get_app(app), bind) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block return_statement call identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier | Creates the connector for a given state and bind. |
def _visible(self, element):
if element.name in self._disallowed_names:
return False
elif re.match(u'<!--.*-->', six.text_type(element.extract())):
return False
return True | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement false elif_clause call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list call attribute identifier identifier argument_list block return_statement false return_statement true | Used to filter text elements that have invisible text on the page. |
def update_vcl(self, service_id, version_number, name_key, **kwargs):
body = self._formdata(kwargs, FastlyVCL.FIELDS)
content = self._fetch("/service/%s/version/%d/vcl/%s" % (service_id, version_number, name_key), method="PUT", body=body)
return FastlyVCL(self, content) | module function_definition identifier parameters identifier identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call identifier argument_list identifier identifier | Update the uploaded VCL for a particular service and version. |
def _write_scalar(self, name:str, scalar_value, iteration:int)->None:
"Writes single scalar value to Tensorboard."
tag = self.metrics_root + name
self.tbwriter.add_scalar(tag=tag, scalar_value=scalar_value, global_step=iteration) | module function_definition identifier parameters identifier typed_parameter identifier type identifier identifier typed_parameter identifier type identifier type none block expression_statement string string_start string_content string_end expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Writes single scalar value to Tensorboard. |
def _spawn_kafka_connection_thread(self):
self.logger.debug("Spawn kafka connection thread")
self.kafka_connected = False
self._kafka_thread = Thread(target=self._setup_kafka)
self._kafka_thread.setDaemon(True)
self._kafka_thread.start() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier false expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list true expression_statement call attribute attribute identifier identifier identifier argument_list | Spawns a kafka connection thread |
def r(self):
r_args = [_to_r(self.args), _to_r(self.kwargs)]
r_args = ",".join([x for x in r_args if x != ""])
return "{}({})".format(self.name, r_args) | module function_definition identifier parameters identifier block expression_statement assignment identifier list call identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator identifier string string_start string_end return_statement call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier | Convert this GGStatement into its R equivalent expression |
def _repr_html_(self, **kwargs):
from jinja2 import Template
from markdown import markdown as convert_markdown
extensions = [
'markdown.extensions.extra',
'markdown.extensions.admonition'
]
return convert_markdown(self.markdown, extensions) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block import_from_statement dotted_name identifier dotted_name identifier import_from_statement dotted_name identifier aliased_import dotted_name identifier identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end return_statement call identifier argument_list attribute identifier identifier identifier | Produce HTML for Jupyter Notebook |
def copy_image_from_url(url, cache_dir=None, use_cache=True):
return cache_image_data(cache_dir, hashlib.sha1(url).hexdigest(), ImgurUploader().upload, url, use_cache=use_cache) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier true block return_statement call identifier argument_list identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list attribute call identifier argument_list identifier identifier keyword_argument identifier identifier | Copy image from given URL and return upload metadata. |
def remove_xml_element(name, tree):
remove = tree.findall(
".//{{http://soap.sforce.com/2006/04/metadata}}{}".format(name)
)
if not remove:
return tree
parent_map = {c: p for p in tree.iter() for c in p}
for elem in remove:
parent = parent_map[elem]
parent.remove(elem)
return tree | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier if_statement not_operator identifier block return_statement identifier expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause identifier call attribute identifier identifier argument_list for_in_clause identifier identifier for_statement identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Removes XML elements from an ElementTree content tree |
def echo(topic_name, num_print=None, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT):
class PrintWithCount(object):
def __init__(self, out):
self._printed = 0
self._out = out
def print_and_increment(self, msg):
self._out.write('{}\n'.format(msg))
self._printed += 1
def get_count(self):
return self._printed
counter = PrintWithCount(out)
sub = jps.Subscriber(
topic_name, counter.print_and_increment, host=host, sub_port=sub_port)
try:
while num_print is None or counter.get_count() < num_print:
sub.spin_once()
time.sleep(0.0001)
except KeyboardInterrupt:
pass | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier attribute identifier identifier default_parameter identifier call attribute attribute identifier identifier identifier argument_list default_parameter identifier attribute identifier identifier block class_definition identifier argument_list identifier block function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier identifier function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier integer function_definition identifier parameters identifier block return_statement attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier try_statement block while_statement boolean_operator comparison_operator identifier none comparison_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list float except_clause identifier block pass_statement | print the data for the given topic forever |
def post_parse(self):
if self.cache and not self.cache_loaded:
self.cache_writer_cls(self.file_name, self.wavefront).write() | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier not_operator attribute identifier identifier block expression_statement call attribute call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier argument_list | Called after parsing is done |
def combine_sets(*sets):
combined = set()
for s in sets:
combined.update(s)
return combined | module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Combine multiple sets to create a single larger set. |
def build_suite(args):
loader = Loader()
if len(args.files) == 0 or args.files[0] == "-":
suite = loader.load_suite_from_stdin()
else:
suite = loader.load(args.files)
return suite | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list if_statement boolean_operator comparison_operator call identifier argument_list attribute identifier identifier integer comparison_operator subscript attribute identifier identifier integer string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Build a test suite by loading TAP files or a TAP stream. |
def remove_module_load(state_dict):
new_state_dict = OrderedDict()
for k, v in state_dict.items(): new_state_dict[k[7:]] = v
return new_state_dict | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier subscript identifier slice integer identifier return_statement identifier | create new OrderedDict that does not contain `module.` |
def where(self, **overrides):
route_data = self.route.copy()
route_data.update(overrides)
return self.__class__(**route_data) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Creates a new route, based on the current route, with the specified overrided values |
def _buildElementNsmap(using_elements):
thisMap = {}
for e in using_elements:
thisMap[e.attrib['prefix']] = e.attrib['namespace']
return thisMap | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment subscript identifier subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end return_statement identifier | build a namespace map for an ADMX element |
def scores(self, result, add_new_line=True):
if result.goalsHomeTeam > result.goalsAwayTeam:
homeColor, awayColor = (self.colors.WIN, self.colors.LOSE)
elif result.goalsHomeTeam < result.goalsAwayTeam:
homeColor, awayColor = (self.colors.LOSE, self.colors.WIN)
else:
homeColor = awayColor = self.colors.TIE
click.secho('%-25s %2s' % (result.homeTeam, result.goalsHomeTeam),
fg=homeColor, nl=False)
click.secho(" vs ", nl=False)
click.secho('%2s %s' % (result.goalsAwayTeam,
result.awayTeam.rjust(25)), fg=awayColor,
nl=add_new_line) | module function_definition identifier parameters identifier identifier default_parameter identifier true block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment pattern_list identifier identifier tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier elif_clause comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment pattern_list identifier identifier tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier else_clause block expression_statement assignment identifier assignment identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier false expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute attribute identifier identifier identifier argument_list integer keyword_argument identifier identifier keyword_argument identifier identifier | Prints out the scores in a pretty format |
def write_spelling(token_folder, spelling_file):
token_pattern = r'[a-z]{3,}'
tokens = []
for base, dirlist, fnlist in os.walk(token_folder):
for fn in fnlist:
fp = os.path.join(base, fn)
with open(fp) as f:
toks = re.findall(token_pattern, f.read())
tokens.extend(toks)
token_ranked, _ = zip(*Counter(tokens).most_common())
with open(spelling_file, 'w') as f:
f.write('\n'.join(token_ranked)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier block for_statement identifier identifier block 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 identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list list_splat call attribute call identifier argument_list identifier identifier argument_list 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 expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | Generate the spelling correction file form token_folder and save to spelling_file |
def _affine_mult(c:FlowField,m:AffineMatrix)->FlowField:
"Multiply `c` by `m` - can adjust for rectangular shaped `c`."
if m is None: return c
size = c.flow.size()
h,w = c.size
m[0,1] *= h/w
m[1,0] *= w/h
c.flow = c.flow.view(-1,2)
c.flow = torch.addmm(m[:2,2], c.flow, m[:2,:2].t()).view(size)
return c | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement string string_start string_content string_end if_statement comparison_operator identifier none block return_statement identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement augmented_assignment subscript identifier integer integer binary_operator identifier identifier expression_statement augmented_assignment subscript identifier integer integer binary_operator identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list unary_operator integer integer expression_statement assignment attribute identifier identifier call attribute call attribute identifier identifier argument_list subscript identifier slice integer integer attribute identifier identifier call attribute subscript identifier slice integer slice integer identifier argument_list identifier argument_list identifier return_statement identifier | Multiply `c` by `m` - can adjust for rectangular shaped `c`. |
def put_device(self, pin, state, momentary=None, times=None, pause=None):
url = self.base_url + '/device'
payload = {
"pin": pin,
"state": state
}
if momentary is not None:
payload["momentary"] = momentary
if times is not None:
payload["times"] = times
if pause is not None:
payload["pause"] = pause
try:
r = requests.put(url, json=payload, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier integer return_statement call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block raise_statement call attribute identifier identifier argument_list identifier | Actuate a device pin |
def to_json_payload(self, data_rows):
num_rows = len(data_rows)
num_page = self.num_page
num_rows_page = self.num_rows_page
pages = num_rows / num_rows_page
pages += divmod(num_rows, num_rows_page)[1] and 1 or 0
start = (num_page - 1) * num_rows_page
end = num_page * num_rows_page
payload = {"page": num_page,
"total": pages,
"records": num_rows,
"rows": data_rows[start:end]}
return json.dumps(payload) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement augmented_assignment identifier boolean_operator boolean_operator subscript call identifier argument_list identifier identifier integer integer integer expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier integer identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end subscript identifier slice identifier identifier return_statement call attribute identifier identifier argument_list identifier | Returns the json payload |
def _found_barcode(self, record, sample, barcode=None):
assert record.id == self.current_record['sequence_name']
self.current_record['sample'] = sample | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block assert_statement comparison_operator attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier | Hook called when barcode is found |
def dict(self):
post_dict = {
'id': self.id,
'link': self.link,
'permalink': self.permalink,
'content_type': self.content_type,
'slug': self.slug,
'updated': self.updated,
'published': self.published,
'title': self.title,
'description': self.description,
'author': self.author,
'categories': self.categories[1:-1].split(',') if self.categories else None,
'summary': self.summary,
}
if self.attributes:
attributes = simplejson.loads(self.attributes)
post_dict.update(attributes)
return post_dict | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end conditional_expression call attribute subscript attribute identifier identifier slice integer unary_operator integer identifier argument_list string string_start string_content string_end attribute identifier identifier none pair string string_start string_content string_end attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Returns dictionary of post fields and attributes |
def sitegate_view(*args_dec, **kwargs_dec):
if len(args_dec):
return signup_view(signin_view(redirect_signedin(*args_dec, **kwargs_dec)))
signin = signin_view(**kwargs_dec)
signup = signup_view(**kwargs_dec)
return lambda *args, **kwargs: signup(signin(redirect_signedin(*args, **kwargs))) | module function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement call identifier argument_list identifier block return_statement call identifier argument_list call identifier argument_list call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement assignment identifier call identifier argument_list dictionary_splat identifier return_statement lambda lambda_parameters list_splat_pattern identifier dictionary_splat_pattern identifier call identifier argument_list call identifier argument_list call identifier argument_list list_splat identifier dictionary_splat identifier | Decorator to mark views used both for signup & sign in. |
def _convert_to_bytes(type_name, value):
int_types = {'uint8_t': 'B', 'int8_t': 'b', 'uint16_t': 'H', 'int16_t': 'h', 'uint32_t': 'L', 'int32_t': 'l'}
type_name = type_name.lower()
if type_name not in int_types and type_name not in ['string', 'binary']:
raise ArgumentError('Type must be a known integer type, integer type array, string', known_integers=int_types.keys(), actual_type=type_name)
if type_name == 'string':
bytevalue = bytes(value)
elif type_name == 'binary':
bytevalue = bytes(value)
else:
bytevalue = struct.pack("<%s" % int_types[type_name], value)
return bytevalue | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end 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 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 expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end subscript identifier identifier identifier return_statement identifier | Convert a typed value to a binary array |
async def update(self, db=None, data=None):
db = db or self.db
if data:
self.import_data(data)
data = self.prepare_data()
else:
data = self.export_data(native=True)
if self.primary_key not in data or data[self.primary_key] is None:
raise Exception('Missing object primary key')
query = {self.primary_key: self.pk}
for i in self.connection_retries():
try:
result = await db[self.get_collection_name()].find_one_and_replace(
filter=query,
replacement=data,
return_document=ReturnDocument.AFTER
)
if result:
updated_obj = self.create_model(result)
updated_obj._db = db
asyncio.ensure_future(post_save.send(
sender=self.__class__,
db=db,
instance=updated_obj,
created=False)
)
return updated_obj
return None
except ConnectionFailure as ex:
exceed = await self.check_reconnect_tries_and_wait(i, 'update')
if exceed:
raise ex | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier attribute identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier true if_statement boolean_operator comparison_operator attribute identifier identifier identifier comparison_operator subscript identifier attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary pair attribute identifier identifier attribute identifier identifier for_statement identifier call attribute identifier identifier argument_list block try_statement block expression_statement assignment identifier await call attribute subscript identifier call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier false return_statement identifier return_statement none except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list identifier string string_start string_content string_end if_statement identifier block raise_statement identifier | Update the entire document by replacing its content with new data, retaining its primary key |
def release_node(self, node):
try:
node._release_script(keys=[self.resource], args=[self.lock_key])
except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutError):
pass | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list keyword_argument identifier list attribute identifier identifier keyword_argument identifier list attribute identifier identifier except_clause tuple attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier block pass_statement | release a single redis node |
def fill_phenotype_label(self,inplace=False):
def _get_phenotype(d):
vals = [k for k,v in d.items() if v == 1]
return np.nan if len(vals) == 0 else vals[0]
if inplace:
if self.shape[0] == 0: return self
self['phenotype_label'] = self.apply(lambda x: _get_phenotype(x['phenotype_calls']),1)
return
fixed = self.copy()
if fixed.shape[0] == 0: return fixed
fixed['phenotype_label'] = fixed.apply(lambda x: _get_phenotype(x['phenotype_calls']),1)
return fixed | module function_definition identifier parameters identifier default_parameter identifier false block function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier integer return_statement conditional_expression attribute identifier identifier comparison_operator call identifier argument_list identifier integer subscript identifier integer if_statement identifier block if_statement comparison_operator subscript attribute identifier identifier integer integer block return_statement identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list lambda lambda_parameters identifier call identifier argument_list subscript identifier string string_start string_content string_end integer return_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator subscript attribute identifier identifier integer integer block return_statement identifier expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list lambda lambda_parameters identifier call identifier argument_list subscript identifier string string_start string_content string_end integer return_statement identifier | Set the phenotype_label column according to our rules for mutual exclusion |
def register(parser):
cmd_login.register(parser)
cmd_logout.register(parser)
cmd_switch.register(parser)
cmd_profiles.register(parser) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Register profile commands with the given parser. |
def endline_semicolon_check(self, original, loc, tokens):
return self.check_strict("semicolon at end of line", original, loc, tokens) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier | Check for semicolons at the end of lines. |
def get(name):
linkcheckers = get_enabled(ENTRYPOINT, current_app)
linkcheckers.update(no_check=NoCheckLinkchecker)
selected_linkchecker = linkcheckers.get(name)
if not selected_linkchecker:
default_linkchecker = current_app.config.get(
'LINKCHECKING_DEFAULT_LINKCHECKER')
selected_linkchecker = linkcheckers.get(default_linkchecker)
if not selected_linkchecker:
log.error('No linkchecker found ({} requested and no fallback)'.format(
name))
return selected_linkchecker | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator 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 call attribute identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Get a linkchecker given its name or fallback on default |
def _sector_and_sz_itr(self, elf, data_start):
for entry_start in itertools.count(data_start, self.FLASH_SECTORS_STRUCT_SIZE):
data = elf.read(entry_start, self.FLASH_SECTORS_STRUCT_SIZE)
size, start = struct.unpack(self.FLASH_SECTORS_STRUCT, data)
start_and_size = start, size
if start_and_size == (self.SECTOR_END, self.SECTOR_END):
return
yield start_and_size | module function_definition identifier parameters identifier identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier expression_list identifier identifier if_statement comparison_operator identifier tuple attribute identifier identifier attribute identifier identifier block return_statement expression_statement yield identifier | Iterator which returns starting address and sector size |
def count(self):
if self._primary_keys is None:
return self.queryset.count()
else:
return len(self.pks) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement call attribute attribute identifier identifier identifier argument_list else_clause block return_statement call identifier argument_list attribute identifier identifier | Return a count of instances. |
def sort_by_speedup(self, reverse=True):
self._confs.sort(key=lambda c: c.speedup, reverse=reverse)
return self | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier lambda lambda_parameters identifier attribute identifier identifier keyword_argument identifier identifier return_statement identifier | Sort the configurations in place. items with highest speedup come first |
def no_operation(self, onerror = None):
request.NoOperation(display = self.display,
onerror = onerror) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier | Do nothing but send a request to the server. |
def call_env_updated(cls, kb_app,
sphinx_app: Sphinx,
sphinx_env: BuildEnvironment):
for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EU):
callback(kb_app, sphinx_app, sphinx_env) | module function_definition identifier parameters identifier identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block for_statement identifier call attribute identifier identifier argument_list identifier attribute identifier identifier block expression_statement call identifier argument_list identifier identifier identifier | On the env-updated event, do callbacks |
def do_encode(cls, obj):
if isinstance(obj, ConjureBeanType):
return cls.encode_conjure_bean_type(obj)
elif isinstance(obj, ConjureUnionType):
return cls.encode_conjure_union_type(obj)
elif isinstance(obj, ConjureEnumType):
return obj.value
elif isinstance(obj, list):
return list(map(cls.do_encode, obj))
elif isinstance(obj, dict):
return {cls.do_encode(key): cls.do_encode(value)
for key, value in obj.items()}
else:
return cls.encode_primitive(obj) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block return_statement attribute identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list call identifier argument_list attribute identifier identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement dictionary_comprehension pair call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list else_clause block return_statement call attribute identifier identifier argument_list identifier | Encodes the passed object into json |
def _print_throbber(self):
self._print('[')
for position in range(self._bar_width):
self._print('O' if position == self._throbber_index else ' ')
self._print(']')
self._throbber_index = next(self._throbber_iter) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list conditional_expression string string_start string_content string_end comparison_operator identifier attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier | Print an indefinite progress bar. |
def fnv(data, hval_init, fnv_prime, fnv_size):
assert isinstance(data, bytes)
hval = hval_init
for byte in data:
hval = (hval * fnv_prime) % fnv_size
hval = hval ^ _get_byte(byte)
return hval | module function_definition identifier parameters identifier identifier identifier identifier block assert_statement call identifier argument_list identifier identifier expression_statement assignment identifier identifier for_statement identifier identifier block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier return_statement identifier | Core FNV hash algorithm used in FNV0 and FNV1. |
def _scheduling_block_config(num_blocks=5, start_sbi_id=0, start_pb_id=0,
project='sip'):
pb_id = start_pb_id
for sb_id, sbi_id in _scheduling_block_ids(num_blocks, start_sbi_id,
project):
sub_array_id = 'subarray-{:02d}'.format(random.choice(range(5)))
config = dict(id=sbi_id,
sched_block_id=sb_id,
sub_array_id=sub_array_id,
processing_blocks=_generate_processing_blocks(pb_id))
pb_id += len(config['processing_blocks'])
yield config | module function_definition identifier parameters default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier identifier for_statement pattern_list identifier identifier call identifier argument_list identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list call identifier argument_list integer expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier call identifier argument_list identifier expression_statement augmented_assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement yield identifier | Return a Scheduling Block Configuration dictionary |
def duplicate(self):
a_per = self.analysis_period.duplicate() if self.analysis_period else None
return self.__class__(self.data_type, self.unit,
a_per, deepcopy(self.metadata)) | module function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression call attribute attribute identifier identifier identifier argument_list attribute identifier identifier none return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier call identifier argument_list attribute identifier identifier | Return a copy of the header. |
def convert_to_btc(self, amount, currency):
if isinstance(amount, Decimal):
use_decimal = True
else:
use_decimal = self._force_decimal
url = 'https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency)
response = requests.get(url)
if response.status_code == 200:
data = response.json()
price = data.get('bpi').get(currency, {}).get('rate_float', None)
if price:
if use_decimal:
price = Decimal(price)
try:
converted_btc = amount/price
return converted_btc
except TypeError:
raise DecimalFloatMismatchError("convert_to_btc requires amount parameter is of type Decimal when force_decimal=True")
raise RatesNotAvailableError("BitCoin Rates Source Not Ready For Given date") | module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier true else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list identifier dictionary identifier argument_list string string_start string_content string_end none if_statement identifier block if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier binary_operator identifier identifier return_statement identifier except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list string string_start string_content string_end | Convert X amount to Bit Coins |
def get(self, eid):
data = self._http_req('connections/%u' % eid)
self.debug(0x01, data['decoded'])
return data['decoded'] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list integer subscript identifier string string_start string_content string_end return_statement subscript identifier string string_start string_content string_end | Returns a dict with the complete record of the entity with the given eID |
def _get_machine_info(parallel, sys_config, dirs, config):
if parallel.get("queue") and parallel.get("scheduler"):
sched_info_dict = {
"slurm": _slurm_info,
"torque": _torque_info,
"sge": _sge_info
}
if parallel["scheduler"].lower() in sched_info_dict:
try:
return sched_info_dict[parallel["scheduler"].lower()](parallel.get("queue", ""))
except:
logger.exception("Couldn't get machine information from resource query function for queue "
"'{0}' on scheduler \"{1}\"; "
"submitting job to queue".format(parallel.get("queue", ""), parallel["scheduler"]))
else:
logger.info("Resource query function not implemented for scheduler \"{0}\"; "
"submitting job to queue".format(parallel["scheduler"]))
from bcbio.distributed import prun
with prun.start(parallel, [[sys_config]], config, dirs) as run_parallel:
return run_parallel("machine_info", [[sys_config]]) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement comparison_operator call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier block try_statement block return_statement call subscript identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end except_clause block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content escape_sequence escape_sequence string_end string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end subscript identifier string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content escape_sequence escape_sequence string_end string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end import_from_statement dotted_name identifier identifier dotted_name identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier list list identifier identifier identifier as_pattern_target identifier block return_statement call identifier argument_list string string_start string_content string_end list list identifier | Get machine resource information from the job scheduler via either the command line or the queue. |
def create_rule(self):
return BlockRule(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | module function_definition identifier parameters identifier block return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | Get an instance of block rule services facade. |
def register_pivot_wavelength(self, telescope, band, wlen):
if (telescope, band) in self._pivot_wavelengths:
raise AlreadyDefinedError('pivot wavelength for %s/%s already '
'defined', telescope, band)
self._note(telescope, band)
self._pivot_wavelengths[telescope,band] = wlen
return self | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator tuple identifier identifier attribute identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier identifier return_statement identifier | Register precomputed pivot wavelengths. |
def get(cls, id):
client = cls._new_api_client()
return client.make_request(cls, 'get', url_params={'id': id}) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end identifier | Look up one Union object |
def reroot_graph(G: nx.DiGraph, node: str) -> nx.DiGraph:
G = G.copy()
for n, successors in list(nx.bfs_successors(G, source=node)):
for s in successors:
G.add_edge(s, n, **G.edges[n, s])
G.remove_edge(n, s)
return G | module function_definition identifier parameters typed_parameter identifier type attribute identifier identifier typed_parameter identifier type identifier type attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier dictionary_splat subscript attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier return_statement identifier | Return a copy of the graph rooted at the given node |
def json_data(self, name, default=None):
value = self.get(name)
if value is Missing.Value:
return default
return value | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement identifier return_statement identifier | Get a JSON compatible value of the field |
def returns(self) -> T.Optional[DocstringReturns]:
try:
return next(
DocstringReturns.from_meta(meta)
for meta in self.meta
if meta.args[0] in {"return", "returns", "yield", "yields"}
)
except StopIteration:
return None | module function_definition identifier parameters identifier type subscript attribute identifier identifier identifier block try_statement block return_statement call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator subscript attribute identifier identifier integer set 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 except_clause identifier block return_statement none | Return return information indicated in docstring. |
def pip_list(self, name=None, prefix=None, abspath=True):
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name:
prefix = self.get_prefix_envname(name)
pip_command = os.sep.join([prefix, 'bin', 'python'])
cmd_list = [pip_command, PIP_LIST_SCRIPT]
process_worker = ProcessWorker(cmd_list, pip=True, parse=True,
callback=self._pip_list,
extra_kwargs={'prefix': prefix})
process_worker.sig_finished.connect(self._start)
self._queue.append(process_worker)
self._start()
return process_worker | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier true block if_statement boolean_operator parenthesized_expression boolean_operator identifier identifier not_operator parenthesized_expression boolean_operator identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list list identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list identifier identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier true keyword_argument identifier true keyword_argument identifier attribute identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Get list of pip installed packages. |
def connect(self):
self._connect()
logger.debug('Connected to Deluge, detecting daemon version')
self._detect_deluge_version()
logger.debug('Daemon version {} detected, logging in'.format(self.deluge_version))
if self.deluge_version == 2:
result = self.call('daemon.login', self.username, self.password, client_version='deluge-client')
else:
result = self.call('daemon.login', self.username, self.password)
logger.debug('Logged in with value %r' % result)
self.connected = True | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier true | Connects to the Deluge instance |
async def read(cls, boot_source, id):
if isinstance(boot_source, int):
boot_source_id = boot_source
elif isinstance(boot_source, BootSource):
boot_source_id = boot_source.id
else:
raise TypeError(
"boot_source must be a BootSource or int, not %s"
% type(boot_source).__name__)
data = await cls._handler.read(boot_source_id=boot_source_id, id=id)
return cls(data, {"boot_source_id": boot_source_id}) | module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute call identifier argument_list identifier identifier expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier return_statement call identifier argument_list identifier dictionary pair string string_start string_content string_end identifier | Get `BootSourceSelection` by `id`. |
def getmodeldefinition(self, storageobject, required=False):
if isinstance(storageobject, StorageTableModel):
definitionlist = [definition for definition in self._modeldefinitions if definition['modelname'] == storageobject.__class__.__name__]
elif isinstance(storageobject, StorageTableQuery):
storagemodel = storageobject._storagemodel
definitionlist = [definition for definition in self._modeldefinitions if definition['modelname'] == storagemodel.__class__.__name__]
else:
raise Exception("Argument is not an StorageTableModel nor an StorageTableQuery")
modeldefinition = None
if len(definitionlist) == 1:
modeldefinition = definitionlist[0]
elif len(definitionlist) > 1:
raise ModelRegisteredMoreThanOnceError(storageobject)
if required and modeldefinition is None:
raise ModelNotRegisteredError(storageobject)
return modeldefinition | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier none if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier subscript identifier integer elif_clause comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list identifier if_statement boolean_operator identifier comparison_operator identifier none block raise_statement call identifier argument_list identifier return_statement identifier | find modeldefinition for StorageTableModel or StorageTableQuery |
def input_files(self):
return self.workspace.mets.find_files(fileGrp=self.input_file_grp, pageId=self.page_id) | module function_definition identifier parameters identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | List the input files |
def _first_and_last_element(arr):
if isinstance(arr, np.ndarray) or hasattr(arr, 'data'):
data = arr.data if sparse.issparse(arr) else arr
return data.flat[0], data.flat[-1]
else:
return arr[0, 0], arr[-1, -1] | module function_definition identifier parameters identifier block if_statement boolean_operator call identifier argument_list identifier attribute identifier identifier call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier conditional_expression attribute identifier identifier call attribute identifier identifier argument_list identifier identifier return_statement expression_list subscript attribute identifier identifier integer subscript attribute identifier identifier unary_operator integer else_clause block return_statement expression_list subscript identifier integer integer subscript identifier unary_operator integer unary_operator integer | Returns first and last element of numpy array or sparse matrix. |
def complete_pool_name(arg):
search_string = '^'
if arg is not None:
search_string += arg
res = Pool.search({
'operator': 'regex_match',
'val1': 'name',
'val2': search_string
})
ret = []
for p in res['result']:
ret.append(p.name)
return ret | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement augmented_assignment identifier identifier expression_statement assignment identifier 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 pair string string_start string_content string_end identifier expression_statement assignment identifier list for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Returns list of matching pool names |
def _is_cow(path):
dirname = os.path.dirname(path)
return 'C' not in __salt__['file.lsattr'](dirname)[path] | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement comparison_operator string string_start string_content string_end subscript call subscript identifier string string_start string_content string_end argument_list identifier identifier | Check if the subvolume is copy on write |
def _init_kind_converter(self):
from ..utils import invert_dict
kinds = self.session.query(Kind).all()
self._kind_id_to_name = {
kind.id: kind.name for kind in kinds
}
self._kind_name_to_id = invert_dict(self._kind_id_to_name) | module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list expression_statement assignment attribute identifier identifier dictionary_comprehension pair attribute identifier identifier attribute identifier identifier for_in_clause identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier | Make a dictionary mapping kind ids to the names. |
def unicode_right(s, width):
i = len(s)
j = 0
for ch in reversed(s):
j += __unicode_width_mapping[east_asian_width(ch)]
if width < j:
break
i -= 1
return s[i:] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier integer for_statement identifier call identifier argument_list identifier block expression_statement augmented_assignment identifier subscript identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier block break_statement expression_statement augmented_assignment identifier integer return_statement subscript identifier slice identifier | Cut unicode string from right to fit a given width. |
def deregister_entity_from_group(self, entity, group):
if entity in self._entities:
if entity in self._groups[group]:
self._groups[group].remove(entity)
else:
raise UnmanagedEntityError(entity) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block if_statement comparison_operator identifier subscript attribute identifier identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier else_clause block raise_statement call identifier argument_list identifier | Removes entity from group |
def validate_custom_interpreters_list(self):
custom_list = self.get_option('custom_interpreters_list')
valid_custom_list = []
for value in custom_list:
if (osp.isfile(value) and programs.is_python_interpreter(value)
and value != get_python_executable()):
valid_custom_list.append(value)
self.set_option('custom_interpreters_list', valid_custom_list) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block if_statement parenthesized_expression boolean_operator boolean_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier comparison_operator identifier call identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Check that the used custom interpreters are still valid. |
def _echo_byte(self, byte):
if byte == '\n':
self.send_buffer += '\r'
if self.telnet_echo_password:
self.send_buffer += '*'
else:
self.send_buffer += byte | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content escape_sequence string_end block expression_statement augmented_assignment attribute identifier identifier string string_start string_content escape_sequence string_end if_statement attribute identifier identifier block expression_statement augmented_assignment attribute identifier identifier string string_start string_content string_end else_clause block expression_statement augmented_assignment attribute identifier identifier identifier | Echo a character back to the client and convert LF into CR\LF. |
def push_script(self, scriptable, script, callback=None):
if script in self.threads:
self.threads[script].finish()
thread = Thread(self.run_script(scriptable, script),
scriptable, callback)
self.new_threads[script] = thread
return thread | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier | Run the script and add it to the list of threads. |
def inputfiles(self, inputtemplate=None):
if isinstance(inputtemplate, InputTemplate):
inputtemplate = inputtemplate.id
for inputfile in self.input:
if not inputtemplate or inputfile.metadata.inputtemplate == inputtemplate:
yield inputfile | module function_definition identifier parameters identifier default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement boolean_operator not_operator identifier comparison_operator attribute attribute identifier identifier identifier identifier block expression_statement yield identifier | Generator yielding all inputfiles for the specified inputtemplate, if ``inputtemplate=None``, inputfiles are returned regardless of inputtemplate. |
def __get_ac_tree(self, ac: model.AssetClass, with_stocks: bool):
output = []
output.append(self.__get_ac_row(ac))
for child in ac.classes:
output += self.__get_ac_tree(child, with_stocks)
if with_stocks:
for stock in ac.stocks:
row = None
if isinstance(stock, Stock):
row = self.__get_stock_row(stock, ac.depth + 1)
elif isinstance(stock, CashBalance):
row = self.__get_cash_row(stock, ac.depth + 1)
output.append(row)
return output | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier typed_parameter identifier type identifier block expression_statement assignment identifier list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier none if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator attribute identifier identifier integer elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | formats the ac tree - entity with child elements |
def Decode(self, attribute, value):
required_type = self._attribute_types.get(attribute, "bytes")
if required_type == "integer":
return rdf_structs.SignedVarintReader(value, 0)[0]
elif required_type == "unsigned_integer":
return rdf_structs.VarintReader(value, 0)[0]
elif required_type == "string":
if isinstance(value, bytes):
return value.decode("utf-8")
else:
return utils.SmartUnicode(value)
else:
return value | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block return_statement subscript call attribute identifier identifier argument_list identifier integer integer elif_clause comparison_operator identifier string string_start string_content string_end block return_statement subscript call attribute identifier identifier argument_list identifier integer integer elif_clause comparison_operator identifier string string_start string_content string_end block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block return_statement call attribute identifier identifier argument_list identifier else_clause block return_statement identifier | Decode the value to the required type. |
def list_bgp_speakers(self, retrieve_all=True, **_params):
return self.list('bgp_speakers', self.bgp_speakers_path, retrieve_all,
**_params) | module function_definition identifier parameters identifier default_parameter identifier true dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier dictionary_splat identifier | Fetches a list of all BGP speakers for a project. |
def start(self):
assert not self.interrupted
for thread in self.worker_threads:
thread.start()
WorkerThread.start(self) | module function_definition identifier parameters identifier block assert_statement not_operator attribute identifier identifier for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier | Starts the coordinator thread and all related worker threads. |
def _jobs():
response = salt.utils.http.query(
"{0}/scheduler/jobs".format(_base_url()),
decode_type='json',
decode=True,
)
jobs = {}
for job in response['dict']:
jobs[job.pop('name')] = job
return jobs | module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier true expression_statement assignment identifier dictionary for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier | Return the currently configured jobs. |
def sweHousesLon(jd, lat, lon, hsys):
hsys = SWE_HOUSESYS[hsys]
hlist, ascmc = swisseph.houses(jd, lat, lon, hsys)
angles = [
ascmc[0],
ascmc[1],
angle.norm(ascmc[0] + 180),
angle.norm(ascmc[1] + 180)
]
return (hlist, angles) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier list subscript identifier integer subscript identifier integer call attribute identifier identifier argument_list binary_operator subscript identifier integer integer call attribute identifier identifier argument_list binary_operator subscript identifier integer integer return_statement tuple identifier identifier | Returns lists with house and angle longitudes. |
def write(self, fd):
print >>fd, self.classHead
for t in self.items:
print >>fd, t
print >>fd, self.classFoot | module function_definition identifier parameters identifier identifier block print_statement chevron identifier attribute identifier identifier for_statement identifier attribute identifier identifier block print_statement chevron identifier identifier print_statement chevron identifier attribute identifier identifier | write out to file descriptor. |
def _to_micros(dur):
if hasattr(dur, 'total_seconds'):
return int(dur.total_seconds() * 10e5)
return dur.microseconds + (dur.seconds + dur.days * 24 * 3600) * 1000000 | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block return_statement call identifier argument_list binary_operator call attribute identifier identifier argument_list float return_statement binary_operator attribute identifier identifier binary_operator parenthesized_expression binary_operator attribute identifier identifier binary_operator binary_operator attribute identifier identifier integer integer integer | Convert duration 'dur' to microseconds. |
def tcp_client(tcp_addr):
family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
for i in range(300):
logging.info("Connecting to: %s, attempt %d", tcp_addr, i)
try:
sock.connect(tcp_addr)
break
except socket.error:
time.sleep(1)
else:
sock.connect(tcp_addr)
logging.info("Connected.")
map_data = read_tcp(sock)
settings_str = read_tcp(sock)
if not settings_str:
raise socket.error("Failed to read")
settings = json.loads(settings_str.decode())
logging.info("Got settings. map_name: %s.", settings["map_name"])
logging.debug("settings: %s", settings)
settings["map_data"] = map_data
return sock, settings | module function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier for_statement identifier call identifier argument_list integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier break_statement except_clause attribute identifier identifier block expression_statement call attribute identifier identifier argument_list integer else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement expression_list identifier identifier | Connect to the tcp server, and return the settings. |
def initialize_vthunder(a10_cfg, device_cfg, client):
vth = a10_cfg.get_vthunder_config()
initialize_interfaces(vth, device_cfg, client)
initialize_dns(vth, device_cfg, client)
initialize_licensing(vth, device_cfg, client)
initialize_sflow(vth, device_cfg, client) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list identifier identifier identifier | Perform initialization of system-wide settings |
def textalign(text, maxlength, align='left'):
if align == 'left':
return text
elif align == 'centre' or align == 'center':
spaces = ' ' * (int((maxlength - len(text)) / 2))
elif align == 'right':
spaces = (maxlength - len(text))
else:
raise ValueError("Invalid alignment specified.")
return spaces + text | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block if_statement comparison_operator identifier string string_start string_content string_end block return_statement identifier elif_clause boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end parenthesized_expression call identifier argument_list binary_operator parenthesized_expression binary_operator identifier call identifier argument_list identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier parenthesized_expression binary_operator identifier call identifier argument_list identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end return_statement binary_operator identifier identifier | Align Text When Given Full Length |
def unpackmar(marfile, destdir):
marfile = cygpath(os.path.abspath(marfile))
nullfd = open(os.devnull, "w")
try:
check_call([MAR, '-x', marfile], cwd=destdir,
stdout=nullfd, preexec_fn=_noumask)
except Exception:
log.exception("Error unpacking mar file %s to %s", marfile, destdir)
raise
nullfd.close() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end try_statement block expression_statement call identifier argument_list list identifier string string_start string_content string_end identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier raise_statement expression_statement call attribute identifier identifier argument_list | Unpack marfile into destdir |
def display(table, limit=0, vrepr=None, index_header=None, caption=None,
tr_style=None, td_styles=None, encoding=None, truncate=None,
epilogue=None):
from IPython.core.display import display_html
html = _display_html(table, limit=limit, vrepr=vrepr,
index_header=index_header, caption=caption,
tr_style=tr_style, td_styles=td_styles,
encoding=encoding, truncate=truncate,
epilogue=epilogue)
display_html(html, raw=True) | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block import_from_statement dotted_name identifier identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call identifier argument_list identifier keyword_argument identifier true | Display a table inline within an IPython notebook. |
def manual_argument_parsing(argv):
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dashdash_index = argv.index('--')
except ValueError:
print_std_err('Must separate command by `--`')
print_help_and_exit()
patches, cmd = argv[:dashdash_index], argv[dashdash_index + 1:]
if '--help' in patches or '-h' in patches:
print_help_and_exit()
if '--all' in patches:
all_patches = True
patches.remove('--all')
else:
all_patches = False
unknown_options = [patch for patch in patches if patch.startswith('-')]
if unknown_options:
print_std_err('Unknown options: {!r}'.format(unknown_options))
print_help_and_exit()
if patches and all_patches:
print_std_err('--all and patches specified: {!r}'.format(patches))
print_help_and_exit()
return Arguments(all=all_patches, patches=tuple(patches), cmd=tuple(cmd)) | module function_definition identifier parameters identifier block if_statement boolean_operator boolean_operator not_operator identifier comparison_operator identifier list string string_start string_content string_end comparison_operator identifier list string string_start string_content string_end block expression_statement call identifier argument_list try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list expression_statement assignment pattern_list identifier identifier expression_list subscript identifier slice identifier subscript identifier slice binary_operator identifier integer if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block expression_statement call identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier false expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list if_statement boolean_operator identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier call identifier argument_list identifier keyword_argument identifier call identifier argument_list identifier | sadness because argparse doesn't quite do what we want. |
def _integrate_variable_trajectory(self, h, g, tol, step, relax):
solution = np.hstack((self.t, self.y))
while self.successful():
self.integrate(self.t + h, step, relax)
current_step = np.hstack((self.t, self.y))
solution = np.vstack((solution, current_step))
if g(self.t, self.y, *self.f_params) < tol:
break
else:
continue
return solution | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier while_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list tuple attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier attribute identifier identifier list_splat attribute identifier identifier identifier block break_statement else_clause block continue_statement return_statement identifier | Generates a solution trajectory of variable length. |
def get(self, user_id):
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.all()
if not user:
return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)
return self.make_response({
'user': user.to_json(),
'roles': roles
}, HTTP.OK) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list comparison_operator attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement not_operator identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier return_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end identifier attribute identifier identifier | Returns a specific user |
def wait_for_task(service, task, timeout_sec=120):
return time_wait(lambda: task_predicate(service, task), timeout_seconds=timeout_sec) | module function_definition identifier parameters identifier identifier default_parameter identifier integer block return_statement call identifier argument_list lambda call identifier argument_list identifier identifier keyword_argument identifier identifier | Waits for a task which was launched to be launched |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.