code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _summarize_inputs(samples, out_dir):
"""Summarize inputs for MultiQC reporting in display.
"""
logger.info("summarize target information")
if samples[0].get("analysis", "").lower() in ["variant", "variant2"]:
metrics_dir = utils.safe_makedir(os.path.join(out_dir, "report", "metrics"))
... | def function[_summarize_inputs, parameter[samples, out_dir]]:
constant[Summarize inputs for MultiQC reporting in display.
]
call[name[logger].info, parameter[constant[summarize target information]]]
if compare[call[call[call[name[samples]][constant[0]].get, parameter[constant[analysis], cons... | keyword[def] identifier[_summarize_inputs] ( identifier[samples] , identifier[out_dir] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
keyword[if] identifier[samples] [ literal[int] ]. identifier[get] ( literal[string] , literal[string] ). identifier[lower] () keyword[in]... | def _summarize_inputs(samples, out_dir):
"""Summarize inputs for MultiQC reporting in display.
"""
logger.info('summarize target information')
if samples[0].get('analysis', '').lower() in ['variant', 'variant2']:
metrics_dir = utils.safe_makedir(os.path.join(out_dir, 'report', 'metrics'))
... |
def save_state_with_reason(self, reason, progress, snapshot, state_file_path, pause_vm):
"""Internal method for triggering a VM save state with a specified reason
code. The reason code can be interpreted by device/drivers and thus it
might behave slightly differently than a normal VM save state.... | def function[save_state_with_reason, parameter[self, reason, progress, snapshot, state_file_path, pause_vm]]:
constant[Internal method for triggering a VM save state with a specified reason
code. The reason code can be interpreted by device/drivers and thus it
might behave slightly differently t... | keyword[def] identifier[save_state_with_reason] ( identifier[self] , identifier[reason] , identifier[progress] , identifier[snapshot] , identifier[state_file_path] , identifier[pause_vm] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[reason] , identifier[Reason] )... | def save_state_with_reason(self, reason, progress, snapshot, state_file_path, pause_vm):
"""Internal method for triggering a VM save state with a specified reason
code. The reason code can be interpreted by device/drivers and thus it
might behave slightly differently than a normal VM save state.
... |
def create_on_task(self, task, params={}, **options):
"""Adds a comment to a task. The comment will be authored by the
currently authenticated user, and timestamped when the server receives
the request.
Returns the full record for the new story added to the task.
Param... | def function[create_on_task, parameter[self, task, params]]:
constant[Adds a comment to a task. The comment will be authored by the
currently authenticated user, and timestamped when the server receives
the request.
Returns the full record for the new story added to the task.
... | keyword[def] identifier[create_on_task] ( identifier[self] , identifier[task] , identifier[params] ={},** identifier[options] ):
literal[string]
identifier[path] = literal[string] %( identifier[task] )
keyword[return] identifier[self] . identifier[client] . identifier[post] ( identifier[p... | def create_on_task(self, task, params={}, **options):
"""Adds a comment to a task. The comment will be authored by the
currently authenticated user, and timestamped when the server receives
the request.
Returns the full record for the new story added to the task.
Parameters... |
def _map_smtp_headers_to_api_parameters(self, email_message):
"""
Map the values passed in SMTP headers to API-ready
2-item tuples present in HEADERS_MAP
header values must be a single string or list or tuple of strings
:return: 2-item tuples of the form (api_name, api_values)
... | def function[_map_smtp_headers_to_api_parameters, parameter[self, email_message]]:
constant[
Map the values passed in SMTP headers to API-ready
2-item tuples present in HEADERS_MAP
header values must be a single string or list or tuple of strings
:return: 2-item tuples of the f... | keyword[def] identifier[_map_smtp_headers_to_api_parameters] ( identifier[self] , identifier[email_message] ):
literal[string]
identifier[api_data] =[]
keyword[for] identifier[smtp_key] , identifier[api_transformer] keyword[in] identifier[six] . identifier[iteritems] ( identifier[self] ... | def _map_smtp_headers_to_api_parameters(self, email_message):
"""
Map the values passed in SMTP headers to API-ready
2-item tuples present in HEADERS_MAP
header values must be a single string or list or tuple of strings
:return: 2-item tuples of the form (api_name, api_values)
... |
def promote_artifacts(self, promote_stage='latest'):
"""Promote artifact version to dest.
Args:
promote_stage (string): Stage that is being promoted
"""
if promote_stage.lower() == 'alpha':
self._sync_to_uri(self.s3_canary_uri)
elif promote_stage.lower() ... | def function[promote_artifacts, parameter[self, promote_stage]]:
constant[Promote artifact version to dest.
Args:
promote_stage (string): Stage that is being promoted
]
if compare[call[name[promote_stage].lower, parameter[]] equal[==] constant[alpha]] begin[:]
... | keyword[def] identifier[promote_artifacts] ( identifier[self] , identifier[promote_stage] = literal[string] ):
literal[string]
keyword[if] identifier[promote_stage] . identifier[lower] ()== literal[string] :
identifier[self] . identifier[_sync_to_uri] ( identifier[self] . identifier[s... | def promote_artifacts(self, promote_stage='latest'):
"""Promote artifact version to dest.
Args:
promote_stage (string): Stage that is being promoted
"""
if promote_stage.lower() == 'alpha':
self._sync_to_uri(self.s3_canary_uri) # depends on [control=['if'], data=[]]
eli... |
async def write(self, towrite: bytes, await_blocking=False):
"""
Appends towrite to the write queue
>>> await test.write(b"HELLO")
# Returns without wait time
>>> await test.write(b"HELLO", await_blocking = True)
# Returns when the bufer is flushed
:param towrit... | <ast.AsyncFunctionDef object at 0x7da20c6a93c0> | keyword[async] keyword[def] identifier[write] ( identifier[self] , identifier[towrite] : identifier[bytes] , identifier[await_blocking] = keyword[False] ):
literal[string]
keyword[await] identifier[self] . identifier[_write] ( identifier[towrite] )
keyword[if] identifier[awai... | async def write(self, towrite: bytes, await_blocking=False):
"""
Appends towrite to the write queue
>>> await test.write(b"HELLO")
# Returns without wait time
>>> await test.write(b"HELLO", await_blocking = True)
# Returns when the bufer is flushed
:param towrite: ... |
def get_keys(self, bucket, timeout=None):
"""
Lists all keys within a bucket.
"""
msg_code = riak.pb.messages.MSG_CODE_LIST_KEYS_REQ
codec = self._get_codec(msg_code)
stream = self.stream_keys(bucket, timeout=timeout)
return codec.decode_get_keys(stream) | def function[get_keys, parameter[self, bucket, timeout]]:
constant[
Lists all keys within a bucket.
]
variable[msg_code] assign[=] name[riak].pb.messages.MSG_CODE_LIST_KEYS_REQ
variable[codec] assign[=] call[name[self]._get_codec, parameter[name[msg_code]]]
variable[strea... | keyword[def] identifier[get_keys] ( identifier[self] , identifier[bucket] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[msg_code] = identifier[riak] . identifier[pb] . identifier[messages] . identifier[MSG_CODE_LIST_KEYS_REQ]
identifier[codec] = identifier[self] . id... | def get_keys(self, bucket, timeout=None):
"""
Lists all keys within a bucket.
"""
msg_code = riak.pb.messages.MSG_CODE_LIST_KEYS_REQ
codec = self._get_codec(msg_code)
stream = self.stream_keys(bucket, timeout=timeout)
return codec.decode_get_keys(stream) |
def count_items(self):
"""Counts Items in full_soup and soup. For debugging"""
soup_items = self.soup.findAll('item')
full_soup_items = self.full_soup.findAll('item')
return len(soup_items), len(full_soup_items) | def function[count_items, parameter[self]]:
constant[Counts Items in full_soup and soup. For debugging]
variable[soup_items] assign[=] call[name[self].soup.findAll, parameter[constant[item]]]
variable[full_soup_items] assign[=] call[name[self].full_soup.findAll, parameter[constant[item]]]
re... | keyword[def] identifier[count_items] ( identifier[self] ):
literal[string]
identifier[soup_items] = identifier[self] . identifier[soup] . identifier[findAll] ( literal[string] )
identifier[full_soup_items] = identifier[self] . identifier[full_soup] . identifier[findAll] ( literal[string] )... | def count_items(self):
"""Counts Items in full_soup and soup. For debugging"""
soup_items = self.soup.findAll('item')
full_soup_items = self.full_soup.findAll('item')
return (len(soup_items), len(full_soup_items)) |
def delete_cash_on_delivery_payment_by_id(cls, cash_on_delivery_payment_id, **kwargs):
"""Delete CashOnDeliveryPayment
Delete an instance of CashOnDeliveryPayment by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=... | def function[delete_cash_on_delivery_payment_by_id, parameter[cls, cash_on_delivery_payment_id]]:
constant[Delete CashOnDeliveryPayment
Delete an instance of CashOnDeliveryPayment by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, p... | keyword[def] identifier[delete_cash_on_delivery_payment_by_id] ( identifier[cls] , identifier[cash_on_delivery_payment_id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):... | def delete_cash_on_delivery_payment_by_id(cls, cash_on_delivery_payment_id, **kwargs):
"""Delete CashOnDeliveryPayment
Delete an instance of CashOnDeliveryPayment by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True... |
def model_name(allele, num):
"""
Generate a model name
Parameters
----------
allele : string
num : int
Returns
-------
string
"""
random_string = hashlib.sha1(
str(time.time()).encode()).hexdigest()[:16]
... | def function[model_name, parameter[allele, num]]:
constant[
Generate a model name
Parameters
----------
allele : string
num : int
Returns
-------
string
]
variable[random_string] assign[=] call[call[call[name[hashlib].sha... | keyword[def] identifier[model_name] ( identifier[allele] , identifier[num] ):
literal[string]
identifier[random_string] = identifier[hashlib] . identifier[sha1] (
identifier[str] ( identifier[time] . identifier[time] ()). identifier[encode] ()). identifier[hexdigest] ()[: literal[int] ]
... | def model_name(allele, num):
"""
Generate a model name
Parameters
----------
allele : string
num : int
Returns
-------
string
"""
random_string = hashlib.sha1(str(time.time()).encode()).hexdigest()[:16]
return '%s-%d-%s' % (a... |
def _get_version_info():
"""
Returns the currently-installed awslimitchecker version, and a best-effort
attempt at finding the origin URL and commit/tag if installed from an
editable git clone.
:returns: awslimitchecker version
:rtype: str
"""
if os.environ.get('VERSIONCHECK_DEBUG', '')... | def function[_get_version_info, parameter[]]:
constant[
Returns the currently-installed awslimitchecker version, and a best-effort
attempt at finding the origin URL and commit/tag if installed from an
editable git clone.
:returns: awslimitchecker version
:rtype: str
]
if compare... | keyword[def] identifier[_get_version_info] ():
literal[string]
keyword[if] identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] )!= literal[string] :
keyword[for] identifier[lname] keyword[in] [ literal[string] , literal[string] , literal[string] ]:
... | def _get_version_info():
"""
Returns the currently-installed awslimitchecker version, and a best-effort
attempt at finding the origin URL and commit/tag if installed from an
editable git clone.
:returns: awslimitchecker version
:rtype: str
"""
if os.environ.get('VERSIONCHECK_DEBUG', '')... |
def clean(self):
""" Check user has cookies enabled
"""
if self.request:
if not self.request.session.test_cookie_worked():
raise forms.ValidationError("Cookies must be enabled.")
return self.cleaned_data | def function[clean, parameter[self]]:
constant[ Check user has cookies enabled
]
if name[self].request begin[:]
if <ast.UnaryOp object at 0x7da18dc06890> begin[:]
<ast.Raise object at 0x7da18dc045b0>
return[name[self].cleaned_data] | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[request] :
keyword[if] keyword[not] identifier[self] . identifier[request] . identifier[session] . identifier[test_cookie_worked] ():
keyword[raise] i... | def clean(self):
""" Check user has cookies enabled
"""
if self.request:
if not self.request.session.test_cookie_worked():
raise forms.ValidationError('Cookies must be enabled.') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
return self.cleaned_d... |
def get_form_kwargs(self):
"""
initialize default value that won't be displayed
:return:
"""
kwargs = super(UserServiceUpdateView, self).get_form_kwargs()
kwargs['initial']['user'] = self.request.user
kwargs['initial']['name'] = self.object.name
return kwa... | def function[get_form_kwargs, parameter[self]]:
constant[
initialize default value that won't be displayed
:return:
]
variable[kwargs] assign[=] call[call[name[super], parameter[name[UserServiceUpdateView], name[self]]].get_form_kwargs, parameter[]]
call[call[name[kwargs]... | keyword[def] identifier[get_form_kwargs] ( identifier[self] ):
literal[string]
identifier[kwargs] = identifier[super] ( identifier[UserServiceUpdateView] , identifier[self] ). identifier[get_form_kwargs] ()
identifier[kwargs] [ literal[string] ][ literal[string] ]= identifier[self] . ident... | def get_form_kwargs(self):
"""
initialize default value that won't be displayed
:return:
"""
kwargs = super(UserServiceUpdateView, self).get_form_kwargs()
kwargs['initial']['user'] = self.request.user
kwargs['initial']['name'] = self.object.name
return kwargs |
async def download_file_by_id(self, file_id: base.String, destination=None,
timeout: base.Integer = 30, chunk_size: base.Integer = 65536,
seek: base.Boolean = True):
"""
Download file by file_id to destination
if You want to au... | <ast.AsyncFunctionDef object at 0x7da1b18fb760> | keyword[async] keyword[def] identifier[download_file_by_id] ( identifier[self] , identifier[file_id] : identifier[base] . identifier[String] , identifier[destination] = keyword[None] ,
identifier[timeout] : identifier[base] . identifier[Integer] = literal[int] , identifier[chunk_size] : identifier[base] . identifie... | async def download_file_by_id(self, file_id: base.String, destination=None, timeout: base.Integer=30, chunk_size: base.Integer=65536, seek: base.Boolean=True):
"""
Download file by file_id to destination
if You want to automatically create destination (:class:`io.BytesIO`) use default
value... |
def get_currency_symbols(self) -> List[str]:
""" Returns the used currencies' symbols as an array """
result = []
currencies = self.currencies.get_book_currencies()
for cur in currencies:
result.append(cur.mnemonic)
return result | def function[get_currency_symbols, parameter[self]]:
constant[ Returns the used currencies' symbols as an array ]
variable[result] assign[=] list[[]]
variable[currencies] assign[=] call[name[self].currencies.get_book_currencies, parameter[]]
for taget[name[cur]] in starred[name[currencie... | keyword[def] identifier[get_currency_symbols] ( identifier[self] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[result] =[]
identifier[currencies] = identifier[self] . identifier[currencies] . identifier[get_book_currencies] ()
keyword[for] identifier[cur] ... | def get_currency_symbols(self) -> List[str]:
""" Returns the used currencies' symbols as an array """
result = []
currencies = self.currencies.get_book_currencies()
for cur in currencies:
result.append(cur.mnemonic) # depends on [control=['for'], data=['cur']]
return result |
def snow_partitioning_n(im, r_max=4, sigma=0.4, return_all=True,
mask=True, randomize=False, alias=None):
r"""
This function partitions an imaging oontain an arbitrary number of phases
into regions using a marker-based watershed segmentation. Its an extension
of snow_partitioning... | def function[snow_partitioning_n, parameter[im, r_max, sigma, return_all, mask, randomize, alias]]:
constant[
This function partitions an imaging oontain an arbitrary number of phases
into regions using a marker-based watershed segmentation. Its an extension
of snow_partitioning function with all ph... | keyword[def] identifier[snow_partitioning_n] ( identifier[im] , identifier[r_max] = literal[int] , identifier[sigma] = literal[int] , identifier[return_all] = keyword[True] ,
identifier[mask] = keyword[True] , identifier[randomize] = keyword[False] , identifier[alias] = keyword[None] ):
literal[string]
... | def snow_partitioning_n(im, r_max=4, sigma=0.4, return_all=True, mask=True, randomize=False, alias=None):
"""
This function partitions an imaging oontain an arbitrary number of phases
into regions using a marker-based watershed segmentation. Its an extension
of snow_partitioning function with all phases... |
def _set_auditpol_data(option, value):
'''
Helper function that updates the current applied settings to match what has
just been set in the audit.csv files. We're doing it this way instead of
running `gpupdate`
Args:
option (str): The name of the option to set
value (str): The value... | def function[_set_auditpol_data, parameter[option, value]]:
constant[
Helper function that updates the current applied settings to match what has
just been set in the audit.csv files. We're doing it this way instead of
running `gpupdate`
Args:
option (str): The name of the option to set... | keyword[def] identifier[_set_auditpol_data] ( identifier[option] , identifier[value] ):
literal[string]
identifier[auditpol_values] ={ literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[... | def _set_auditpol_data(option, value):
"""
Helper function that updates the current applied settings to match what has
just been set in the audit.csv files. We're doing it this way instead of
running `gpupdate`
Args:
option (str): The name of the option to set
value (str): The value... |
def read_touchstone(fname):
r"""
Read a `Touchstone <https://ibis.org/connector/touchstone_spec11.pdf>`_ file.
According to the specification a data line can have at most values for four
complex parameters (plus potentially the frequency point), however this
function is able to process malformed fi... | def function[read_touchstone, parameter[fname]]:
constant[
Read a `Touchstone <https://ibis.org/connector/touchstone_spec11.pdf>`_ file.
According to the specification a data line can have at most values for four
complex parameters (plus potentially the frequency point), however this
function i... | keyword[def] identifier[read_touchstone] ( identifier[fname] ):
literal[string]
identifier[exnports] = identifier[pexdoc] . identifier[exh] . identifier[addex] (
identifier[RuntimeError] , literal[string]
)
identifier[exnoopt] = identifier[pexdoc] . identifier[exh] . identifier[add... | def read_touchstone(fname):
"""
Read a `Touchstone <https://ibis.org/connector/touchstone_spec11.pdf>`_ file.
According to the specification a data line can have at most values for four
complex parameters (plus potentially the frequency point), however this
function is able to process malformed fil... |
def _repr_label_vector(self, label_vector):
"""
Return a human-readable representation of the Cannon label vector.
label_vector should be [[(1,2), (2,1)], [(1,3)]] etc.
"""
string = ["1"]
for cross_terms in label_vector:
sub_string = []
... | def function[_repr_label_vector, parameter[self, label_vector]]:
constant[
Return a human-readable representation of the Cannon label vector.
label_vector should be [[(1,2), (2,1)], [(1,3)]] etc.
]
variable[string] assign[=] list[[<ast.Constant object at 0x7da18fe93c10>... | keyword[def] identifier[_repr_label_vector] ( identifier[self] , identifier[label_vector] ):
literal[string]
identifier[string] =[ literal[string] ]
keyword[for] identifier[cross_terms] keyword[in] identifier[label_vector] :
identifier[sub_string] =[]
keyword[... | def _repr_label_vector(self, label_vector):
"""
Return a human-readable representation of the Cannon label vector.
label_vector should be [[(1,2), (2,1)], [(1,3)]] etc.
"""
string = ['1']
for cross_terms in label_vector:
sub_string = []
for (index, order) in... |
def add(name, **kwargs):
'''
Add a job to the schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.add job1 function='test.ping' seconds=3600
# If function have some arguments, use job_args
salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log... | def function[add, parameter[name]]:
constant[
Add a job to the schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.add job1 function='test.ping' seconds=3600
# If function have some arguments, use job_args
salt '*' schedule.add job2 function='cmd.run' job_args="['... | keyword[def] identifier[add] ( identifier[name] ,** identifier[kwargs] ):
literal[string]
identifier[ret] ={ literal[string] : literal[string] . identifier[format] ( identifier[name] ),
literal[string] : keyword[False] }
keyword[if] identifier[name] keyword[in] identifier[list_] ( identifier... | def add(name, **kwargs):
"""
Add a job to the schedule
CLI Example:
.. code-block:: bash
salt '*' schedule.add job1 function='test.ping' seconds=3600
# If function have some arguments, use job_args
salt '*' schedule.add job2 function='cmd.run' job_args="['date >> /tmp/date.log... |
def append(self, key, value):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists."""
self.__items.append((key, value))
try:
dict_getitem(self, key).append(value)
except KeyError:
dict_setitem(self, key, [value]) | def function[append, parameter[self, key, value]]:
constant[Adds a (name, value) pair, doesn't overwrite the value if it already
exists.]
call[name[self].__items.append, parameter[tuple[[<ast.Name object at 0x7da1b05ec7f0>, <ast.Name object at 0x7da1b05ef760>]]]]
<ast.Try object at 0x7da1b05... | keyword[def] identifier[append] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
identifier[self] . identifier[__items] . identifier[append] (( identifier[key] , identifier[value] ))
keyword[try] :
identifier[dict_getitem] ( identifier[self] , ident... | def append(self, key, value):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists."""
self.__items.append((key, value))
try:
dict_getitem(self, key).append(value) # depends on [control=['try'], data=[]]
except KeyError:
dict_setitem(self, key, [value])... |
def update(self, d):
"""Update the dict with the dict tree in parameter d.
Parameters
----------
d : dict
New dict content
"""
# Call __setitem__ for all keys in d
for key in list(d.keys()):
self.__setitem__(key, d[key]) | def function[update, parameter[self, d]]:
constant[Update the dict with the dict tree in parameter d.
Parameters
----------
d : dict
New dict content
]
for taget[name[key]] in starred[call[name[list], parameter[call[name[d].keys, parameter[]]]]] begin[:]
... | keyword[def] identifier[update] ( identifier[self] , identifier[d] ):
literal[string]
keyword[for] identifier[key] keyword[in] identifier[list] ( identifier[d] . identifier[keys] ()):
identifier[self] . identifier[__setitem__] ( identifier[key] , identifier[d] [ identifier... | def update(self, d):
"""Update the dict with the dict tree in parameter d.
Parameters
----------
d : dict
New dict content
"""
# Call __setitem__ for all keys in d
for key in list(d.keys()):
self.__setitem__(key, d[key]) # depends on [control=['for'], data... |
def get(self, key):
"""
Transactional implementation of :func:`Map.get(key) <hazelcast.proxy.map.Map.get>`
:param key: (object), the specified key.
:return: (object), the value for the specified key.
"""
check_not_none(key, "key can't be none")
return self._encod... | def function[get, parameter[self, key]]:
constant[
Transactional implementation of :func:`Map.get(key) <hazelcast.proxy.map.Map.get>`
:param key: (object), the specified key.
:return: (object), the value for the specified key.
]
call[name[check_not_none], parameter[name[... | keyword[def] identifier[get] ( identifier[self] , identifier[key] ):
literal[string]
identifier[check_not_none] ( identifier[key] , literal[string] )
keyword[return] identifier[self] . identifier[_encode_invoke] ( identifier[transactional_map_get_codec] , identifier[key] = identifier[self... | def get(self, key):
"""
Transactional implementation of :func:`Map.get(key) <hazelcast.proxy.map.Map.get>`
:param key: (object), the specified key.
:return: (object), the value for the specified key.
"""
check_not_none(key, "key can't be none")
return self._encode_invoke(tra... |
def toURLEncoded(self):
"""Generate an x-www-urlencoded string"""
args = sorted(self.toPostArgs().items())
return urllib.parse.urlencode(args) | def function[toURLEncoded, parameter[self]]:
constant[Generate an x-www-urlencoded string]
variable[args] assign[=] call[name[sorted], parameter[call[call[name[self].toPostArgs, parameter[]].items, parameter[]]]]
return[call[name[urllib].parse.urlencode, parameter[name[args]]]] | keyword[def] identifier[toURLEncoded] ( identifier[self] ):
literal[string]
identifier[args] = identifier[sorted] ( identifier[self] . identifier[toPostArgs] (). identifier[items] ())
keyword[return] identifier[urllib] . identifier[parse] . identifier[urlencode] ( identifier[args] ) | def toURLEncoded(self):
"""Generate an x-www-urlencoded string"""
args = sorted(self.toPostArgs().items())
return urllib.parse.urlencode(args) |
def _merge_statement_lists(stmsA: List["HdlStatement"], stmsB: List["HdlStatement"])\
-> List["HdlStatement"]:
"""
Merge two lists of statements into one
:return: list of merged statements
"""
if stmsA is None and stmsB is None:
return None
tmp =... | def function[_merge_statement_lists, parameter[stmsA, stmsB]]:
constant[
Merge two lists of statements into one
:return: list of merged statements
]
if <ast.BoolOp object at 0x7da1b032f2e0> begin[:]
return[constant[None]]
variable[tmp] assign[=] list[[]]
... | keyword[def] identifier[_merge_statement_lists] ( identifier[stmsA] : identifier[List] [ literal[string] ], identifier[stmsB] : identifier[List] [ literal[string] ])-> identifier[List] [ literal[string] ]:
literal[string]
keyword[if] identifier[stmsA] keyword[is] keyword[None] keyword[and] ide... | def _merge_statement_lists(stmsA: List['HdlStatement'], stmsB: List['HdlStatement']) -> List['HdlStatement']:
"""
Merge two lists of statements into one
:return: list of merged statements
"""
if stmsA is None and stmsB is None:
return None # depends on [control=['if'], data=[]]... |
def wait_for_event(self, emptybuffer=False):
"""
Waits until a joystick event becomes available. Returns the event, as
an `InputEvent` tuple.
If *emptybuffer* is `True` (it defaults to `False`), any pending
events will be thrown away first. This is most useful if you are only
... | def function[wait_for_event, parameter[self, emptybuffer]]:
constant[
Waits until a joystick event becomes available. Returns the event, as
an `InputEvent` tuple.
If *emptybuffer* is `True` (it defaults to `False`), any pending
events will be thrown away first. This is most use... | keyword[def] identifier[wait_for_event] ( identifier[self] , identifier[emptybuffer] = keyword[False] ):
literal[string]
keyword[if] identifier[emptybuffer] :
keyword[while] identifier[self] . identifier[_wait] ( literal[int] ):
identifier[self] . identifier[_read] (... | def wait_for_event(self, emptybuffer=False):
"""
Waits until a joystick event becomes available. Returns the event, as
an `InputEvent` tuple.
If *emptybuffer* is `True` (it defaults to `False`), any pending
events will be thrown away first. This is most useful if you are only
... |
def compute_ratio(x):
"""
计算每一类数据的占比
"""
sum_ = sum(x)
ratios = []
for i in x:
ratio = i / sum_
ratios.append(ratio)
return ratios | def function[compute_ratio, parameter[x]]:
constant[
计算每一类数据的占比
]
variable[sum_] assign[=] call[name[sum], parameter[name[x]]]
variable[ratios] assign[=] list[[]]
for taget[name[i]] in starred[name[x]] begin[:]
variable[ratio] assign[=] binary_operation[na... | keyword[def] identifier[compute_ratio] ( identifier[x] ):
literal[string]
identifier[sum_] = identifier[sum] ( identifier[x] )
identifier[ratios] =[]
keyword[for] identifier[i] keyword[in] identifier[x] :
identifier[ratio] = identifier[i] / identifier[sum_]
... | def compute_ratio(x):
"""
计算每一类数据的占比
"""
sum_ = sum(x)
ratios = []
for i in x:
ratio = i / sum_
ratios.append(ratio) # depends on [control=['for'], data=['i']]
return ratios |
def get_favicon(self, article):
"""\
Extract the favicon from a website
http://en.wikipedia.org/wiki/Favicon
<link rel="shortcut icon" type="image/png" href="favicon.png" />
<link rel="icon" type="image/png" href="favicon.png" />
"""
kwargs = {'tag': 'link', 'attr... | def function[get_favicon, parameter[self, article]]:
constant[ Extract the favicon from a website
http://en.wikipedia.org/wiki/Favicon
<link rel="shortcut icon" type="image/png" href="favicon.png" />
<link rel="icon" type="image/png" href="favicon.png" />
]
variabl... | keyword[def] identifier[get_favicon] ( identifier[self] , identifier[article] ):
literal[string]
identifier[kwargs] ={ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] }
identifier[meta] = identifier[self] . identifier[parser] . iden... | def get_favicon(self, article):
""" Extract the favicon from a website
http://en.wikipedia.org/wiki/Favicon
<link rel="shortcut icon" type="image/png" href="favicon.png" />
<link rel="icon" type="image/png" href="favicon.png" />
"""
kwargs = {'tag': 'link', 'attr': 'rel', ... |
def check_type(param, datatype):
"""
Make sure that param is of type datatype and return it.
If param is None, return it.
If param is an instance of datatype, return it.
If param is not an instance of datatype and is not None, cast it as
datatype and return it.
"""
if param is None:
... | def function[check_type, parameter[param, datatype]]:
constant[
Make sure that param is of type datatype and return it.
If param is None, return it.
If param is an instance of datatype, return it.
If param is not an instance of datatype and is not None, cast it as
datatype and return it.
... | keyword[def] identifier[check_type] ( identifier[param] , identifier[datatype] ):
literal[string]
keyword[if] identifier[param] keyword[is] keyword[None] :
keyword[return] identifier[param]
keyword[if] identifier[getattr] ( identifier[datatype] , literal[string] , keyword[None] ) keywo... | def check_type(param, datatype):
"""
Make sure that param is of type datatype and return it.
If param is None, return it.
If param is an instance of datatype, return it.
If param is not an instance of datatype and is not None, cast it as
datatype and return it.
"""
if param is None:
... |
def f_lock_parameters(self):
"""Locks all non-empty parameters"""
for par in self._parameters.values():
if not par.f_is_empty():
par.f_lock() | def function[f_lock_parameters, parameter[self]]:
constant[Locks all non-empty parameters]
for taget[name[par]] in starred[call[name[self]._parameters.values, parameter[]]] begin[:]
if <ast.UnaryOp object at 0x7da1b038b820> begin[:]
call[name[par].f_lock, paramete... | keyword[def] identifier[f_lock_parameters] ( identifier[self] ):
literal[string]
keyword[for] identifier[par] keyword[in] identifier[self] . identifier[_parameters] . identifier[values] ():
keyword[if] keyword[not] identifier[par] . identifier[f_is_empty] ():
iden... | def f_lock_parameters(self):
"""Locks all non-empty parameters"""
for par in self._parameters.values():
if not par.f_is_empty():
par.f_lock() # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['par']] |
def get_static_dependencies(self, dependencies=None, include_beta=None):
"""Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param d... | def function[get_static_dependencies, parameter[self, dependencies, include_beta]]:
constant[Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:... | keyword[def] identifier[get_static_dependencies] ( identifier[self] , identifier[dependencies] = keyword[None] , identifier[include_beta] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[dependencies] :
identifier[dependencies] = identifier[self] . identifier[pr... | def get_static_dependencies(self, dependencies=None, include_beta=None):
"""Resolves the project -> dependencies section of cumulusci.yml
to convert dynamic github dependencies into static dependencies
by inspecting the referenced repositories
Keyword arguments:
:param depen... |
def express_route_cross_connection_peerings(self):
"""Instance depends on the API version:
* 2018-02-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-04-01: :class:`ExpressRouteCrossC... | def function[express_route_cross_connection_peerings, parameter[self]]:
constant[Instance depends on the API version:
* 2018-02-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-04-01:... | keyword[def] identifier[express_route_cross_connection_peerings] ( identifier[self] ):
literal[string]
identifier[api_version] = identifier[self] . identifier[_get_api_version] ( literal[string] )
keyword[if] identifier[api_version] == literal[string] :
keyword[from] . identi... | def express_route_cross_connection_peerings(self):
"""Instance depends on the API version:
* 2018-02-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-04-01: :class:`ExpressRouteCrossConne... |
def loader():
"""Load image from URL, and preprocess for Resnet."""
url = request.args.get('url') # read image URL as a request URL param
response = requests.get(url) # make request to static image file
return response.content | def function[loader, parameter[]]:
constant[Load image from URL, and preprocess for Resnet.]
variable[url] assign[=] call[name[request].args.get, parameter[constant[url]]]
variable[response] assign[=] call[name[requests].get, parameter[name[url]]]
return[name[response].content] | keyword[def] identifier[loader] ():
literal[string]
identifier[url] = identifier[request] . identifier[args] . identifier[get] ( literal[string] )
identifier[response] = identifier[requests] . identifier[get] ( identifier[url] )
keyword[return] identifier[response] . identifier[content] | def loader():
"""Load image from URL, and preprocess for Resnet."""
url = request.args.get('url') # read image URL as a request URL param
response = requests.get(url) # make request to static image file
return response.content |
def get_all(self, name, default=None):
"""make cookie python 3 version use this instead of getheaders"""
if default is None:
default = []
return self._headers.get_list(name) or default | def function[get_all, parameter[self, name, default]]:
constant[make cookie python 3 version use this instead of getheaders]
if compare[name[default] is constant[None]] begin[:]
variable[default] assign[=] list[[]]
return[<ast.BoolOp object at 0x7da1b21d5360>] | keyword[def] identifier[get_all] ( identifier[self] , identifier[name] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[default] keyword[is] keyword[None] :
identifier[default] =[]
keyword[return] identifier[self] . identifier[_headers] . ide... | def get_all(self, name, default=None):
"""make cookie python 3 version use this instead of getheaders"""
if default is None:
default = [] # depends on [control=['if'], data=['default']]
return self._headers.get_list(name) or default |
def run_align(*data):
"""
Prepare data to run alignment step, only once for each project
"""
work_dir = dd.get_work_dir(data[0][0])
out_dir = op.join(work_dir, "seqcluster", "prepare")
seq_out = op.join(out_dir, "seqs.fastq")
bam_dir = op.join(work_dir, "align")
new_bam_file = op.join(ba... | def function[run_align, parameter[]]:
constant[
Prepare data to run alignment step, only once for each project
]
variable[work_dir] assign[=] call[name[dd].get_work_dir, parameter[call[call[name[data]][constant[0]]][constant[0]]]]
variable[out_dir] assign[=] call[name[op].join, parameter... | keyword[def] identifier[run_align] (* identifier[data] ):
literal[string]
identifier[work_dir] = identifier[dd] . identifier[get_work_dir] ( identifier[data] [ literal[int] ][ literal[int] ])
identifier[out_dir] = identifier[op] . identifier[join] ( identifier[work_dir] , literal[string] , literal[str... | def run_align(*data):
"""
Prepare data to run alignment step, only once for each project
"""
work_dir = dd.get_work_dir(data[0][0])
out_dir = op.join(work_dir, 'seqcluster', 'prepare')
seq_out = op.join(out_dir, 'seqs.fastq')
bam_dir = op.join(work_dir, 'align')
new_bam_file = op.join(ba... |
def _tab_newline_replace(self,fromlines,tolines):
"""Returns from/to line lists with tabs expanded and newlines removed.
Instead of tab characters being replaced by the number of spaces
needed to fill in to the next tab stop, this function will fill
the space with tab characters. This ... | def function[_tab_newline_replace, parameter[self, fromlines, tolines]]:
constant[Returns from/to line lists with tabs expanded and newlines removed.
Instead of tab characters being replaced by the number of spaces
needed to fill in to the next tab stop, this function will fill
the spac... | keyword[def] identifier[_tab_newline_replace] ( identifier[self] , identifier[fromlines] , identifier[tolines] ):
literal[string]
keyword[def] identifier[expand_tabs] ( identifier[line] ):
identifier[line] = identifier[line] . identifier[replace] ( literal[string] , literal[s... | def _tab_newline_replace(self, fromlines, tolines):
"""Returns from/to line lists with tabs expanded and newlines removed.
Instead of tab characters being replaced by the number of spaces
needed to fill in to the next tab stop, this function will fill
the space with tab characters. This is... |
def add_child(self, n, parent, **attrs):
'''
API: add_child(self, n, parent, **attrs)
Description:
Adds child n to node parent and return Node n.
Pre:
Node with name parent should exist.
Input:
n: Child node name.
parent: Parent nod... | def function[add_child, parameter[self, n, parent]]:
constant[
API: add_child(self, n, parent, **attrs)
Description:
Adds child n to node parent and return Node n.
Pre:
Node with name parent should exist.
Input:
n: Child node name.
... | keyword[def] identifier[add_child] ( identifier[self] , identifier[n] , identifier[parent] ,** identifier[attrs] ):
literal[string]
identifier[attrs] [ literal[string] ]= identifier[self] . identifier[get_node] ( identifier[parent] ). identifier[get_attr] ( literal[string] )+ literal[int]
... | def add_child(self, n, parent, **attrs):
"""
API: add_child(self, n, parent, **attrs)
Description:
Adds child n to node parent and return Node n.
Pre:
Node with name parent should exist.
Input:
n: Child node name.
parent: Parent node na... |
def _handle_decl_list(self, node, scope, ctxt, stream):
"""Handle For nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling decl list")
# just handle each declaration
for decl in node.decls:
... | def function[_handle_decl_list, parameter[self, node, scope, ctxt, stream]]:
constant[Handle For nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
]
call[name[self]._dlog, parameter[constant[handling decl list]]]
for taget[n... | keyword[def] identifier[_handle_decl_list] ( identifier[self] , identifier[node] , identifier[scope] , identifier[ctxt] , identifier[stream] ):
literal[string]
identifier[self] . identifier[_dlog] ( literal[string] )
keyword[for] identifier[decl] keyword[in] identifier[node] . ... | def _handle_decl_list(self, node, scope, ctxt, stream):
"""Handle For nodes
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog('handling decl list')
# just handle each declaration
for decl in node.decls:
self._handle... |
def print_inheritance(doc, stream):
# type: (List[Dict[Text, Any]], IO) -> None
"""Write a Grapviz inheritance graph for the supplied document."""
stream.write("digraph {\n")
for entry in doc:
if entry["type"] == "record":
label = name = shortname(entry["name"])
fields = ... | def function[print_inheritance, parameter[doc, stream]]:
constant[Write a Grapviz inheritance graph for the supplied document.]
call[name[stream].write, parameter[constant[digraph {
]]]
for taget[name[entry]] in starred[name[doc]] begin[:]
if compare[call[name[entry]][constant[ty... | keyword[def] identifier[print_inheritance] ( identifier[doc] , identifier[stream] ):
literal[string]
identifier[stream] . identifier[write] ( literal[string] )
keyword[for] identifier[entry] keyword[in] identifier[doc] :
keyword[if] identifier[entry] [ literal[string] ]== literal[string]... | def print_inheritance(doc, stream):
# type: (List[Dict[Text, Any]], IO) -> None
'Write a Grapviz inheritance graph for the supplied document.'
stream.write('digraph {\n')
for entry in doc:
if entry['type'] == 'record':
label = name = shortname(entry['name'])
fields = entr... |
def _deserialize_primitive(data, klass):
"""Deserializes to primitive type.
:param data: data to deserialize.
:param klass: class literal.
:return: int, long, float, str, bool.
:rtype: int | long | float | str | bool
"""
try:
value = klass(data)
except UnicodeEncodeError:
... | def function[_deserialize_primitive, parameter[data, klass]]:
constant[Deserializes to primitive type.
:param data: data to deserialize.
:param klass: class literal.
:return: int, long, float, str, bool.
:rtype: int | long | float | str | bool
]
<ast.Try object at 0x7da207f01600>
r... | keyword[def] identifier[_deserialize_primitive] ( identifier[data] , identifier[klass] ):
literal[string]
keyword[try] :
identifier[value] = identifier[klass] ( identifier[data] )
keyword[except] identifier[UnicodeEncodeError] :
identifier[value] = identifier[six] . identifier[u] ( ... | def _deserialize_primitive(data, klass):
"""Deserializes to primitive type.
:param data: data to deserialize.
:param klass: class literal.
:return: int, long, float, str, bool.
:rtype: int | long | float | str | bool
"""
try:
value = klass(data) # depends on [control=['try'], data... |
def _tf_predict(model_dir, input_csvlines):
"""Prediction with a tf savedmodel.
Args:
model_dir: directory that contains a saved model
input_csvlines: list of csv strings
Returns:
Dict in the form tensor_name:prediction_list. Note that the value is always
a list, even if there was only 1 row... | def function[_tf_predict, parameter[model_dir, input_csvlines]]:
constant[Prediction with a tf savedmodel.
Args:
model_dir: directory that contains a saved model
input_csvlines: list of csv strings
Returns:
Dict in the form tensor_name:prediction_list. Note that the value is always
a l... | keyword[def] identifier[_tf_predict] ( identifier[model_dir] , identifier[input_csvlines] ):
literal[string]
keyword[with] identifier[tf] . identifier[Graph] (). identifier[as_default] (), identifier[tf] . identifier[Session] () keyword[as] identifier[sess] :
identifier[input_alias_map] , identifier[ou... | def _tf_predict(model_dir, input_csvlines):
"""Prediction with a tf savedmodel.
Args:
model_dir: directory that contains a saved model
input_csvlines: list of csv strings
Returns:
Dict in the form tensor_name:prediction_list. Note that the value is always
a list, even if there was only 1 r... |
def __industry_code(self):
''' import industry_code '''
csv_path = os.path.join(os.path.dirname(__file__),
self.industry_code_files)
with open(csv_path) as csv_file:
csv_data = csv.reader(csv_file)
result = {}
for i in csv_data:
... | def function[__industry_code, parameter[self]]:
constant[ import industry_code ]
variable[csv_path] assign[=] call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[name[__file__]]], name[self].industry_code_files]]
with call[name[open], parameter[name[csv_path]]] begin[:]
... | keyword[def] identifier[__industry_code] ( identifier[self] ):
literal[string]
identifier[csv_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ),
identifier[self] . identifier[industry_code_files] ... | def __industry_code(self):
""" import industry_code """
csv_path = os.path.join(os.path.dirname(__file__), self.industry_code_files)
with open(csv_path) as csv_file:
csv_data = csv.reader(csv_file)
result = {}
for i in csv_data:
result[i[0]] = i[1].decode('utf-8') # depe... |
def lock(self, lock_name, timeout=900):
"""
Attempt to use lock and unlock, which will work if the Cache is Redis,
but fall back to a memcached-compliant add/delete approach.
If the Jobtastic Cache isn't Redis or Memcache, or another product
with a compatible lock or add/delete ... | def function[lock, parameter[self, lock_name, timeout]]:
constant[
Attempt to use lock and unlock, which will work if the Cache is Redis,
but fall back to a memcached-compliant add/delete approach.
If the Jobtastic Cache isn't Redis or Memcache, or another product
with a compati... | keyword[def] identifier[lock] ( identifier[self] , identifier[lock_name] , identifier[timeout] = literal[int] ):
literal[string]
keyword[try] :
keyword[try] :
identifier[lock] = identifier[self] . identifier[cache] . identifier[lock]
keyword[exce... | def lock(self, lock_name, timeout=900):
"""
Attempt to use lock and unlock, which will work if the Cache is Redis,
but fall back to a memcached-compliant add/delete approach.
If the Jobtastic Cache isn't Redis or Memcache, or another product
with a compatible lock or add/delete API,... |
def set(self, dct) :
"""Set the store using a dictionary"""
# if not self.mustValidate :
# self.store = dct
# self.patchStore = dct
# return
for field, value in dct.items() :
if field not in self.collection.arangoPrivates :
if isin... | def function[set, parameter[self, dct]]:
constant[Set the store using a dictionary]
for taget[tuple[[<ast.Name object at 0x7da1b0de3580>, <ast.Name object at 0x7da1b0de3250>]]] in starred[call[name[dct].items, parameter[]]] begin[:]
if compare[name[field] <ast.NotIn object at 0x7da2590d7... | keyword[def] identifier[set] ( identifier[self] , identifier[dct] ):
literal[string]
keyword[for] identifier[field] , identifier[value] keyword[in] identifier[dct] . identifier[items] ():
keyword[if] identifier[field] keyword[not] keyword[in] ... | def set(self, dct):
"""Set the store using a dictionary"""
# if not self.mustValidate :
# self.store = dct
# self.patchStore = dct
# return
for (field, value) in dct.items():
if field not in self.collection.arangoPrivates:
if isinstance(value, dict):
... |
def on_audio_adapter_change(self, audio_adapter):
"""Triggerd when settings of the audio adapter of the
associated virtual machine have changed.
in audio_adapter of type :class:`IAudioAdapter`
raises :class:`VBoxErrorInvalidVmState`
Session state prevents operation.
... | def function[on_audio_adapter_change, parameter[self, audio_adapter]]:
constant[Triggerd when settings of the audio adapter of the
associated virtual machine have changed.
in audio_adapter of type :class:`IAudioAdapter`
raises :class:`VBoxErrorInvalidVmState`
Session state ... | keyword[def] identifier[on_audio_adapter_change] ( identifier[self] , identifier[audio_adapter] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[audio_adapter] , identifier[IAudioAdapter] ):
keyword[raise] identifier[TypeError] ( literal[string] )
... | def on_audio_adapter_change(self, audio_adapter):
"""Triggerd when settings of the audio adapter of the
associated virtual machine have changed.
in audio_adapter of type :class:`IAudioAdapter`
raises :class:`VBoxErrorInvalidVmState`
Session state prevents operation.
... |
def parse(string, language=None):
"""
Return a solution to the equation in the input string.
"""
if language:
string = replace_word_tokens(string, language)
tokens = tokenize(string)
postfix = to_postfix(tokens)
return evaluate_postfix(postfix) | def function[parse, parameter[string, language]]:
constant[
Return a solution to the equation in the input string.
]
if name[language] begin[:]
variable[string] assign[=] call[name[replace_word_tokens], parameter[name[string], name[language]]]
variable[tokens] assign[=] c... | keyword[def] identifier[parse] ( identifier[string] , identifier[language] = keyword[None] ):
literal[string]
keyword[if] identifier[language] :
identifier[string] = identifier[replace_word_tokens] ( identifier[string] , identifier[language] )
identifier[tokens] = identifier[tokenize] ( ide... | def parse(string, language=None):
"""
Return a solution to the equation in the input string.
"""
if language:
string = replace_word_tokens(string, language) # depends on [control=['if'], data=[]]
tokens = tokenize(string)
postfix = to_postfix(tokens)
return evaluate_postfix(postfix) |
def tryCComment(self, block):
"""C comment checking. If the previous line begins with a "/*" or a "* ", then
return its leading white spaces + ' *' + the white spaces after the *
return: filler string or null, if not in a C comment
"""
indentation = None
prevNonEmptyBloc... | def function[tryCComment, parameter[self, block]]:
constant[C comment checking. If the previous line begins with a "/*" or a "* ", then
return its leading white spaces + ' *' + the white spaces after the *
return: filler string or null, if not in a C comment
]
variable[indentatio... | keyword[def] identifier[tryCComment] ( identifier[self] , identifier[block] ):
literal[string]
identifier[indentation] = keyword[None]
identifier[prevNonEmptyBlock] = identifier[self] . identifier[_prevNonEmptyBlock] ( identifier[block] )
keyword[if] keyword[not] identifier[pr... | def tryCComment(self, block):
"""C comment checking. If the previous line begins with a "/*" or a "* ", then
return its leading white spaces + ' *' + the white spaces after the *
return: filler string or null, if not in a C comment
"""
indentation = None
prevNonEmptyBlock = self._pre... |
def combine(path1, path2):
# type: (Text, Text) -> Text
"""Join two paths together.
This is faster than :func:`~fs.path.join`, but only works when the
second path is relative, and there are no back references in either
path.
Arguments:
path1 (str): A PyFilesytem path.
path2 (st... | def function[combine, parameter[path1, path2]]:
constant[Join two paths together.
This is faster than :func:`~fs.path.join`, but only works when the
second path is relative, and there are no back references in either
path.
Arguments:
path1 (str): A PyFilesytem path.
path2 (str)... | keyword[def] identifier[combine] ( identifier[path1] , identifier[path2] ):
literal[string]
keyword[if] keyword[not] identifier[path1] :
keyword[return] identifier[path2] . identifier[lstrip] ()
keyword[return] literal[string] . identifier[format] ( identifier[path1] . identifier[rstrip]... | def combine(path1, path2):
# type: (Text, Text) -> Text
'Join two paths together.\n\n This is faster than :func:`~fs.path.join`, but only works when the\n second path is relative, and there are no back references in either\n path.\n\n Arguments:\n path1 (str): A PyFilesytem path.\n pat... |
def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None):
"""
Create an Assignment Group.
Create a new assignment group for this course.
"""
path = {}
data = {}
params... | def function[create_assignment_group, parameter[self, course_id, group_weight, integration_data, name, position, rules, sis_source_id]]:
constant[
Create an Assignment Group.
Create a new assignment group for this course.
]
variable[path] assign[=] dictionary[[], []]
var... | keyword[def] identifier[create_assignment_group] ( identifier[self] , identifier[course_id] , identifier[group_weight] = keyword[None] , identifier[integration_data] = keyword[None] , identifier[name] = keyword[None] , identifier[position] = keyword[None] , identifier[rules] = keyword[None] , identifier[sis_source_id... | def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None):
"""
Create an Assignment Group.
Create a new assignment group for this course.
"""
path = {}
data = {}
params = {} # REQUIRED - PATH... |
def generate_query(command):
"""Add header, checksum and footer to command data."""
data = bytearray(command)
c = checksum(data)
data.append(c >> 8)
data.append(c & 0xFF)
data.replace(b'\xFE', b'\xFE\xF0')
data = bytearray.fromhex("FEFE") + data + bytearray.fromhex("FE0D")
return data | def function[generate_query, parameter[command]]:
constant[Add header, checksum and footer to command data.]
variable[data] assign[=] call[name[bytearray], parameter[name[command]]]
variable[c] assign[=] call[name[checksum], parameter[name[data]]]
call[name[data].append, parameter[binary... | keyword[def] identifier[generate_query] ( identifier[command] ):
literal[string]
identifier[data] = identifier[bytearray] ( identifier[command] )
identifier[c] = identifier[checksum] ( identifier[data] )
identifier[data] . identifier[append] ( identifier[c] >> literal[int] )
identifier[data]... | def generate_query(command):
"""Add header, checksum and footer to command data."""
data = bytearray(command)
c = checksum(data)
data.append(c >> 8)
data.append(c & 255)
data.replace(b'\xfe', b'\xfe\xf0')
data = bytearray.fromhex('FEFE') + data + bytearray.fromhex('FE0D')
return data |
def approvecommittee(self, committees, account=None, **kwargs):
""" Approve a committee
:param list committees: list of committee member name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``)
"""
if not ... | def function[approvecommittee, parameter[self, committees, account]]:
constant[ Approve a committee
:param list committees: list of committee member name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``)
]
... | keyword[def] identifier[approvecommittee] ( identifier[self] , identifier[committees] , identifier[account] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[account] :
keyword[if] literal[string] keyword[in] identifier[self] . identifie... | def approvecommittee(self, committees, account=None, **kwargs):
""" Approve a committee
:param list committees: list of committee member name or id
:param str account: (optional) the account to allow access
to (defaults to ``default_account``)
"""
if not account:... |
def xmllint_format(xml):
"""
Pretty-print XML like ``xmllint`` does.
Arguments:
xml (string): Serialized XML
"""
parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True)
document = ET.fromstring(xml, parser)
return ('%s\n%s' % ('<?xml version="1.0" en... | def function[xmllint_format, parameter[xml]]:
constant[
Pretty-print XML like ``xmllint`` does.
Arguments:
xml (string): Serialized XML
]
variable[parser] assign[=] call[name[ET].XMLParser, parameter[]]
variable[document] assign[=] call[name[ET].fromstring, parameter[name[xm... | keyword[def] identifier[xmllint_format] ( identifier[xml] ):
literal[string]
identifier[parser] = identifier[ET] . identifier[XMLParser] ( identifier[resolve_entities] = keyword[False] , identifier[strip_cdata] = keyword[False] , identifier[remove_blank_text] = keyword[True] )
identifier[document] = i... | def xmllint_format(xml):
"""
Pretty-print XML like ``xmllint`` does.
Arguments:
xml (string): Serialized XML
"""
parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True)
document = ET.fromstring(xml, parser)
return ('%s\n%s' % ('<?xml version="1.0" en... |
def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs):
"""Query on node properties. See documentation for _OTIWrapper class."""
assert self.use_v1
return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix),
query_d... | def function[find_nodes, parameter[self, query_dict, exact, verbose]]:
constant[Query on node properties. See documentation for _OTIWrapper class.]
assert[name[self].use_v1]
return[call[name[self]._do_query, parameter[call[constant[{p}/singlePropertySearchForTreeNodes].format, parameter[]]]]] | keyword[def] identifier[find_nodes] ( identifier[self] , identifier[query_dict] = keyword[None] , identifier[exact] = keyword[False] , identifier[verbose] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[assert] identifier[self] . identifier[use_v1]
keyword[return] ide... | def find_nodes(self, query_dict=None, exact=False, verbose=False, **kwargs):
"""Query on node properties. See documentation for _OTIWrapper class."""
assert self.use_v1
return self._do_query('{p}/singlePropertySearchForTreeNodes'.format(p=self.query_prefix), query_dict=query_dict, exact=exact, verbose=verbo... |
def _get_individual_image(self, run, tag, index, sample):
"""
Returns the actual image bytes for a given image.
Args:
run: The name of the run the image belongs to.
tag: The name of the tag the images belongs to.
index: The index of the image in the current reservoir.
sample: The ze... | def function[_get_individual_image, parameter[self, run, tag, index, sample]]:
constant[
Returns the actual image bytes for a given image.
Args:
run: The name of the run the image belongs to.
tag: The name of the tag the images belongs to.
index: The index of the image in the current ... | keyword[def] identifier[_get_individual_image] ( identifier[self] , identifier[run] , identifier[tag] , identifier[index] , identifier[sample] ):
literal[string]
keyword[if] identifier[self] . identifier[_db_connection_provider] :
identifier[db] = identifier[self] . identifier[_db_connection_provid... | def _get_individual_image(self, run, tag, index, sample):
"""
Returns the actual image bytes for a given image.
Args:
run: The name of the run the image belongs to.
tag: The name of the tag the images belongs to.
index: The index of the image in the current reservoir.
sample: The ze... |
def make_fakelc(lcfile,
outdir,
magrms=None,
randomizemags=True,
randomizecoords=False,
lcformat='hat-sql',
lcformatdir=None,
timecols=None,
magcols=None,
errcols=None):
''... | def function[make_fakelc, parameter[lcfile, outdir, magrms, randomizemags, randomizecoords, lcformat, lcformatdir, timecols, magcols, errcols]]:
constant[This preprocesses an input real LC and sets it up to be a fake LC.
Parameters
----------
lcfile : str
This is an input light curve file ... | keyword[def] identifier[make_fakelc] ( identifier[lcfile] ,
identifier[outdir] ,
identifier[magrms] = keyword[None] ,
identifier[randomizemags] = keyword[True] ,
identifier[randomizecoords] = keyword[False] ,
identifier[lcformat] = literal[string] ,
identifier[lcformatdir] = keyword[None] ,
identifier[timecols... | def make_fakelc(lcfile, outdir, magrms=None, randomizemags=True, randomizecoords=False, lcformat='hat-sql', lcformatdir=None, timecols=None, magcols=None, errcols=None):
"""This preprocesses an input real LC and sets it up to be a fake LC.
Parameters
----------
lcfile : str
This is an input li... |
def update(self, alert_condition_infra_id, policy_id,
name, condition_type, alert_condition_configuration, enabled=True):
"""
This API endpoint allows you to update an alert condition for infrastucture
:type alert_condition_infra_id: int
:param alert_condition_infra_id: A... | def function[update, parameter[self, alert_condition_infra_id, policy_id, name, condition_type, alert_condition_configuration, enabled]]:
constant[
This API endpoint allows you to update an alert condition for infrastucture
:type alert_condition_infra_id: int
:param alert_condition_infr... | keyword[def] identifier[update] ( identifier[self] , identifier[alert_condition_infra_id] , identifier[policy_id] ,
identifier[name] , identifier[condition_type] , identifier[alert_condition_configuration] , identifier[enabled] = keyword[True] ):
literal[string]
identifier[data] ={
liter... | def update(self, alert_condition_infra_id, policy_id, name, condition_type, alert_condition_configuration, enabled=True):
"""
This API endpoint allows you to update an alert condition for infrastucture
:type alert_condition_infra_id: int
:param alert_condition_infra_id: Alert Condition Infr... |
def _update_docinfo(self):
"""Update the PDF's DocumentInfo dictionary to match XMP metadata
The standard mapping is described here:
https://www.pdfa.org/pdfa-metadata-xmp-rdf-dublin-core/
"""
self._pdf.docinfo # Touch object to ensure it exists
for uri, element, do... | def function[_update_docinfo, parameter[self]]:
constant[Update the PDF's DocumentInfo dictionary to match XMP metadata
The standard mapping is described here:
https://www.pdfa.org/pdfa-metadata-xmp-rdf-dublin-core/
]
name[self]._pdf.docinfo
for taget[tuple[[<ast.Nam... | keyword[def] identifier[_update_docinfo] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_pdf] . identifier[docinfo]
keyword[for] identifier[uri] , identifier[element] , identifier[docinfo_name] , identifier[converter] keyword[in] identifier[self] . identifier[DOCIN... | def _update_docinfo(self):
"""Update the PDF's DocumentInfo dictionary to match XMP metadata
The standard mapping is described here:
https://www.pdfa.org/pdfa-metadata-xmp-rdf-dublin-core/
"""
self._pdf.docinfo # Touch object to ensure it exists
for (uri, element, docinfo_name,... |
def time(self):
"Return the time part, with tzinfo None."
return time(self.hour, self.minute, self.second, self.microsecond) | def function[time, parameter[self]]:
constant[Return the time part, with tzinfo None.]
return[call[name[time], parameter[name[self].hour, name[self].minute, name[self].second, name[self].microsecond]]] | keyword[def] identifier[time] ( identifier[self] ):
literal[string]
keyword[return] identifier[time] ( identifier[self] . identifier[hour] , identifier[self] . identifier[minute] , identifier[self] . identifier[second] , identifier[self] . identifier[microsecond] ) | def time(self):
"""Return the time part, with tzinfo None."""
return time(self.hour, self.minute, self.second, self.microsecond) |
def create_oqhazardlib_source(self, tom, mesh_spacing, area_discretisation,
use_defaults=False):
"""
Converts the source model into an instance of the :class:
openquake.hazardlib.source.area.AreaSource
:param tom:
Temporal Occurrence model a... | def function[create_oqhazardlib_source, parameter[self, tom, mesh_spacing, area_discretisation, use_defaults]]:
constant[
Converts the source model into an instance of the :class:
openquake.hazardlib.source.area.AreaSource
:param tom:
Temporal Occurrence model as instance of... | keyword[def] identifier[create_oqhazardlib_source] ( identifier[self] , identifier[tom] , identifier[mesh_spacing] , identifier[area_discretisation] ,
identifier[use_defaults] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[mfd] :
keyword[r... | def create_oqhazardlib_source(self, tom, mesh_spacing, area_discretisation, use_defaults=False):
"""
Converts the source model into an instance of the :class:
openquake.hazardlib.source.area.AreaSource
:param tom:
Temporal Occurrence model as instance of :class:
open... |
def render_entries(cls, entries, additional_columns=None,
only_show=None, numbers=False):
"""
Pretty-prints a list of entries. If the window is wide enough to
support printing as a table, runs the `print_table.render_table`
function on the table. Otherwise, constru... | def function[render_entries, parameter[cls, entries, additional_columns, only_show, numbers]]:
constant[
Pretty-prints a list of entries. If the window is wide enough to
support printing as a table, runs the `print_table.render_table`
function on the table. Otherwise, constructs a line-b... | keyword[def] identifier[render_entries] ( identifier[cls] , identifier[entries] , identifier[additional_columns] = keyword[None] ,
identifier[only_show] = keyword[None] , identifier[numbers] = keyword[False] ):
literal[string]
identifier[additional_columns] = identifier[additional_columns] keywor... | def render_entries(cls, entries, additional_columns=None, only_show=None, numbers=False):
"""
Pretty-prints a list of entries. If the window is wide enough to
support printing as a table, runs the `print_table.render_table`
function on the table. Otherwise, constructs a line-by-line
... |
def _create_ids(self, home_teams, away_teams):
"""
Creates IDs for both players/teams
"""
categories = pd.Categorical(np.append(home_teams,away_teams))
home_id, away_id = categories.codes[0:int(len(categories)/2)], categories.codes[int(len(categories)/2):len(categories)+1]
... | def function[_create_ids, parameter[self, home_teams, away_teams]]:
constant[
Creates IDs for both players/teams
]
variable[categories] assign[=] call[name[pd].Categorical, parameter[call[name[np].append, parameter[name[home_teams], name[away_teams]]]]]
<ast.Tuple object at 0x7da... | keyword[def] identifier[_create_ids] ( identifier[self] , identifier[home_teams] , identifier[away_teams] ):
literal[string]
identifier[categories] = identifier[pd] . identifier[Categorical] ( identifier[np] . identifier[append] ( identifier[home_teams] , identifier[away_teams] ))
identifi... | def _create_ids(self, home_teams, away_teams):
"""
Creates IDs for both players/teams
"""
categories = pd.Categorical(np.append(home_teams, away_teams))
(home_id, away_id) = (categories.codes[0:int(len(categories) / 2)], categories.codes[int(len(categories) / 2):len(categories) + 1])
ret... |
def load_message_classes():
"""Load the 'fedora.messages' entry points and register the message classes."""
for message in pkg_resources.iter_entry_points("fedora.messages"):
cls = message.load()
_log.info(
"Registering the '%s' key as the '%r' class in the Message "
"cla... | def function[load_message_classes, parameter[]]:
constant[Load the 'fedora.messages' entry points and register the message classes.]
for taget[name[message]] in starred[call[name[pkg_resources].iter_entry_points, parameter[constant[fedora.messages]]]] begin[:]
variable[cls] assign[=] cal... | keyword[def] identifier[load_message_classes] ():
literal[string]
keyword[for] identifier[message] keyword[in] identifier[pkg_resources] . identifier[iter_entry_points] ( literal[string] ):
identifier[cls] = identifier[message] . identifier[load] ()
identifier[_log] . identifier[info] ... | def load_message_classes():
"""Load the 'fedora.messages' entry points and register the message classes."""
for message in pkg_resources.iter_entry_points('fedora.messages'):
cls = message.load()
_log.info("Registering the '%s' key as the '%r' class in the Message class registry", message.name, ... |
def to_dict(self, short_pred=True, properties=True):
"""
Encode the Dmrs as a dictionary suitable for JSON serialization.
"""
qs = set(self.nodeids(quantifier=True))
def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
def _node(node, short_pred=True):
p =... | def function[to_dict, parameter[self, short_pred, properties]]:
constant[
Encode the Dmrs as a dictionary suitable for JSON serialization.
]
variable[qs] assign[=] call[name[set], parameter[call[name[self].nodeids, parameter[]]]]
def function[_lnk, parameter[obj]]:
return... | keyword[def] identifier[to_dict] ( identifier[self] , identifier[short_pred] = keyword[True] , identifier[properties] = keyword[True] ):
literal[string]
identifier[qs] = identifier[set] ( identifier[self] . identifier[nodeids] ( identifier[quantifier] = keyword[True] ))
keyword[def] ident... | def to_dict(self, short_pred=True, properties=True):
"""
Encode the Dmrs as a dictionary suitable for JSON serialization.
"""
qs = set(self.nodeids(quantifier=True))
def _lnk(obj):
return {'from': obj.cfrom, 'to': obj.cto}
def _node(node, short_pred=True):
p = node.pred... |
def createAARText(self):
'''Creates the text for airspeed, altitude and climb rate.'''
self.airspeedText = self.axes.text(self.rightPos-(self.vertSize/10.0),-0.97+(2*self.vertSize)-(self.vertSize/10.0),'AS: %.1f m/s' % self.airspeed,color='w',size=self.fontSize,ha='right')
self.altitudeText = ... | def function[createAARText, parameter[self]]:
constant[Creates the text for airspeed, altitude and climb rate.]
name[self].airspeedText assign[=] call[name[self].axes.text, parameter[binary_operation[name[self].rightPos - binary_operation[name[self].vertSize / constant[10.0]]], binary_operation[binary_o... | keyword[def] identifier[createAARText] ( identifier[self] ):
literal[string]
identifier[self] . identifier[airspeedText] = identifier[self] . identifier[axes] . identifier[text] ( identifier[self] . identifier[rightPos] -( identifier[self] . identifier[vertSize] / literal[int] ),- literal[int] +( l... | def createAARText(self):
"""Creates the text for airspeed, altitude and climb rate."""
self.airspeedText = self.axes.text(self.rightPos - self.vertSize / 10.0, -0.97 + 2 * self.vertSize - self.vertSize / 10.0, 'AS: %.1f m/s' % self.airspeed, color='w', size=self.fontSize, ha='right')
self.altitudeText = s... |
def getConfigDirectory():
"""
Determines the platform-specific config directory location for ue4cli
"""
if platform.system() == 'Windows':
return os.path.join(os.environ['APPDATA'], 'ue4cli')
else:
return os.path.join(os.environ['HOME'], '.config', 'ue4cli') | def function[getConfigDirectory, parameter[]]:
constant[
Determines the platform-specific config directory location for ue4cli
]
if compare[call[name[platform].system, parameter[]] equal[==] constant[Windows]] begin[:]
return[call[name[os].path.join, parameter[call[name[os].environ][constant... | keyword[def] identifier[getConfigDirectory] ():
literal[string]
keyword[if] identifier[platform] . identifier[system] ()== literal[string] :
keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[environ] [ literal[string] ], literal[string] )
keyword[else] ... | def getConfigDirectory():
"""
Determines the platform-specific config directory location for ue4cli
"""
if platform.system() == 'Windows':
return os.path.join(os.environ['APPDATA'], 'ue4cli') # depends on [control=['if'], data=[]]
else:
return os.path.join(os.environ['HOME'], '.config',... |
def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text(
"""
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN ('unknown', 'unavailable')
... | def function[fetch_all_data, parameter[self, limit]]:
constant[
Fetch data for all entities.
]
variable[query] assign[=] call[name[text], parameter[constant[
SELECT domain, entity_id, state, last_changed
FROM states
WHERE
state NOT IN (... | keyword[def] identifier[fetch_all_data] ( identifier[self] , identifier[limit] = literal[int] ):
literal[string]
identifier[query] = identifier[text] (
literal[string]
)
keyword[try] :
identifier[print] ( literal[string] )
identifier[re... | def fetch_all_data(self, limit=50000):
"""
Fetch data for all entities.
"""
# Query text
query = text("\n SELECT domain, entity_id, state, last_changed\n FROM states\n WHERE\n state NOT IN ('unknown', 'unavailable')\n ORDER BY last_c... |
def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs):
''' Write rows data to a CSV file (with or without fieldnames) '''
if not quoting:
quoting = csv.QUOTE_MINIMAL
if 'lineterminator' not in kwargs:
kw... | def function[write_csv, parameter[path, rows, dialect, fieldnames, quoting, extrasaction]]:
constant[ Write rows data to a CSV file (with or without fieldnames) ]
if <ast.UnaryOp object at 0x7da1b10616c0> begin[:]
variable[quoting] assign[=] name[csv].QUOTE_MINIMAL
if compare[con... | keyword[def] identifier[write_csv] ( identifier[path] , identifier[rows] , identifier[dialect] = literal[string] , identifier[fieldnames] = keyword[None] , identifier[quoting] = identifier[csv] . identifier[QUOTE_ALL] , identifier[extrasaction] = literal[string] ,* identifier[args] ,** identifier[kwargs] ):
... | def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs):
""" Write rows data to a CSV file (with or without fieldnames) """
if not quoting:
quoting = csv.QUOTE_MINIMAL # depends on [control=['if'], data=[]]
if 'lineterminator' not i... |
def filter(self, table, idps, filter_string):
"""Naive case-insensitive search."""
q = filter_string.lower()
return [idp for idp in idps
if q in idp.ud.lower()] | def function[filter, parameter[self, table, idps, filter_string]]:
constant[Naive case-insensitive search.]
variable[q] assign[=] call[name[filter_string].lower, parameter[]]
return[<ast.ListComp object at 0x7da1b1985900>] | keyword[def] identifier[filter] ( identifier[self] , identifier[table] , identifier[idps] , identifier[filter_string] ):
literal[string]
identifier[q] = identifier[filter_string] . identifier[lower] ()
keyword[return] [ identifier[idp] keyword[for] identifier[idp] keyword[in] identifie... | def filter(self, table, idps, filter_string):
"""Naive case-insensitive search."""
q = filter_string.lower()
return [idp for idp in idps if q in idp.ud.lower()] |
def worker(self):
"""
Calculates the quartet weights for the test at a random
subsampled chunk of loci.
"""
## subsample loci
fullseqs = self.sample_loci()
## find all iterations of samples for this quartet
liters = itertools.product(*self.imap.values())
## run tree inference fo... | def function[worker, parameter[self]]:
constant[
Calculates the quartet weights for the test at a random
subsampled chunk of loci.
]
variable[fullseqs] assign[=] call[name[self].sample_loci, parameter[]]
variable[liters] assign[=] call[name[itertools].product, parameter[<ast.Starred... | keyword[def] identifier[worker] ( identifier[self] ):
literal[string]
identifier[fullseqs] = identifier[self] . identifier[sample_loci] ()
identifier[liters] = identifier[itertools] . identifier[product] (* identifier[self] . identifier[imap] . identifier[values] ())
identifier[... | def worker(self):
"""
Calculates the quartet weights for the test at a random
subsampled chunk of loci.
""" ## subsample loci
fullseqs = self.sample_loci()
## find all iterations of samples for this quartet
liters = itertools.product(*self.imap.values())
## run tree inference for each... |
def utc(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Build a `Time` from a UTC calendar date.
You can either specify the date as separate components, or
provide a time zone aware Python datetime. The following two
calls are equivalent (the ``utc`` time zone object can ... | def function[utc, parameter[self, year, month, day, hour, minute, second]]:
constant[Build a `Time` from a UTC calendar date.
You can either specify the date as separate components, or
provide a time zone aware Python datetime. The following two
calls are equivalent (the ``utc`` time z... | keyword[def] identifier[utc] ( identifier[self] , identifier[year] , identifier[month] = literal[int] , identifier[day] = literal[int] , identifier[hour] = literal[int] , identifier[minute] = literal[int] , identifier[second] = literal[int] ):
literal[string]
keyword[if] identifier[isinstance] ( i... | def utc(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Build a `Time` from a UTC calendar date.
You can either specify the date as separate components, or
provide a time zone aware Python datetime. The following two
calls are equivalent (the ``utc`` time zone object can be
... |
def clean_filters(filters: Mapping = None) -> str:
"""
Checks the values inside `filters`
https://docs.docker.com/engine/api/v1.29/#operation/ServiceList
Returns a new dictionary in the format `map[string][]string` jsonized
"""
if filters and isinstance(filters, dict):
for k, v in filte... | def function[clean_filters, parameter[filters]]:
constant[
Checks the values inside `filters`
https://docs.docker.com/engine/api/v1.29/#operation/ServiceList
Returns a new dictionary in the format `map[string][]string` jsonized
]
if <ast.BoolOp object at 0x7da1b08d54e0> begin[:]
... | keyword[def] identifier[clean_filters] ( identifier[filters] : identifier[Mapping] = keyword[None] )-> identifier[str] :
literal[string]
keyword[if] identifier[filters] keyword[and] identifier[isinstance] ( identifier[filters] , identifier[dict] ):
keyword[for] identifier[k] , identifier[v] ... | def clean_filters(filters: Mapping=None) -> str:
"""
Checks the values inside `filters`
https://docs.docker.com/engine/api/v1.29/#operation/ServiceList
Returns a new dictionary in the format `map[string][]string` jsonized
"""
if filters and isinstance(filters, dict):
for (k, v) in filter... |
def statement(self):
"""
statement : assign_statement
| expression
| control
| empty
Feature For Loop adds:
| loop
Feature Func adds:
| func
| return statement
... | def function[statement, parameter[self]]:
constant[
statement : assign_statement
| expression
| control
| empty
Feature For Loop adds:
| loop
Feature Func adds:
| func
... | keyword[def] identifier[statement] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[cur_token] . identifier[type] == identifier[TokenTypes] . identifier[VAR] :
identifier[self] . identifier[tokenizer] . identifier[start_saving] ( identifier[self] . ident... | def statement(self):
"""
statement : assign_statement
| expression
| control
| empty
Feature For Loop adds:
| loop
Feature Func adds:
| func
| return statement
""... |
def WriteFileFooter(self):
"""Writes the file footer (finished the file)."""
if not self._stream:
raise ArchiveAlreadyClosedError(
"Attempting to write to a ZIP archive that was already closed.")
if self.cur_cmpr:
buf = self.cur_cmpr.flush()
self.cur_compress_size += len(buf)
... | def function[WriteFileFooter, parameter[self]]:
constant[Writes the file footer (finished the file).]
if <ast.UnaryOp object at 0x7da1b1c0f610> begin[:]
<ast.Raise object at 0x7da1b1c0f550>
if name[self].cur_cmpr begin[:]
variable[buf] assign[=] call[name[self].cur_cmpr.f... | keyword[def] identifier[WriteFileFooter] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_stream] :
keyword[raise] identifier[ArchiveAlreadyClosedError] (
literal[string] )
keyword[if] identifier[self] . identifier[cur_cmpr] :
ide... | def WriteFileFooter(self):
"""Writes the file footer (finished the file)."""
if not self._stream:
raise ArchiveAlreadyClosedError('Attempting to write to a ZIP archive that was already closed.') # depends on [control=['if'], data=[]]
if self.cur_cmpr:
buf = self.cur_cmpr.flush()
sel... |
def str(self, space=False):
"""String version. Set space=True to line them all up nicely."""
return "%s/%s (%s)" % (str(int(self.id)).rjust(space and 4),
self.name.ljust(space and 50),
"; ".join(str(a) for a in self.args)) | def function[str, parameter[self, space]]:
constant[String version. Set space=True to line them all up nicely.]
return[binary_operation[constant[%s/%s (%s)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da18f00e500>, <ast.Call object at 0x7da18f00d6c0>, <ast.Call object at 0x7da18f00e290>... | keyword[def] identifier[str] ( identifier[self] , identifier[space] = keyword[False] ):
literal[string]
keyword[return] literal[string] %( identifier[str] ( identifier[int] ( identifier[self] . identifier[id] )). identifier[rjust] ( identifier[space] keyword[and] literal[int] ),
identifier[self] . ... | def str(self, space=False):
"""String version. Set space=True to line them all up nicely."""
return '%s/%s (%s)' % (str(int(self.id)).rjust(space and 4), self.name.ljust(space and 50), '; '.join((str(a) for a in self.args))) |
def get_recurring_bill_by_subscription(self, subscription_id):
"""
Consulta de las facturas que están pagadas o pendientes por pagar. Se puede consultar por cliente,
por suscripción o por rango de fechas.
Args:
subscription_id:
Returns:
"""
params =... | def function[get_recurring_bill_by_subscription, parameter[self, subscription_id]]:
constant[
Consulta de las facturas que están pagadas o pendientes por pagar. Se puede consultar por cliente,
por suscripción o por rango de fechas.
Args:
subscription_id:
Returns:
... | keyword[def] identifier[get_recurring_bill_by_subscription] ( identifier[self] , identifier[subscription_id] ):
literal[string]
identifier[params] ={
literal[string] : identifier[subscription_id] ,
}
keyword[return] identifier[self] . identifier[client] . identifier[_get]... | def get_recurring_bill_by_subscription(self, subscription_id):
"""
Consulta de las facturas que están pagadas o pendientes por pagar. Se puede consultar por cliente,
por suscripción o por rango de fechas.
Args:
subscription_id:
Returns:
"""
params = {'subsc... |
def get(self, sid):
"""
Constructs a EventContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext
"""
return EventContext(self._version, workspace_sid=self._solut... | def function[get, parameter[self, sid]]:
constant[
Constructs a EventContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext
]
return[call[name[EventContext], paramet... | keyword[def] identifier[get] ( identifier[self] , identifier[sid] ):
literal[string]
keyword[return] identifier[EventContext] ( identifier[self] . identifier[_version] , identifier[workspace_sid] = identifier[self] . identifier[_solution] [ literal[string] ], identifier[sid] = identifier[sid] ,) | def get(self, sid):
"""
Constructs a EventContext
:param sid: The sid
:returns: twilio.rest.taskrouter.v1.workspace.event.EventContext
:rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext
"""
return EventContext(self._version, workspace_sid=self._solution['wor... |
def create(self, **kwargs):
"""Create the resource on the BIG-IP®.
Uses HTTP POST to the `collection` URI to create a resource associated
with a new unique URI on the device.
..
If you do a create with inheritedTrafficGroup set to 'false' you
must also have a tr... | def function[create, parameter[self]]:
constant[Create the resource on the BIG-IP®.
Uses HTTP POST to the `collection` URI to create a resource associated
with a new unique URI on the device.
..
If you do a create with inheritedTrafficGroup set to 'false' you
mu... | keyword[def] identifier[create] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[itg] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[itg] keyword[and] identifier[itg] == literal[string] :
identifier[s... | def create(self, **kwargs):
"""Create the resource on the BIG-IP®.
Uses HTTP POST to the `collection` URI to create a resource associated
with a new unique URI on the device.
..
If you do a create with inheritedTrafficGroup set to 'false' you
must also have a traffi... |
async def loadCoreModule(self, ctor, conf=None):
'''
Load a single cortex module with the given ctor and conf.
Args:
ctor (str): The python module class path
conf (dict):Config dictionary for the module
'''
if conf is None:
conf = {}
... | <ast.AsyncFunctionDef object at 0x7da20c76e440> | keyword[async] keyword[def] identifier[loadCoreModule] ( identifier[self] , identifier[ctor] , identifier[conf] = keyword[None] ):
literal[string]
keyword[if] identifier[conf] keyword[is] keyword[None] :
identifier[conf] ={}
identifier[modu] = identifier[self] . identifie... | async def loadCoreModule(self, ctor, conf=None):
"""
Load a single cortex module with the given ctor and conf.
Args:
ctor (str): The python module class path
conf (dict):Config dictionary for the module
"""
if conf is None:
conf = {} # depends on [contro... |
def _update_top_pipeline(self):
"""Helper function to update the _optimized_pipeline field."""
# Store the pipeline with the highest internal testing score
if self._pareto_front:
self._optimized_pipeline_score = -float('inf')
for pipeline, pipeline_scores in zip(self._par... | def function[_update_top_pipeline, parameter[self]]:
constant[Helper function to update the _optimized_pipeline field.]
if name[self]._pareto_front begin[:]
name[self]._optimized_pipeline_score assign[=] <ast.UnaryOp object at 0x7da2041db760>
for taget[tuple[[<ast.Name ob... | keyword[def] identifier[_update_top_pipeline] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_pareto_front] :
identifier[self] . identifier[_optimized_pipeline_score] =- identifier[float] ( literal[string] )
keyword[for] identifi... | def _update_top_pipeline(self):
"""Helper function to update the _optimized_pipeline field."""
# Store the pipeline with the highest internal testing score
if self._pareto_front:
self._optimized_pipeline_score = -float('inf')
for (pipeline, pipeline_scores) in zip(self._pareto_front.items, r... |
def _set_uplink_switch(self, v, load=False):
"""
Setter method for uplink_switch, mapped from YANG variable /uplink_switch (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_uplink_switch is considered as a private
method. Backends looking to populate this v... | def function[_set_uplink_switch, parameter[self, v, load]]:
constant[
Setter method for uplink_switch, mapped from YANG variable /uplink_switch (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_uplink_switch is considered as a private
method. Backends l... | keyword[def] identifier[_set_uplink_switch] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_uplink_switch(self, v, load=False):
"""
Setter method for uplink_switch, mapped from YANG variable /uplink_switch (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_uplink_switch is considered as a private
method. Backends looking to populate this v... |
def get_image_data(self, ids=None, voxels=None, dense=True):
""" Slices and returns a subset of image data.
Args:
ids (list, array): A list or 1D numpy array of study ids to
return. If None, returns data for all studies.
voxels (list, array): A list or 1D numpy a... | def function[get_image_data, parameter[self, ids, voxels, dense]]:
constant[ Slices and returns a subset of image data.
Args:
ids (list, array): A list or 1D numpy array of study ids to
return. If None, returns data for all studies.
voxels (list, array): A list o... | keyword[def] identifier[get_image_data] ( identifier[self] , identifier[ids] = keyword[None] , identifier[voxels] = keyword[None] , identifier[dense] = keyword[True] ):
literal[string]
keyword[if] identifier[dense] keyword[and] identifier[ids] keyword[is] keyword[None] keyword[and] identifie... | def get_image_data(self, ids=None, voxels=None, dense=True):
""" Slices and returns a subset of image data.
Args:
ids (list, array): A list or 1D numpy array of study ids to
return. If None, returns data for all studies.
voxels (list, array): A list or 1D numpy array... |
def get_data_dirs(__pkg: str) -> List[str]:
"""Return all data directories for given package.
Args:
__pkg: Package name
"""
dirs = [user_data(__pkg), ]
dirs.extend(path.expanduser(path.sep.join([d, __pkg]))
for d in getenv('XDG_DATA_DIRS',
'/u... | def function[get_data_dirs, parameter[__pkg]]:
constant[Return all data directories for given package.
Args:
__pkg: Package name
]
variable[dirs] assign[=] list[[<ast.Call object at 0x7da18ede4820>]]
call[name[dirs].extend, parameter[<ast.GeneratorExp object at 0x7da18ede49d0>]]... | keyword[def] identifier[get_data_dirs] ( identifier[__pkg] : identifier[str] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[dirs] =[ identifier[user_data] ( identifier[__pkg] ),]
identifier[dirs] . identifier[extend] ( identifier[path] . identifier[expanduser] ( identifier[path] ... | def get_data_dirs(__pkg: str) -> List[str]:
"""Return all data directories for given package.
Args:
__pkg: Package name
"""
dirs = [user_data(__pkg)]
dirs.extend((path.expanduser(path.sep.join([d, __pkg])) for d in getenv('XDG_DATA_DIRS', '/usr/local/share/:/usr/share/').split(':')))
re... |
def check_in(request, action):
"""This function checks for missing properties in the request dict
for the corresponding action."""
if not request:
req_str = ""
for idx, val in enumerate(actions[action]):
req_str += "\n" + val
erstr = "Provide a request dict with the follo... | def function[check_in, parameter[request, action]]:
constant[This function checks for missing properties in the request dict
for the corresponding action.]
if <ast.UnaryOp object at 0x7da1b236d720> begin[:]
variable[req_str] assign[=] constant[]
for taget[tuple[[<ast.... | keyword[def] identifier[check_in] ( identifier[request] , identifier[action] ):
literal[string]
keyword[if] keyword[not] identifier[request] :
identifier[req_str] = literal[string]
keyword[for] identifier[idx] , identifier[val] keyword[in] identifier[enumerate] ( identifier[actions]... | def check_in(request, action):
"""This function checks for missing properties in the request dict
for the corresponding action."""
if not request:
req_str = ''
for (idx, val) in enumerate(actions[action]):
req_str += '\n' + val # depends on [control=['for'], data=[]]
ers... |
def add_field(cls, name, descriptor):
"""Add a field to store custom tags.
:param name: the name of the property the field is accessed
through. It must not already exist on this class.
:param descriptor: an instance of :class:`MediaField`.
"""
if not isinst... | def function[add_field, parameter[cls, name, descriptor]]:
constant[Add a field to store custom tags.
:param name: the name of the property the field is accessed
through. It must not already exist on this class.
:param descriptor: an instance of :class:`MediaField`.
... | keyword[def] identifier[add_field] ( identifier[cls] , identifier[name] , identifier[descriptor] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[descriptor] , identifier[MediaField] ):
keyword[raise] identifier[ValueError] (
literal[strin... | def add_field(cls, name, descriptor):
"""Add a field to store custom tags.
:param name: the name of the property the field is accessed
through. It must not already exist on this class.
:param descriptor: an instance of :class:`MediaField`.
"""
if not isinstance(des... |
def popone(self, key, default=_marker):
"""Remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise
KeyError is raised.
"""
identity = self._title(key)
for i in range(len(self._impl._items)):
if self._im... | def function[popone, parameter[self, key, default]]:
constant[Remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise
KeyError is raised.
]
variable[identity] assign[=] call[name[self]._title, parameter[name[key]]]
... | keyword[def] identifier[popone] ( identifier[self] , identifier[key] , identifier[default] = identifier[_marker] ):
literal[string]
identifier[identity] = identifier[self] . identifier[_title] ( identifier[key] )
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len]... | def popone(self, key, default=_marker):
"""Remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise
KeyError is raised.
"""
identity = self._title(key)
for i in range(len(self._impl._items)):
if self._impl._items[i][0] ... |
def data(self, table_name, metadata, persist_as=None, how='the_geom'):
"""Get an augmented CARTO dataset with `Data Observatory
<https://carto.com/data-observatory>`__ measures. Use
`CartoContext.data_discovery
<#context.CartoContext.data_discovery>`__ to search for available
mea... | def function[data, parameter[self, table_name, metadata, persist_as, how]]:
constant[Get an augmented CARTO dataset with `Data Observatory
<https://carto.com/data-observatory>`__ measures. Use
`CartoContext.data_discovery
<#context.CartoContext.data_discovery>`__ to search for available
... | keyword[def] identifier[data] ( identifier[self] , identifier[table_name] , identifier[metadata] , identifier[persist_as] = keyword[None] , identifier[how] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[metadata] , identifier[pd] . i... | def data(self, table_name, metadata, persist_as=None, how='the_geom'):
"""Get an augmented CARTO dataset with `Data Observatory
<https://carto.com/data-observatory>`__ measures. Use
`CartoContext.data_discovery
<#context.CartoContext.data_discovery>`__ to search for available
measure... |
def CountHuntFlows(self,
hunt_id,
filter_condition=db.HuntFlowsCondition.UNSET):
"""Counts hunt flows matching given conditions."""
return len(
self.ReadHuntFlows(
hunt_id, 0, sys.maxsize, filter_condition=filter_condition)) | def function[CountHuntFlows, parameter[self, hunt_id, filter_condition]]:
constant[Counts hunt flows matching given conditions.]
return[call[name[len], parameter[call[name[self].ReadHuntFlows, parameter[name[hunt_id], constant[0], name[sys].maxsize]]]]] | keyword[def] identifier[CountHuntFlows] ( identifier[self] ,
identifier[hunt_id] ,
identifier[filter_condition] = identifier[db] . identifier[HuntFlowsCondition] . identifier[UNSET] ):
literal[string]
keyword[return] identifier[len] (
identifier[self] . identifier[ReadHuntFlows] (
identifier[... | def CountHuntFlows(self, hunt_id, filter_condition=db.HuntFlowsCondition.UNSET):
"""Counts hunt flows matching given conditions."""
return len(self.ReadHuntFlows(hunt_id, 0, sys.maxsize, filter_condition=filter_condition)) |
def get(self):
"""Return a Deferred that fires with a SourceStamp instance."""
d = self.getBaseRevision()
d.addCallback(self.getPatch)
d.addCallback(self.done)
return d | def function[get, parameter[self]]:
constant[Return a Deferred that fires with a SourceStamp instance.]
variable[d] assign[=] call[name[self].getBaseRevision, parameter[]]
call[name[d].addCallback, parameter[name[self].getPatch]]
call[name[d].addCallback, parameter[name[self].done]]
... | keyword[def] identifier[get] ( identifier[self] ):
literal[string]
identifier[d] = identifier[self] . identifier[getBaseRevision] ()
identifier[d] . identifier[addCallback] ( identifier[self] . identifier[getPatch] )
identifier[d] . identifier[addCallback] ( identifier[self] . ide... | def get(self):
"""Return a Deferred that fires with a SourceStamp instance."""
d = self.getBaseRevision()
d.addCallback(self.getPatch)
d.addCallback(self.done)
return d |
def Region2_cp0(Tr, Pr):
"""Ideal properties for Region 2
Parameters
----------
Tr : float
Reduced temperature, [-]
Pr : float
Reduced pressure, [-]
Returns
-------
prop : array
Array with ideal Gibbs energy partial derivatives:
* g: Ideal Specific ... | def function[Region2_cp0, parameter[Tr, Pr]]:
constant[Ideal properties for Region 2
Parameters
----------
Tr : float
Reduced temperature, [-]
Pr : float
Reduced pressure, [-]
Returns
-------
prop : array
Array with ideal Gibbs energy partial derivatives:
... | keyword[def] identifier[Region2_cp0] ( identifier[Tr] , identifier[Pr] ):
literal[string]
identifier[Jo] =[ literal[int] , literal[int] ,- literal[int] ,- literal[int] ,- literal[int] ,- literal[int] ,- literal[int] , literal[int] , literal[int] ]
identifier[no] =[- literal[int] , literal[int] ,- lite... | def Region2_cp0(Tr, Pr):
"""Ideal properties for Region 2
Parameters
----------
Tr : float
Reduced temperature, [-]
Pr : float
Reduced pressure, [-]
Returns
-------
prop : array
Array with ideal Gibbs energy partial derivatives:
* g: Ideal Specific ... |
def add_resource(self, resource):
"""Add a resource to the list of interesting resources"""
if resource.exists():
self.resources[resource] = self.timekeeper.get_indicator(resource)
else:
self.resources[resource] = None | def function[add_resource, parameter[self, resource]]:
constant[Add a resource to the list of interesting resources]
if call[name[resource].exists, parameter[]] begin[:]
call[name[self].resources][name[resource]] assign[=] call[name[self].timekeeper.get_indicator, parameter[name[resource... | keyword[def] identifier[add_resource] ( identifier[self] , identifier[resource] ):
literal[string]
keyword[if] identifier[resource] . identifier[exists] ():
identifier[self] . identifier[resources] [ identifier[resource] ]= identifier[self] . identifier[timekeeper] . identifier[get_in... | def add_resource(self, resource):
"""Add a resource to the list of interesting resources"""
if resource.exists():
self.resources[resource] = self.timekeeper.get_indicator(resource) # depends on [control=['if'], data=[]]
else:
self.resources[resource] = None |
def add_member_to_group(self, group_id, member_id):
"""AddMemberToGroup.
[Preview API] Add a member to a Group.
:param str group_id: Id of the Group.
:param str member_id: Id of the member to add.
"""
route_values = {}
if group_id is not None:
route_va... | def function[add_member_to_group, parameter[self, group_id, member_id]]:
constant[AddMemberToGroup.
[Preview API] Add a member to a Group.
:param str group_id: Id of the Group.
:param str member_id: Id of the member to add.
]
variable[route_values] assign[=] dictionary[[]... | keyword[def] identifier[add_member_to_group] ( identifier[self] , identifier[group_id] , identifier[member_id] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[group_id] keyword[is] keyword[not] keyword[None] :
identifier[route_values] [ literal[strin... | def add_member_to_group(self, group_id, member_id):
"""AddMemberToGroup.
[Preview API] Add a member to a Group.
:param str group_id: Id of the Group.
:param str member_id: Id of the member to add.
"""
route_values = {}
if group_id is not None:
route_values['groupId'] ... |
def dump_dh_parameters(dh_parameters, encoding='pem'):
"""
Serializes an asn1crypto.algos.DHParameters object into a byte string
:param dh_parameters:
An asn1crypto.algos.DHParameters object
:param encoding:
A unicode string of "pem" or "der"
:return:
A byte string of the ... | def function[dump_dh_parameters, parameter[dh_parameters, encoding]]:
constant[
Serializes an asn1crypto.algos.DHParameters object into a byte string
:param dh_parameters:
An asn1crypto.algos.DHParameters object
:param encoding:
A unicode string of "pem" or "der"
:return:
... | keyword[def] identifier[dump_dh_parameters] ( identifier[dh_parameters] , identifier[encoding] = literal[string] ):
literal[string]
keyword[if] identifier[encoding] keyword[not] keyword[in] identifier[set] ([ literal[string] , literal[string] ]):
keyword[raise] identifier[ValueError] ( ident... | def dump_dh_parameters(dh_parameters, encoding='pem'):
"""
Serializes an asn1crypto.algos.DHParameters object into a byte string
:param dh_parameters:
An asn1crypto.algos.DHParameters object
:param encoding:
A unicode string of "pem" or "der"
:return:
A byte string of the ... |
def poke(self, context):
"""
Pokes for a mail attachment on the mail server.
:param context: The context that is being provided when poking.
:type context: dict
:return: True if attachment with the given name is present and False if not.
:rtype: bool
"""
... | def function[poke, parameter[self, context]]:
constant[
Pokes for a mail attachment on the mail server.
:param context: The context that is being provided when poking.
:type context: dict
:return: True if attachment with the given name is present and False if not.
:rtype... | keyword[def] identifier[poke] ( identifier[self] , identifier[context] ):
literal[string]
identifier[self] . identifier[log] . identifier[info] ( literal[string] , identifier[self] . identifier[attachment_name] )
keyword[with] identifier[ImapHook] ( identifier[imap_conn_id] = identifier[... | def poke(self, context):
"""
Pokes for a mail attachment on the mail server.
:param context: The context that is being provided when poking.
:type context: dict
:return: True if attachment with the given name is present and False if not.
:rtype: bool
"""
self.log... |
def _new_master_key(self, key_id):
"""Returns a KMSMasterKey for the specified key_id.
:param bytes key_id: KMS CMK ID
:returns: KMS Master Key based on key_id
:rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey
:raises InvalidKeyIdError: if key_id is not a valid KMS CMK I... | def function[_new_master_key, parameter[self, key_id]]:
constant[Returns a KMSMasterKey for the specified key_id.
:param bytes key_id: KMS CMK ID
:returns: KMS Master Key based on key_id
:rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey
:raises InvalidKeyIdError: if key_... | keyword[def] identifier[_new_master_key] ( identifier[self] , identifier[key_id] ):
literal[string]
identifier[_key_id] = identifier[to_str] ( identifier[key_id] )
keyword[return] identifier[KMSMasterKey] ( identifier[config] = identifier[KMSMasterKeyConfig] ( identifier[key_id] = identif... | def _new_master_key(self, key_id):
"""Returns a KMSMasterKey for the specified key_id.
:param bytes key_id: KMS CMK ID
:returns: KMS Master Key based on key_id
:rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey
:raises InvalidKeyIdError: if key_id is not a valid KMS CMK ID to... |
def parse_field(text, name=None, version=None, encoding_chars=None, validation_level=None,
reference=None, force_varies=False):
"""
Parse the given ER7-encoded field and return an instance of :class:`Field <hl7apy.core.Field>`.
:type text: ``str``
:param text: the ER7-encoded string con... | def function[parse_field, parameter[text, name, version, encoding_chars, validation_level, reference, force_varies]]:
constant[
Parse the given ER7-encoded field and return an instance of :class:`Field <hl7apy.core.Field>`.
:type text: ``str``
:param text: the ER7-encoded string containing the fiel... | keyword[def] identifier[parse_field] ( identifier[text] , identifier[name] = keyword[None] , identifier[version] = keyword[None] , identifier[encoding_chars] = keyword[None] , identifier[validation_level] = keyword[None] ,
identifier[reference] = keyword[None] , identifier[force_varies] = keyword[False] ):
lite... | def parse_field(text, name=None, version=None, encoding_chars=None, validation_level=None, reference=None, force_varies=False):
"""
Parse the given ER7-encoded field and return an instance of :class:`Field <hl7apy.core.Field>`.
:type text: ``str``
:param text: the ER7-encoded string containing the fiel... |
def dict2obj(d):
"""Convert a dict to an object or namespace
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> obj = dict2obj(d)
>>> obj.b.c
2
>>> obj.d
['hi', {'foo': 'bar'}]
>>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]}
>>> obj = dict2obj(d)
>>... | def function[dict2obj, parameter[d]]:
constant[Convert a dict to an object or namespace
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> obj = dict2obj(d)
>>> obj.b.c
2
>>> obj.d
['hi', {'foo': 'bar'}]
>>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]}
... | keyword[def] identifier[dict2obj] ( identifier[d] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[d] ,( identifier[Mapping] , identifier[list] , identifier[tuple] )):
keyword[try] :
identifier[d] = identifier[dict] ( identifier[d] )
keyword[except] ( ident... | def dict2obj(d):
"""Convert a dict to an object or namespace
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> obj = dict2obj(d)
>>> obj.b.c
2
>>> obj.d
['hi', {'foo': 'bar'}]
>>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]}
>>> obj = dict2obj(d)
>>... |
def _compute_all_features(self):
"""Computes all the features (beatsync, framesync) from the audio."""
# Read actual audio waveform
self._audio, _ = librosa.load(self.file_struct.audio_file,
sr=self.sr)
# Get duration of audio file
self.dur ... | def function[_compute_all_features, parameter[self]]:
constant[Computes all the features (beatsync, framesync) from the audio.]
<ast.Tuple object at 0x7da1b0552110> assign[=] call[name[librosa].load, parameter[name[self].file_struct.audio_file]]
name[self].dur assign[=] binary_operation[call[nam... | keyword[def] identifier[_compute_all_features] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_audio] , identifier[_] = identifier[librosa] . identifier[load] ( identifier[self] . identifier[file_struct] . identifier[audio_file] ,
identifier[sr] = identifier[s... | def _compute_all_features(self):
"""Computes all the features (beatsync, framesync) from the audio."""
# Read actual audio waveform
(self._audio, _) = librosa.load(self.file_struct.audio_file, sr=self.sr)
# Get duration of audio file
self.dur = len(self._audio) / float(self.sr)
# Compute actual ... |
def clone(self, label):
"""
Clones this volume to a new volume in the same region with the given label
:param label: The label for the new volume.
:returns: The new volume object.
"""
result = self._client.post('{}/clone'.format(Volume.api_endpoint),
mod... | def function[clone, parameter[self, label]]:
constant[
Clones this volume to a new volume in the same region with the given label
:param label: The label for the new volume.
:returns: The new volume object.
]
variable[result] assign[=] call[name[self]._client.post, para... | keyword[def] identifier[clone] ( identifier[self] , identifier[label] ):
literal[string]
identifier[result] = identifier[self] . identifier[_client] . identifier[post] ( literal[string] . identifier[format] ( identifier[Volume] . identifier[api_endpoint] ),
identifier[model] = identifier[s... | def clone(self, label):
"""
Clones this volume to a new volume in the same region with the given label
:param label: The label for the new volume.
:returns: The new volume object.
"""
result = self._client.post('{}/clone'.format(Volume.api_endpoint), model=self, data={'label': ... |
def write_mates(self):
'''Scan the current chromosome for matches to any of the reads stored
in the read1s buffer'''
if self.chrom is not None:
U.debug("Dumping %i mates for contig %s" % (
len(self.read1s), self.chrom))
for read in self.infile.fetch(reference... | def function[write_mates, parameter[self]]:
constant[Scan the current chromosome for matches to any of the reads stored
in the read1s buffer]
if compare[name[self].chrom is_not constant[None]] begin[:]
call[name[U].debug, parameter[binary_operation[constant[Dumping %i mates for c... | keyword[def] identifier[write_mates] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[chrom] keyword[is] keyword[not] keyword[None] :
identifier[U] . identifier[debug] ( literal[string] %(
identifier[len] ( identifier[self] . identifier[r... | def write_mates(self):
"""Scan the current chromosome for matches to any of the reads stored
in the read1s buffer"""
if self.chrom is not None:
U.debug('Dumping %i mates for contig %s' % (len(self.read1s), self.chrom)) # depends on [control=['if'], data=[]]
for read in self.infile.fetch(ref... |
def get_domain_realm(self, path_info, environ):
"""Resolve a relative url to the appropriate realm name."""
realm = self._calc_realm_from_path_provider(path_info, environ)
return realm | def function[get_domain_realm, parameter[self, path_info, environ]]:
constant[Resolve a relative url to the appropriate realm name.]
variable[realm] assign[=] call[name[self]._calc_realm_from_path_provider, parameter[name[path_info], name[environ]]]
return[name[realm]] | keyword[def] identifier[get_domain_realm] ( identifier[self] , identifier[path_info] , identifier[environ] ):
literal[string]
identifier[realm] = identifier[self] . identifier[_calc_realm_from_path_provider] ( identifier[path_info] , identifier[environ] )
keyword[return] identifier[realm]... | def get_domain_realm(self, path_info, environ):
"""Resolve a relative url to the appropriate realm name."""
realm = self._calc_realm_from_path_provider(path_info, environ)
return realm |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.