code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def merge_webhooks_runset(runset):
min_started_at = min([w['started_at'] for w in runset])
max_ended_at = max([w['ended_at'] for w in runset])
ellapse = max_ended_at - min_started_at
errors_count = sum(1 for w in runset if 'error' in w)
total_count = len(runset)
data = dict(
ellapse=ellapse,
errors_count=errors_count,
total_count=total_count,
)
return data | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier identifier expression_statement assignment identifier call identifier argument_list list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call identifier generator_expression integer for_in_clause identifier identifier if_clause comparison_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier | Make some statistics on the run set. |
def list(ctx, scenario_name, format):
args = ctx.obj.get('args')
subcommand = base._get_subcommand(__name__)
command_args = {
'subcommand': subcommand,
'format': format,
}
statuses = []
s = scenarios.Scenarios(
base.get_configs(args, command_args), scenario_name)
for scenario in s:
statuses.extend(base.execute_subcommand(scenario.config, subcommand))
headers = [util.title(name) for name in status.get_status()._fields]
if format == 'simple' or format == 'plain':
table_format = 'simple'
if format == 'plain':
headers = []
table_format = format
_print_tabulate_data(headers, statuses, table_format)
else:
_print_yaml_data(headers, statuses) | module function_definition identifier parameters identifier identifier 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 expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier attribute call attribute identifier identifier argument_list identifier if_statement 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 string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier list expression_statement assignment identifier identifier expression_statement call identifier argument_list identifier identifier identifier else_clause block expression_statement call identifier argument_list identifier identifier | Lists status of instances. |
def server(port):
args = ['python', 'manage.py', 'runserver']
if port:
args.append(port)
run.main(args) | module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Start the Django dev server. |
def orphans_single(default_exec=False):
if not default_exec and executable.endswith('uwsgi'):
_executable = executable[:-5] + 'python'
else:
_executable = executable
p = subprocess.Popen([_executable, '-m', 'nikola', 'orphans'],
stdout=subprocess.PIPE)
p.wait()
files = [l.strip().decode('utf-8') for l in p.stdout.readlines()]
for f in files:
if f:
os.unlink(f)
out = '\n'.join(files)
return p.returncode, out | module function_definition identifier parameters default_parameter identifier false block if_statement boolean_operator not_operator identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator subscript identifier slice unary_operator integer string string_start string_content string_end else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list list identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end for_in_clause identifier call attribute attribute identifier identifier identifier argument_list for_statement identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier return_statement expression_list attribute identifier identifier identifier | Remove all orphans in the site, in the single user-mode. |
def comp_idat(self, idat):
if self.compression is not None:
compressor = zlib.compressobj(self.compression)
else:
compressor = zlib.compressobj()
for dat in idat:
compressed = compressor.compress(dat)
if len(compressed):
yield compressed
flushed = compressor.flush()
if len(flushed):
yield flushed | module function_definition identifier parameters identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call identifier argument_list identifier block expression_statement yield identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call identifier argument_list identifier block expression_statement yield identifier | Generator that produce compressed IDAT chunks from IDAT data |
def query_dated(num=10, kind='1'):
return TabWiki.select().where(
TabWiki.kind == kind
).order_by(
TabWiki.time_update.desc()
).limit(num) | module function_definition identifier parameters default_parameter identifier integer default_parameter identifier string string_start string_content string_end block return_statement call attribute call attribute call attribute call attribute identifier identifier argument_list identifier argument_list comparison_operator attribute identifier identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier argument_list identifier | List the wiki of dated. |
def open(self):
self._connection = paramiko.SSHClient()
self._connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
self._connection.connect(hostname=self._hostname,
username=self._username,
password=self._password,
timeout=self._timeout,
port=self._port)
self._connection.get_transport().set_keepalive(self._keepalive)
self.connected = True
self.config = PluribusConfig(self)
except paramiko.ssh_exception.AuthenticationException:
raise pyPluribus.exceptions.ConnectionError("Unable to open connection with {hostname}: \
invalid credentials!".format(hostname=self._hostname))
except socket_error as sockerr:
raise pyPluribus.exceptions.ConnectionError("Cannot open connection: {skterr}. \
Wrong port?".format(skterr=sockerr.message))
except socket_gaierror as sockgai:
raise pyPluribus.exceptions.ConnectionError("Cannot open connection: {gaierr}. \
Wrong hostname?".format(gaierr=sockgai.message)) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier call identifier argument_list identifier except_clause attribute attribute identifier identifier identifier block raise_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list keyword_argument identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list keyword_argument identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list keyword_argument identifier attribute identifier identifier | Opens a SSH connection with a Pluribus machine. |
def _check_jp2h_child_boxes(self, boxes, parent_box_name):
JP2H_CHILDREN = set(['bpcc', 'cdef', 'cmap', 'ihdr', 'pclr'])
box_ids = set([box.box_id for box in boxes])
intersection = box_ids.intersection(JP2H_CHILDREN)
if len(intersection) > 0 and parent_box_name not in ['jp2h', 'jpch']:
msg = "A {0} box can only be nested in a JP2 header box."
raise IOError(msg.format(list(intersection)[0]))
for box in boxes:
if hasattr(box, 'box'):
self._check_jp2h_child_boxes(box.box, box.box_id) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list call attribute identifier identifier argument_list subscript call identifier argument_list identifier integer for_statement identifier identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Certain boxes can only reside in the JP2 header. |
def delete_migration(connection, basename):
sql = "DELETE FROM migrations_applied WHERE name = %s"
with connection.cursor() as cursor:
cursor.execute(sql, (basename,))
connection.commit()
return True | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier tuple identifier expression_statement call attribute identifier identifier argument_list return_statement true | Delete a migration in `migrations_applied` table |
def pformat_xml(xml):
try:
from lxml import etree
if not isinstance(xml, bytes):
xml = xml.encode('utf-8')
xml = etree.parse(io.BytesIO(xml))
xml = etree.tostring(xml, pretty_print=True, xml_declaration=True,
encoding=xml.docinfo.encoding)
xml = bytes2str(xml)
except Exception:
if isinstance(xml, bytes):
xml = bytes2str(xml)
xml = xml.replace('><', '>\n<')
return xml.replace(' ', ' ').replace('\t', ' ') | module function_definition identifier parameters identifier block try_statement block import_from_statement dotted_name identifier dotted_name identifier if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true keyword_argument identifier true keyword_argument identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content escape_sequence string_end return_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content escape_sequence string_end string string_start string_content string_end | Return pretty formatted XML. |
def _dotted_get(self, dotted_key, default=None, **kwargs):
split_key = dotted_key.split(".")
name, keys = split_key[0], split_key[1:]
result = self.get(name, default=default, **kwargs)
self._memoized = result
if not keys or result is default:
self._memoized = None
return result
return self._dotted_get(".".join(keys), default=default, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier expression_list subscript identifier integer subscript identifier slice integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier identifier if_statement boolean_operator not_operator identifier comparison_operator identifier identifier block expression_statement assignment attribute identifier identifier none return_statement identifier return_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier identifier dictionary_splat identifier | Perform dotted key lookups and keep track of where we are. |
def _find_impl(cls, role, interface):
module = _relation_module(role, interface)
if not module:
return None
return cls._find_subclass(module) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement not_operator identifier block return_statement none return_statement call attribute identifier identifier argument_list identifier | Find relation implementation based on its role and interface. |
def _cast_page(val):
try:
val = int(val)
if val < 0:
raise ValueError
return val
except (TypeError, ValueError):
raise ValueError | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier integer block raise_statement identifier return_statement identifier except_clause tuple identifier identifier block raise_statement identifier | Convert the page limit & offset into int's & type check |
def gen_unkn():
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.UNKN, empty_reg, empty_reg, empty_reg) | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier identifier | Return an UNKN instruction. |
def add_jsfile_head(self, src: str) -> None:
self.head.appendChild(Script(src=src)) | module function_definition identifier parameters identifier typed_parameter identifier type identifier type none block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier | Add JS file to load at this document's header. |
def logvalue(self, key, value):
if not hasattr(self, 'logvalues'):
self.logvalues = {}
self.logvalues[key] = value | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier dictionary expression_statement assignment subscript attribute identifier identifier identifier identifier | Add log entry to request log info |
def _validate_state(state, valid_states):
if state in State:
return state.name
elif state in valid_states:
return state
else:
raise Invalid('Invalid state') | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block return_statement attribute identifier identifier elif_clause comparison_operator identifier identifier block return_statement identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Validate a state string |
def _upload_file_aws_cli(local_fname, bucket, keyname, config=None, mditems=None):
s3_fname = "s3://%s/%s" % (bucket, keyname)
args = ["--sse", "--expected-size", str(os.path.getsize(local_fname))]
if config:
if config.get("region"):
args += ["--region", config.get("region")]
if config.get("reduced_redundancy"):
args += ["--storage-class", "REDUCED_REDUNDANCY"]
cmd = [os.path.join(os.path.dirname(sys.executable), "aws"), "s3", "cp"] + args + \
[local_fname, s3_fname]
do.run(cmd, "Upload to s3: %s %s" % (bucket, keyname)) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement augmented_assignment identifier list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement augmented_assignment identifier list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier binary_operator binary_operator list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier line_continuation list identifier identifier expression_statement call attribute identifier identifier argument_list identifier binary_operator string string_start string_content string_end tuple identifier identifier | Streaming upload via the standard AWS command line interface. |
def compute_output(t0, t1):
if t0 is None or t1 is None:
return -1.0
else:
response = 1.1 - 0.1 * abs(t0 - t1)
return max(0.0, min(1.0, response)) | module function_definition identifier parameters identifier identifier block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block return_statement unary_operator float else_clause block expression_statement assignment identifier binary_operator float binary_operator float call identifier argument_list binary_operator identifier identifier return_statement call identifier argument_list float call identifier argument_list float identifier | Compute the network's output based on the "time to first spike" of the two output neurons. |
def requires_loaded(func):
def _wrapper(self, *args, **kwargs):
if self._loaded_data is None:
self._loaded_data = self.loader.load(self.service_name)
return func(self, *args, **kwargs)
return _wrapper | module function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | A decorator to ensure the resource data is loaded. |
def opened(self, block_identifier: BlockSpecification) -> bool:
return self.token_network.channel_is_opened(
participant1=self.participant1,
participant2=self.participant2,
block_identifier=block_identifier,
channel_identifier=self.channel_identifier,
) | module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier | Returns if the channel is opened. |
def urlencode(txt):
if isinstance(txt, unicode):
txt = txt.encode('utf-8')
return urllib.quote_plus(txt) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier | Url encode a path. |
def open_link(self, *args):
if "disabled" not in self.state():
webbrowser.open(self._link)
self.__clicked = True
self._on_leave() | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list | Open the link in the web browser. |
def item_links_addition(self, data):
links_item_factory = self.context.get('links_item_factory',
default_links_item_factory)
data['links'] = links_item_factory(data)
return data | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier return_statement identifier | Add the links for each community. |
def from_forward(cls, fmodel, **kwargs):
im = cls(fmodel.dim_x, fmodel.dim_y, **kwargs)
im.fmodel = fmodel
return im | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | Construst an inverse model from a forward model and constraints. |
def install():
ceph_dir = "/etc/ceph"
if not os.path.exists(ceph_dir):
os.mkdir(ceph_dir)
apt_install('ceph-common', fatal=True) | module function_definition identifier parameters block expression_statement assignment identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier true | Basic Ceph client installation. |
def make_definition(name, base, schema):
class_name = make_class_name(name)
cls = register(make(class_name, base, schema))
globals()[class_name] = cls | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier identifier expression_statement assignment subscript call identifier argument_list identifier identifier | Create a new definition. |
def __leaf(i, j, first, maxfirst, prevleaf, ancestor):
jleaf = 0
if i<=j or first[j] <= maxfirst[i]: return -1, jleaf
maxfirst[i] = first[j]
jprev = prevleaf[i]
prevleaf[i] = j
if jprev == -1: jleaf = 1
else: jleaf = 2
if jleaf == 1: return i, jleaf
q = jprev
while q != ancestor[q]: q = ancestor[q]
s = jprev
while s != q:
sparent = ancestor[s]
ancestor[s] = q
s = sparent
return q, jleaf | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier integer if_statement boolean_operator comparison_operator identifier identifier comparison_operator subscript identifier identifier subscript identifier identifier block return_statement expression_list unary_operator integer identifier expression_statement assignment subscript identifier identifier subscript identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment subscript identifier identifier identifier if_statement comparison_operator identifier unary_operator integer block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier integer if_statement comparison_operator identifier integer block return_statement expression_list identifier identifier expression_statement assignment identifier identifier while_statement comparison_operator identifier subscript identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier identifier while_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier identifier return_statement expression_list identifier identifier | Determine if j is leaf of i'th row subtree. |
def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej):
alpha = ei_dot_ei * ei_dot_ej
alpha_sum = alpha[0] + alpha[1] + alpha[2]
beta = alpha / alpha_sum[None]
a = X * beta[..., None]
cc = a[0] + a[1] + a[2]
return cc | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator binary_operator subscript identifier integer subscript identifier integer subscript identifier integer expression_statement assignment identifier binary_operator identifier subscript identifier none expression_statement assignment identifier binary_operator identifier subscript identifier ellipsis none expression_statement assignment identifier binary_operator binary_operator subscript identifier integer subscript identifier integer subscript identifier integer return_statement identifier | Computes the circumcenters of all given triangles. |
def temp_unit(self):
if CONST.UNIT_FAHRENHEIT in self._get_status(CONST.TEMP_STATUS_KEY):
return CONST.UNIT_FAHRENHEIT
elif CONST.UNIT_CELSIUS in self._get_status(CONST.TEMP_STATUS_KEY):
return CONST.UNIT_CELSIUS
return None | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier block return_statement attribute identifier identifier elif_clause comparison_operator attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier block return_statement attribute identifier identifier return_statement none | Get unit of temp. |
def gen_str_to_sign(self, req):
url = urlsplit(req.url)
bucket_name = url.netloc.split(".", 1)[0]
logger.debug(req.headers.items())
ucloud_headers = [
(k, v.strip())
for k, v in sorted(req.headers.lower_items())
if k.startswith("x-ucloud-")
]
canonicalized_headers = "\n".join([
"{0}:{1}".format(k, v) for k, v in ucloud_headers
])
canonicalized_resource = "/{0}{1}".format(
bucket_name,
unquote(url.path)
)
str_to_sign = "\n".join([
req.method,
req.headers.get("content-md5", ""),
req.headers.get("content-type", ""),
req.headers.get("date", self._expires),
canonicalized_headers + canonicalized_resource
])
return str_to_sign | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end integer integer expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier list_comprehension tuple identifier call attribute identifier identifier argument_list for_in_clause pattern_list identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list if_clause call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list list_comprehension call attribute string string_start string_content string_end identifier argument_list identifier identifier for_in_clause pattern_list identifier identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier binary_operator identifier identifier return_statement identifier | Generate string to sign using giving prepared request |
def com_google_fonts_check_name_mandatory_entries(ttFont, style):
from fontbakery.utils import get_name_entry_strings
from fontbakery.constants import RIBBI_STYLE_NAMES
required_nameIDs = [NameID.FONT_FAMILY_NAME,
NameID.FONT_SUBFAMILY_NAME,
NameID.FULL_FONT_NAME,
NameID.POSTSCRIPT_NAME]
if style not in RIBBI_STYLE_NAMES:
required_nameIDs += [NameID.TYPOGRAPHIC_FAMILY_NAME,
NameID.TYPOGRAPHIC_SUBFAMILY_NAME]
failed = False
for nameId in required_nameIDs:
if len(get_name_entry_strings(ttFont, nameId)) == 0:
failed = True
yield FAIL, (f"Font lacks entry with nameId={nameId}"
f" ({NameID(nameId).name})")
if not failed:
yield PASS, "Font contains values for all mandatory name table entries." | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement augmented_assignment identifier list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier false for_statement identifier identifier block if_statement comparison_operator call identifier argument_list call identifier argument_list identifier identifier integer block expression_statement assignment identifier true expression_statement yield expression_list identifier parenthesized_expression concatenated_string string string_start string_content interpolation identifier string_end string string_start string_content interpolation attribute call identifier argument_list identifier identifier string_content string_end if_statement not_operator identifier block expression_statement yield expression_list identifier string string_start string_content string_end | Font has all mandatory 'name' table entries ? |
def connected(self, **kwargs):
self.bot.log.info('Server config: %r', self.bot.server_config)
self.bot.config['nick'] = kwargs['me']
self.bot.recompile()
self.bot.notify('server_ready')
self.bot.detach_events(*self.before_connect_events) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment subscript attribute attribute identifier identifier identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list list_splat attribute identifier identifier | triger the server_ready event |
def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs):
try:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_TLS
except AttributeError:
pool_kwargs['ssl_version'] = ssl.PROTOCOL_SSLv23
return super(SSLAdapter, self).init_poolmanager(connections, maxsize, block, **pool_kwargs) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false dictionary_splat_pattern identifier block try_statement block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier except_clause identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier dictionary_splat identifier | Called to initialize the HTTPAdapter when no proxy is used. |
def lonlat2xyz(lons, lats):
R = 6370997.0
x_coords = R * da.cos(da.deg2rad(lats)) * da.cos(da.deg2rad(lons))
y_coords = R * da.cos(da.deg2rad(lats)) * da.sin(da.deg2rad(lons))
z_coords = R * da.sin(da.deg2rad(lats))
return x_coords, y_coords, z_coords | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier float expression_statement assignment identifier binary_operator binary_operator identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier identifier | Convert lons and lats to cartesian coordinates. |
def parse_passage(obj: dict) -> BioCPassage:
passage = BioCPassage()
passage.offset = obj['offset']
passage.infons = obj['infons']
if 'text' in obj:
passage.text = obj['text']
for sentence in obj['sentences']:
passage.add_sentence(parse_sentence(sentence))
for annotation in obj['annotations']:
passage.add_annotation(parse_annotation(annotation))
for relation in obj['relations']:
passage.add_relation(parse_relation(relation))
return passage | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier return_statement identifier | Deserialize a dict obj to a BioCPassage object |
def getNextNode(self, name, **context):
try:
nextNode = self.getBranch(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
return self.getNextBranch(name, **context)
else:
try:
return nextNode.getNextNode(name, **context)
except (error.NoSuchInstanceError, error.NoSuchObjectError):
try:
return self._vars[self._vars.nextKey(nextNode.name)]
except KeyError:
raise error.NoSuchObjectError(name=name, idx=context.get('idx')) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary_splat identifier except_clause tuple attribute identifier identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier else_clause block try_statement block return_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier except_clause tuple attribute identifier identifier attribute identifier identifier block try_statement block return_statement subscript attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause identifier block raise_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end | Return tree node next to name |
def wraps(function):
def wrap(decorator):
decorator = functools.wraps(function)(decorator)
if not hasattr(function, 'original'):
decorator.original = function
else:
decorator.original = function.original
delattr(function, 'original')
return decorator
return wrap | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block expression_statement assignment identifier call call attribute identifier identifier argument_list identifier argument_list identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier identifier else_clause block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call identifier argument_list identifier string string_start string_content string_end return_statement identifier return_statement identifier | Enables building decorators around functions used for hug routes without changing their function signature |
def R_package_resource(package, resource):
package_path = R_package_path(package)
if not package_path:
return None
package_resource = os.path.join(package_path, resource)
if not file_exists(package_resource):
return None
else:
return package_resource | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block return_statement none expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement not_operator call identifier argument_list identifier block return_statement none else_clause block return_statement identifier | return a path to an R package resource, if it is available |
def validate(self):
if not self.api_token or not self.api_token_secret:
raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.")
if self.response_type not in ["json", "pson", "xml", "debug", None]:
raise ImproperlyConfigured("'%s' is an invalid response_type" % self.response_type) | module function_definition identifier parameters identifier block if_statement boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator attribute identifier identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | Perform validation check on properties. |
def remove_graphic(self, graphic: Graphics.Graphic, *, safe: bool=False) -> typing.Optional[typing.Sequence]:
return self.remove_model_item(self, "graphics", graphic, safe=safe) | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier keyword_separator typed_default_parameter identifier type identifier false type subscript attribute identifier identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier keyword_argument identifier identifier | Remove a graphic, but do it through the container, so dependencies can be tracked. |
def _retrieve_indices(cols):
if isinstance(cols, int):
return [cols]
elif isinstance(cols, slice):
start = cols.start if cols.start else 0
stop = cols.stop
step = cols.step if cols.step else 1
return list(range(start, stop, step))
elif isinstance(cols, list) and cols:
if isinstance(cols[0], bool):
return np.flatnonzero(np.asarray(cols))
elif isinstance(cols[0], int):
return cols
else:
raise TypeError('No valid column specifier. Only a scalar, list or slice of all'
'integers or a boolean mask are allowed.') | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement list identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier conditional_expression attribute identifier identifier attribute identifier identifier integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier conditional_expression attribute identifier identifier attribute identifier identifier integer return_statement call identifier argument_list call identifier argument_list identifier identifier identifier elif_clause boolean_operator call identifier argument_list identifier identifier identifier block if_statement call identifier argument_list subscript identifier integer identifier block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list subscript identifier integer identifier block return_statement identifier else_clause block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end | Retrieve a list of indices corresponding to the provided column specification. |
def unparse_qs(qs, sort=False, reverse=False):
result = []
items = qs.items()
if sort:
items = sorted(items, key=lambda x: x[0], reverse=reverse)
for keys, values in items:
query_name = quote(keys)
for value in values:
result.append(query_name + "=" + quote(value))
return "&".join(result) | module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier subscript identifier integer keyword_argument identifier identifier for_statement pattern_list identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator binary_operator identifier string string_start string_content string_end call identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier | Reverse conversion for parse_qs |
def connect_to_database_odbc_mysql(self,
database: str,
user: str,
password: str,
server: str = "localhost",
port: int = 3306,
driver: str = "{MySQL ODBC 5.1 Driver}",
autocommit: bool = True) -> None:
self.connect(engine=ENGINE_MYSQL, interface=INTERFACE_ODBC,
database=database, user=user, password=password,
host=server, port=port, driver=driver,
autocommit=autocommit) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier string string_start string_content string_end typed_default_parameter identifier type identifier integer typed_default_parameter identifier type identifier string string_start string_content string_end typed_default_parameter identifier type identifier true type none block expression_statement call attribute identifier identifier argument_list 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 | Connects to a MySQL database via ODBC. |
def _json_safe(cls, value):
if type(value) == date:
return str(value)
elif type(value) == datetime:
return value.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(value, ObjectId):
return str(value)
elif isinstance(value, _BaseFrame):
return value.to_json_type()
elif isinstance(value, (list, tuple)):
return [cls._json_safe(v) for v in value]
elif isinstance(value, dict):
return {k:cls._json_safe(v) for k, v in value.items()}
return value | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier block return_statement call identifier argument_list identifier elif_clause comparison_operator call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list elif_clause call identifier argument_list identifier tuple identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement dictionary_comprehension pair identifier call attribute identifier identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list return_statement identifier | Return a JSON safe value |
def download(url):
session = requests.Session()
session.mount('file://', FileAdapter())
try:
res = session.get(url)
except requests.exceptions.ConnectionError as e:
raise e
res.raise_for_status()
return res | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block raise_statement identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Uses requests to download an URL, maybe from a file |
def run_queue(self, options, todo):
utils.logging_debug('AutoBatcher(%s): %d items',
self._todo_tasklet.__name__, len(todo))
batch_fut = self._todo_tasklet(todo, options)
self._running.append(batch_fut)
batch_fut.add_callback(self._finished_callback, batch_fut, todo) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier identifier | Actually run the _todo_tasklet. |
def query(self):
self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0]
self._head = HeadRevision(self._p4dict)
self._filename = self.depotFile | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier subscript call attribute attribute identifier identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end integer expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier | Runs an fstat for this file and repopulates the data |
def ordered_dict_to_dict(d):
ret = {}
new_d = deepcopy(d)
for k, v in new_d.items():
if isinstance(v, OrderedDict):
v = dict(v)
if isinstance(v, dict):
v = ordered_dict_to_dict(v)
ret[k] = v
return ret | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier | Converts inner OrderedDict to bare dict |
def cleanup(self):
all([delete_file_or_tree(f) for f in self.to_delete])
self.to_delete = [] | module function_definition identifier parameters identifier block expression_statement call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment attribute identifier identifier list | Clean up my temporary files. |
def rule(self, key):
def register(f):
self.rules[key] = f
return f
return register | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier return_statement identifier | Decorate as a rule for a key in top level JSON. |
def pretty_print(self):
print colored.blue("-" * 40)
print colored.red("datacats: problem was encountered:")
print self.message
print colored.blue("-" * 40) | module function_definition identifier parameters identifier block print_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end integer print_statement call attribute identifier identifier argument_list string string_start string_content string_end print_statement attribute identifier identifier print_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end integer | Print the error message to stdout with colors and borders |
def save_form(self, request, form, change):
obj = form.save(commit=False)
if obj.user_id is None:
obj.user = request.user
return super(OwnableAdmin, self).save_form(request, form, change) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier false if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier identifier | Set the object's owner as the logged in user. |
def add_payload(self, payload):
if self.payloads:
self.payloads[-1].next_payload = payload._type
self.payloads.append(payload) | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement assignment attribute subscript attribute identifier identifier unary_operator integer identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Adds a payload to packet, updating last payload's next_payload field |
def deleteAllGroups(server):
try:
client, key = _get_session(server)
except Exception as exc:
err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
log.error(err_msg)
return {'Error': err_msg}
groups = client.systemgroup.listAllGroups(key)
deleted_groups = []
failed_groups = []
for group in groups:
if client.systemgroup.delete(key, group['name']) == 1:
deleted_groups.append(group['name'])
else:
failed_groups.append(group['name'])
ret = {'deleted': deleted_groups}
if failed_groups:
ret['failed'] = failed_groups
return ret | module function_definition identifier parameters identifier block try_statement block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list identifier subscript identifier string string_start string_content string_end integer block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Delete all server groups from Spacewalk |
def Pull(cls, connection, filename, dest_file, progress_callback):
if progress_callback:
total_bytes = cls.Stat(connection, filename)[1]
progress = cls._HandleProgress(lambda current: progress_callback(filename, current, total_bytes))
next(progress)
cnxn = FileSyncConnection(connection, b'<2I')
try:
cnxn.Send(b'RECV', filename)
for cmd_id, _, data in cnxn.ReadUntil((b'DATA',), b'DONE'):
if cmd_id == b'DONE':
break
dest_file.write(data)
if progress_callback:
progress.send(len(data))
except usb_exceptions.CommonUsbError as e:
raise PullFailedError('Unable to pull file %s due to: %s' % (filename, e)) | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list lambda lambda_parameters identifier call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list tuple string string_start string_content string_end string string_start string_content string_end block if_statement comparison_operator identifier string string_start string_content string_end block break_statement expression_statement call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier | Pull a file from the device into the file-like dest_file. |
def _paginate(url, topkey, *args, **kwargs):
ret = salt.utils.http.query(url, **kwargs)
if 'errors' in ret['dict']:
return ret['dict']
lim = int(ret['dict']['page']['limit'])
total = int(ret['dict']['page']['total'])
if total == 0:
return {}
numpages = (total / lim) + 1
if numpages == 1:
return ret['dict'][topkey]
aggregate_ret = ret['dict'][topkey]
url = args[0]
for p in range(2, numpages):
param_url = url + '?offset={0}'.format(lim * (p - 1))
next_ret = salt.utils.http.query(param_url, kwargs)
aggregate_ret[topkey].extend(next_ret['dict'][topkey])
return aggregate_ret | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier dictionary_splat identifier if_statement comparison_operator string string_start string_content string_end subscript identifier string string_start string_content string_end block return_statement subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier integer block return_statement dictionary expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier integer if_statement comparison_operator identifier integer block return_statement subscript subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier subscript identifier integer for_statement identifier call identifier argument_list integer identifier block expression_statement assignment identifier binary_operator identifier call attribute string string_start string_content string_end identifier argument_list binary_operator identifier parenthesized_expression binary_operator identifier integer expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier expression_statement call attribute subscript identifier identifier identifier argument_list subscript subscript identifier string string_start string_content string_end identifier return_statement identifier | Wrapper to assist with paginated responses from Digicert's REST API. |
def _calcCTRBUF(self):
self.ctr_cks = self.encrypt(struct.pack("Q", self.ctr_iv))
self.ctr_iv += 1
self.ctr_pos = 0 | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer | Calculates one block of CTR keystream |
def _save(self, url, path, data):
worker = self._workers[url]
path = self._paths[url]
if len(data):
try:
with open(path, 'wb') as f:
f.write(data)
except Exception:
logger.error((url, path))
worker.finished = True
worker.sig_download_finished.emit(url, path)
worker.sig_finished.emit(worker, path, None)
self._get_requests.pop(url)
self._workers.pop(url)
self._paths.pop(url) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement call identifier argument_list identifier block try_statement block 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 identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list tuple identifier identifier expression_statement assignment attribute identifier identifier true expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier none expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Save `data` of downloaded `url` in `path`. |
def to_bb(YY, y="deprecated"):
cols,rows = np.nonzero(YY)
if len(cols)==0: return np.zeros(4, dtype=np.float32)
top_row = np.min(rows)
left_col = np.min(cols)
bottom_row = np.max(rows)
right_col = np.max(cols)
return np.array([left_col, top_row, right_col, bottom_row], dtype=np.float32) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement call attribute identifier identifier argument_list integer keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list list identifier identifier identifier identifier keyword_argument identifier attribute identifier identifier | Convert mask YY to a bounding box, assumes 0 as background nonzero object |
def rmvirtualenv():
path = '/'.join([deployment_root(),'env',env.project_fullname])
link = '/'.join([deployment_root(),'env',env.project_name])
if version_state('mkvirtualenv'):
sudo(' '.join(['rm -rf',path]))
sudo(' '.join(['rm -f',link]))
sudo('rm -f /var/local/woven/%s*'% env.project_fullname)
set_version_state('mkvirtualenv',delete=True) | module function_definition identifier parameters block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list call identifier argument_list string string_start string_content string_end attribute identifier identifier if_statement call identifier argument_list string string_start string_content string_end block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list list string string_start string_content string_end identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list list string string_start string_content string_end identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier true | Remove the current or ``env.project_version`` environment and all content in it |
def _association_types(self):
r = self.session.get('/v2/types/associationTypes')
if not r.ok or 'application/json' not in r.headers.get('content-type', ''):
warn = u'Custom Indicators Associations are not supported.'
self.log.warning(warn)
return
data = r.json()
if data.get('status') != 'Success':
warn = u'Bad Status: Custom Indicators Associations are not supported.'
self.log.warning(warn)
return
try:
for association in data.get('data', {}).get('associationType', []):
self._indicator_associations_types_data[association.get('name')] = association
except Exception as e:
self.handle_error(200, [e]) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator not_operator attribute identifier identifier comparison_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement try_statement block for_statement identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list string string_start string_content string_end list block expression_statement assignment subscript attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list integer list identifier | Retrieve Custom Indicator Associations types from the ThreatConnect API. |
def _parse_snapshot_hits(self, file_obj):
for _ in range(self.n_snapshot_hits):
dom_id, pmt_id = unpack('<ib', file_obj.read(5))
tdc_time = unpack('>I', file_obj.read(4))[0]
tot = unpack('<b', file_obj.read(1))[0]
self.snapshot_hits.append((dom_id, pmt_id, tdc_time, tot)) | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list integer expression_statement assignment identifier subscript call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list integer integer expression_statement assignment identifier subscript call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list integer integer expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier identifier identifier | Parse and store snapshot hits. |
def process_login(context, request):
username = request.json['username']
password = request.json['password']
user = context.authenticate(username, password)
if not user:
@request.after
def adjust_status(response):
response.status = 401
return {
'status': 'error',
'error': {
'code': 401,
'message': 'Invalid Username / Password'
}
}
@request.after
def remember(response):
response.headers.add('Access-Control-Expose-Headers', 'Authorization')
identity = user.identity
request.app.remember_identity(response, request, identity)
return {
'status': 'success'
} | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement not_operator identifier block decorated_definition decorator attribute identifier identifier function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier integer return_statement dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end dictionary pair string string_start string_content string_end integer pair string string_start string_content string_end string string_start string_content string_end decorated_definition decorator attribute identifier identifier function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier return_statement dictionary pair string string_start string_content string_end string string_start string_content string_end | Authenticate username and password and log in user |
def _init_sub_groups(self, parent):
if self._sub_groups:
for sub_group in self._sub_groups:
for component in split_path_components(sub_group):
fp = os.path.join(parent.full_path, component)
if os.path.exists(fp):
node = Node(name=component, parent=parent)
parent.children.append(node)
else:
node = parent.create_cgroup(component)
parent = node
self._init_children(node)
else:
self._init_children(parent) | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier | Initialise sub-groups, and create any that do not already exist. |
def Kill(self):
try:
if self.is_running:
self.Detach()
if self._Execute('__kill__') == '__kill_ack__':
time.sleep(0.1)
except (TimeoutError, ProxyError):
logging.debug('Termination request not acknowledged, killing gdb.')
if self.is_running:
os.kill(self._process.pid, signal.SIGINT)
self._process.terminate()
self._process.wait()
self._errfile_r.close()
self._outfile_r.close() | module function_definition identifier parameters identifier block try_statement block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list float except_clause tuple identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Send death pill to Gdb and forcefully kill it if that doesn't work. |
def main():
args = parse_arguments()
print(args)
print("action" + args.action)
print("pid" + args.pid)
print("directory" + args.directory)
print("fileprefix" + args.fileprefix) | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | Check arguments are retrieved. |
def onSync(self, event):
SETUP = self.statement('SETUP')
if SETUP:
sql, data = SETUP(self.database())
if event.context.dryRun:
print sql % data
else:
self.execute(sql, data, writeAccess=True) | 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 if_statement identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list call attribute identifier identifier argument_list if_statement attribute attribute identifier identifier identifier block print_statement binary_operator identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier true | Initializes the database by defining any additional structures that are required during selection. |
def release(self, jid, priority=DEFAULT_PRIORITY, delay=0):
self._interact('release %d %d %d\r\n' % (jid, priority, delay),
['RELEASED', 'BURIED'],
['NOT_FOUND']) | module function_definition identifier parameters identifier identifier default_parameter identifier identifier default_parameter identifier integer block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence escape_sequence string_end tuple identifier identifier identifier list string string_start string_content string_end string string_start string_content string_end list string string_start string_content string_end | Release a reserved job back into the ready queue. |
def on_resolve(target, func, *args, **kwargs):
return _register_hook(ON_RESOLVE, target, func, *args, **kwargs) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list identifier identifier identifier list_splat identifier dictionary_splat identifier | Register a resolution hook. |
def fitImg(self, img_rgb):
H = self.pattern.findHomography(img_rgb)[0]
H_inv = self.pattern.invertHomography(H)
s = self.img_orig.shape
warped = cv2.warpPerspective(img_rgb, H_inv, (s[1], s[0]))
return warped | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier tuple subscript identifier integer subscript identifier integer return_statement identifier | fit perspective and size of the input image to the base image |
def _prep(e):
if 'lastupdate' in e:
e['lastupdate'] = datetime.datetime.fromtimestamp(int(e['lastupdate']))
for k in ['farm', 'server', 'id', 'secret']:
if not k in e:
return e
e["url"] = "https://farm%s.staticflickr.com/%s/%s_%s_b.jpg" % (e["farm"], e["server"], e["id"], e["secret"])
return e | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list call identifier argument_list subscript identifier string string_start string_content string_end for_statement identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block if_statement not_operator comparison_operator identifier identifier block return_statement identifier expression_statement assignment subscript identifier string string_start string_content string_end binary_operator string string_start string_content string_end tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement identifier | Normalizes lastupdate to a timestamp, and constructs a URL from the embedded attributes. |
def move_previews(self):
"Move previews after a resize event"
min_y = self._calc_preview_ypos()
for idx, (key, p) in enumerate(self.previews.items()):
new_dy = min_y[idx] - p.y
self.previews[key].move_by(0, new_dy)
self._update_cregion()
self.show_selected(self._sel_id, self._sel_widget) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list for_statement pattern_list identifier tuple_pattern identifier identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier binary_operator subscript identifier identifier attribute identifier identifier expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list integer identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Move previews after a resize event |
def fullPath(self):
for ((dirTree, dirID, dirSeq), (dirPath, name)) in self.links.items():
try:
path = self.fileSystem.volumes[dirTree].fullPath
if path is not None:
return path + ("/" if path[-1] != "/" else "") + dirPath + name
except Exception:
logging.debug("Haven't imported %d yet", dirTree)
if self.id == BTRFS_FS_TREE_OBJECTID:
return "/"
else:
return None | module function_definition identifier parameters identifier block for_statement tuple_pattern tuple_pattern identifier identifier identifier tuple_pattern identifier identifier call attribute attribute identifier identifier identifier argument_list block try_statement block expression_statement assignment identifier attribute subscript attribute attribute identifier identifier identifier identifier identifier if_statement comparison_operator identifier none block return_statement binary_operator binary_operator binary_operator identifier parenthesized_expression conditional_expression string string_start string_content string_end comparison_operator subscript identifier unary_operator integer string string_start string_content string_end string string_start string_end identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier identifier block return_statement string string_start string_content string_end else_clause block return_statement none | Return full butter path from butter root. |
def start(self):
self.running = True
self.status = 'RUNNING'
self.mylog.record_process('agent', self.name + ' - starting') | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end binary_operator attribute identifier identifier string string_start string_content string_end | Starts an agent with standard logging |
def degree(self, vertex):
try:
return len(self.vertices[vertex])
except KeyError:
raise GraphInsertError("Vertex %s doesn't exist." % (vertex,)) | module function_definition identifier parameters identifier identifier block try_statement block return_statement call identifier argument_list subscript attribute identifier identifier identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier | Return the degree of a vertex |
def rename(idf, objkey, objname, newname):
refnames = getrefnames(idf, objkey)
for refname in refnames:
objlists = getallobjlists(idf, refname)
for refname in refnames:
for robjkey, refname, fieldindexlist in objlists:
idfobjects = idf.idfobjects[robjkey]
for idfobject in idfobjects:
for findex in fieldindexlist:
if idfobject[idfobject.objls[findex]] == objname:
idfobject[idfobject.objls[findex]] = newname
theobject = idf.getobject(objkey, objname)
fieldname = [item for item in theobject.objls if item.endswith('Name')][0]
theobject[fieldname] = newname
return theobject | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier for_statement identifier identifier block for_statement pattern_list identifier identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier for_statement identifier identifier block for_statement identifier identifier block if_statement comparison_operator subscript identifier subscript attribute identifier identifier identifier identifier block expression_statement assignment subscript identifier subscript attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier subscript list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment subscript identifier identifier identifier return_statement identifier | rename all the refrences to this objname |
def send(self, command, message=None):
if message:
joined = command + constants.NL + util.pack(message)
else:
joined = command + constants.NL
if self._blocking:
for sock in self.socket():
sock.sendall(joined)
else:
self._pending.append(joined) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement identifier block expression_statement assignment identifier binary_operator binary_operator identifier attribute identifier identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier binary_operator identifier attribute identifier identifier if_statement attribute identifier identifier block for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Send a command over the socket with length endcoded |
def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
service_name = app.config.get('GSSAPI_SERVICE_NAME', 'HTTP')
hostname = app.config.get('GSSAPI_HOSTNAME', socket.getfqdn())
principal = '{}@{}'.format(service_name, hostname)
name = gssapi.Name(principal, gssapi.NameType.hostbased_service)
app.extensions['gssapi'] = {
'creds': gssapi.Credentials(name=name, usage='accept'),
} | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier dictionary expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end | Initialises the Negotiate extension for the given application. |
def all_tamil( word_in ):
if isinstance(word_in,list):
word = word_in
else:
word = get_letters( word_in )
return all( [(letter in tamil_letters) for letter in word] ) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list list_comprehension parenthesized_expression comparison_operator identifier identifier for_in_clause identifier identifier | predicate checks if all letters of the input word are Tamil letters |
def _load_repo(self):
if self._logg_repo:
return self._logg_repo
try:
_logg_repo = git.Repo(self._engine_path)
log.debug('Loaded git repo [{0}]'.format(self._engine_path))
except Exception:
_logg_repo = self._init_repo()
return _logg_repo | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | Load git repo using GitPython |
def reset(self):
watchers.MATCHER.debug("Node <%s> reset", self)
self._reset()
for child in self.children:
child.node.reset() | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list | Reset itself and recursively all its children. |
def _check_stop(self, iters, elapsed_time, converged):
r_c = self.config['resources']
stop = False
if converged==0:
stop=True
if r_c['maximum-iterations'] !='NA' and iters>= r_c['maximum-iterations']:
stop = True
if r_c['max-run-time'] != 'NA' and elapsed_time/60.>= r_c['max-run-time']:
stop = True
return stop | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier false if_statement comparison_operator identifier integer block expression_statement assignment identifier true if_statement boolean_operator comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier true if_statement boolean_operator comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end comparison_operator binary_operator identifier float subscript identifier string string_start string_content string_end block expression_statement assignment identifier true return_statement identifier | Defines the stopping criterion. |
def __total_pages(self) -> int:
row_count = self.model.query.count()
if isinstance(row_count, int):
return int(row_count / self.limit)
return None | module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list if_statement call identifier argument_list identifier identifier block return_statement call identifier argument_list binary_operator identifier attribute identifier identifier return_statement none | Return max pages created by limit |
def _get_len(self):
if hasattr(self._buffer, 'len'):
self._len = self._buffer.len
return
old_pos = self._buffer.tell()
self._buffer.seek(0, 2)
self._len = self._buffer.tell()
self._buffer.seek(old_pos) | module function_definition identifier parameters identifier block if_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list integer integer expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Return total number of bytes in buffer. |
def item(self, section, it):
for key, value in self.section(section, skip=[]):
if key == it:
return value
raise ConfigError(
"Item '{0}' not found in section '{1}'".format(it, section)) | module function_definition identifier parameters identifier identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list identifier keyword_argument identifier list block if_statement comparison_operator identifier identifier block return_statement identifier raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier | Return content of given item in selected section |
def decompressSkeletalBoneData(self, pvCompressedBuffer, unCompressedBufferSize, eTransformSpace, unTransformArrayCount):
fn = self.function_table.decompressSkeletalBoneData
pTransformArray = VRBoneTransform_t()
result = fn(pvCompressedBuffer, unCompressedBufferSize, eTransformSpace, byref(pTransformArray), unTransformArrayCount)
return result, pTransformArray | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier identifier call identifier argument_list identifier identifier return_statement expression_list identifier identifier | Turns a compressed buffer from GetSkeletalBoneDataCompressed and turns it back into a bone transform array. |
def _collapse_to_cwl_record_single(data, want_attrs, input_files):
out = {}
for key in want_attrs:
key_parts = key.split("__")
out[key] = _to_cwl(tz.get_in(key_parts, data), input_files)
return out | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier identifier call identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier return_statement identifier | Convert a single sample into a CWL record. |
def render_node(self):
self.content = self.node.nodelist.render(self.context) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier | Render the template and save the generated content |
def _snapper_pre(opts, jid):
snapper_pre = None
try:
if not opts['test'] and __opts__.get('snapper_states'):
snapper_pre = __salt__['snapper.create_snapshot'](
config=__opts__.get('snapper_states_config', 'root'),
snapshot_type='pre',
description='Salt State run for jid {0}'.format(jid),
__pub_jid=jid)
except Exception:
log.error('Failed to create snapper pre snapshot for jid: %s', jid)
return snapper_pre | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none try_statement block if_statement boolean_operator not_operator subscript identifier 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 call subscript identifier string string_start string_content string_end argument_list keyword_argument identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list 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 return_statement identifier | Create a snapper pre snapshot |
def _parse_endofnames(client, command, actor, args):
args = args.split(" :", 1)[0]
_, _, channel = args.rpartition(' ')
channel = client.server.get_channel(channel) or channel.lower()
client.dispatch_event('MEMBERS', channel) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier boolean_operator call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Parse an ENDOFNAMES and dispatch a NAMES event for the channel. |
def dict_take(dict_, keys, *d):
try:
return list(dict_take_gen(dict_, keys, *d))
except TypeError:
return list(dict_take_gen(dict_, keys, *d))[0] | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block try_statement block return_statement call identifier argument_list call identifier argument_list identifier identifier list_splat identifier except_clause identifier block return_statement subscript call identifier argument_list call identifier argument_list identifier identifier list_splat identifier integer | get multiple values from a dictionary |
def unmount(self):
self.unmount_bindmounts()
self.unmount_mounts()
self.unmount_volume_groups()
self.unmount_loopbacks()
self.unmount_base_images()
self.clean_dirs() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Calls all unmount methods in the correct order. |
def setSequenceType(self, value):
if value == "ordered-continuous":
self.orderedInputs = 1
self.initContext = 0
elif value == "random-segmented":
self.orderedInputs = 0
self.initContext = 1
elif value == "random-continuous":
self.orderedInputs = 0
self.initContext = 0
elif value == "ordered-segmented":
self.orderedInputs = 1
self.initContext = 1
else:
raise AttributeError("invalid sequence type: '%s'" % value)
self.sequenceType = value | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier integer else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier identifier | You must set this! |
def custom_conf(self, conf):
if conf:
for (key, val) in conf.items():
self.__conf[key] = val
return self | module function_definition identifier parameters identifier identifier block if_statement identifier block for_statement tuple_pattern identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier | custom apikey and http parameters |
def in_transaction(self):
if not hasattr(self.local, 'tx'):
return False
return len(self.local.tx) > 0 | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list attribute identifier identifier string string_start string_content string_end block return_statement false return_statement comparison_operator call identifier argument_list attribute attribute identifier identifier identifier integer | Check if this database is in a transactional context. |
def _translate_src_oprnd(self, operand):
if isinstance(operand, ReilRegisterOperand):
return self._translate_src_register_oprnd(operand)
elif isinstance(operand, ReilImmediateOperand):
return smtsymbol.Constant(operand.size, operand.immediate)
else:
raise Exception("Invalid operand type") | 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 attribute identifier identifier attribute identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Translate source operand to a SMT expression. |
def _check_count(self, result, func, args):
if result == 0:
raise ctypes.WinError(ctypes.get_last_error())
return args | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator identifier integer block raise_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Private function to return ctypes errors cleanly |
def version(self):
lines = iter(self._invoke('version').splitlines())
version = next(lines).strip()
return self._parse_version(version) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier | Return the underlying version |
def post(self, url, postParameters=None, urlParameters=None):
if self._action_token == None:
self._action_token = self.get(ReaderUrl.ACTION_TOKEN_URL)
if self._http == None:
self._setupHttp()
uri = url + "?" + self.getParameters(urlParameters)
postParameters.update({'T':self._action_token})
body = self.postParameters(postParameters)
response, content = self._http.request(uri, "POST", body=body)
return content | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end keyword_argument identifier identifier return_statement identifier | Implement libgreader's interface for authenticated POST request |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.