code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def transit_decrypt_data(self, name, ciphertext, context=None, nonce=None, batch_input=None, mount_point='transit'):
"""POST /<mount_point>/decrypt/<name>
:param name:
:type name:
:param ciphertext:
:type ciphertext:
:param context:
:type context:
:param ... | def function[transit_decrypt_data, parameter[self, name, ciphertext, context, nonce, batch_input, mount_point]]:
constant[POST /<mount_point>/decrypt/<name>
:param name:
:type name:
:param ciphertext:
:type ciphertext:
:param context:
:type context:
:para... | keyword[def] identifier[transit_decrypt_data] ( identifier[self] , identifier[name] , identifier[ciphertext] , identifier[context] = keyword[None] , identifier[nonce] = keyword[None] , identifier[batch_input] = keyword[None] , identifier[mount_point] = literal[string] ):
literal[string]
identifier[... | def transit_decrypt_data(self, name, ciphertext, context=None, nonce=None, batch_input=None, mount_point='transit'):
"""POST /<mount_point>/decrypt/<name>
:param name:
:type name:
:param ciphertext:
:type ciphertext:
:param context:
:type context:
:param nonc... |
def fit(
self,
df,
id_col,
event_col,
start_col="start",
stop_col="stop",
weights_col=None,
show_progress=False,
step_size=None,
robust=False,
strata=None,
initial_point=None,
): # pylint: disable=too-many-arguments
... | def function[fit, parameter[self, df, id_col, event_col, start_col, stop_col, weights_col, show_progress, step_size, robust, strata, initial_point]]:
constant[
Fit the Cox Proportional Hazard model to a time varying dataset. Tied survival times
are handled using Efron's tie-method.
Para... | keyword[def] identifier[fit] (
identifier[self] ,
identifier[df] ,
identifier[id_col] ,
identifier[event_col] ,
identifier[start_col] = literal[string] ,
identifier[stop_col] = literal[string] ,
identifier[weights_col] = keyword[None] ,
identifier[show_progress] = keyword[False] ,
identifier[step_size] = key... | def fit(self, df, id_col, event_col, start_col='start', stop_col='stop', weights_col=None, show_progress=False, step_size=None, robust=False, strata=None, initial_point=None): # pylint: disable=too-many-arguments
'\n Fit the Cox Proportional Hazard model to a time varying dataset. Tied survival times\n ... |
def handle(self):
"""
Executes the command.
"""
if not self.confirm_to_proceed(
"<question>Are you sure you want to rollback the last migration?:</question> "
):
return
database = self.option("database")
repository = DatabaseMigrationRepos... | def function[handle, parameter[self]]:
constant[
Executes the command.
]
if <ast.UnaryOp object at 0x7da18eb54ca0> begin[:]
return[None]
variable[database] assign[=] call[name[self].option, parameter[constant[database]]]
variable[repository] assign[=] call[name[Da... | keyword[def] identifier[handle] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[confirm_to_proceed] (
literal[string]
):
keyword[return]
identifier[database] = identifier[self] . identifier[option] ( literal[st... | def handle(self):
"""
Executes the command.
"""
if not self.confirm_to_proceed('<question>Are you sure you want to rollback the last migration?:</question> '):
return # depends on [control=['if'], data=[]]
database = self.option('database')
repository = DatabaseMigrationReposito... |
async def getHealth(self, *args, **kwargs):
"""
Get EC2 account health metrics
Give some basic stats on the health of our EC2 account
This method gives output: ``v1/health.json#``
This method is ``experimental``
"""
return await self._makeApiCall(self.funcinfo... | <ast.AsyncFunctionDef object at 0x7da1b0400700> | keyword[async] keyword[def] identifier[getHealth] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] keyword[await] identifier[self] . identifier[_makeApiCall] ( identifier[self] . identifier[funcinfo] [ literal[string] ],* identifier[args] ,** iden... | async def getHealth(self, *args, **kwargs):
"""
Get EC2 account health metrics
Give some basic stats on the health of our EC2 account
This method gives output: ``v1/health.json#``
This method is ``experimental``
"""
return await self._makeApiCall(self.funcinfo['getHeal... |
def close(self):
"""Close port."""
os.close(self.in_d)
os.close(self.out_d) | def function[close, parameter[self]]:
constant[Close port.]
call[name[os].close, parameter[name[self].in_d]]
call[name[os].close, parameter[name[self].out_d]] | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[os] . identifier[close] ( identifier[self] . identifier[in_d] )
identifier[os] . identifier[close] ( identifier[self] . identifier[out_d] ) | def close(self):
"""Close port."""
os.close(self.in_d)
os.close(self.out_d) |
def get_user(user_or_username=None):
"""Return Plone User
:param user_or_username: Plone user or user id
:type groupname: PloneUser/MemberData/str
:returns: Plone MemberData
:rtype: object
"""
if user_or_username is None:
return None
if hasattr(user_or_username, "getUserId"):
... | def function[get_user, parameter[user_or_username]]:
constant[Return Plone User
:param user_or_username: Plone user or user id
:type groupname: PloneUser/MemberData/str
:returns: Plone MemberData
:rtype: object
]
if compare[name[user_or_username] is constant[None]] begin[:]
... | keyword[def] identifier[get_user] ( identifier[user_or_username] = keyword[None] ):
literal[string]
keyword[if] identifier[user_or_username] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[if] identifier[hasattr] ( identifier[user_or_username] , literal[string] ):
... | def get_user(user_or_username=None):
"""Return Plone User
:param user_or_username: Plone user or user id
:type groupname: PloneUser/MemberData/str
:returns: Plone MemberData
:rtype: object
"""
if user_or_username is None:
return None # depends on [control=['if'], data=[]]
if h... |
def update(self, data, timeout=-1, force=False):
"""
Updates one or more attributes for a server hardware type resource.
Args:
data (dict): Object to update.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the o... | def function[update, parameter[self, data, timeout, force]]:
constant[
Updates one or more attributes for a server hardware type resource.
Args:
data (dict): Object to update.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout do... | keyword[def] identifier[update] ( identifier[self] , identifier[data] , identifier[timeout] =- literal[int] , identifier[force] = keyword[False] ):
literal[string]
identifier[uri] = identifier[self] . identifier[data] [ literal[string] ]
identifier[self] . identifier[data] = identifier[sel... | def update(self, data, timeout=-1, force=False):
"""
Updates one or more attributes for a server hardware type resource.
Args:
data (dict): Object to update.
timeout:
Timeout in seconds. Wait for task completion by default. The timeout does not abort the opera... |
def method_selector_fn(self):
"""Gets the method selector from the config.
"""
if callable(self.json_rpc_method):
return self.json_rpc_method
elif isinstance(self.json_rpc_method, (str,)):
return lambda *_: self.json_rpc_method
raise ValueError("``json_rpc... | def function[method_selector_fn, parameter[self]]:
constant[Gets the method selector from the config.
]
if call[name[callable], parameter[name[self].json_rpc_method]] begin[:]
return[name[self].json_rpc_method]
<ast.Raise object at 0x7da18c4ce170> | keyword[def] identifier[method_selector_fn] ( identifier[self] ):
literal[string]
keyword[if] identifier[callable] ( identifier[self] . identifier[json_rpc_method] ):
keyword[return] identifier[self] . identifier[json_rpc_method]
keyword[elif] identifier[isinstance] ( iden... | def method_selector_fn(self):
"""Gets the method selector from the config.
"""
if callable(self.json_rpc_method):
return self.json_rpc_method # depends on [control=['if'], data=[]]
elif isinstance(self.json_rpc_method, (str,)):
return lambda *_: self.json_rpc_method # depends on [c... |
def _secondary_loop(self, reconnect=False):
"""The worker loop for the secondary nodes."""
if self.num_workers > 1:
pool = multiprocessing.Pool(self.num_workers)
else:
pool = None
should_reconnect = True
while should_reconnect:
i = 0
... | def function[_secondary_loop, parameter[self, reconnect]]:
constant[The worker loop for the secondary nodes.]
if compare[name[self].num_workers greater[>] constant[1]] begin[:]
variable[pool] assign[=] call[name[multiprocessing].Pool, parameter[name[self].num_workers]]
variable[s... | keyword[def] identifier[_secondary_loop] ( identifier[self] , identifier[reconnect] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[num_workers] > literal[int] :
identifier[pool] = identifier[multiprocessing] . identifier[Pool] ( identifier[self] . identi... | def _secondary_loop(self, reconnect=False):
"""The worker loop for the secondary nodes."""
if self.num_workers > 1:
pool = multiprocessing.Pool(self.num_workers) # depends on [control=['if'], data=[]]
else:
pool = None
should_reconnect = True
while should_reconnect:
i = 0
... |
def schedule(self, callback, *args, **kwargs):
"""Schedule the callback to be called asynchronously in a thread pool.
Args:
callback (Callable): The function to call.
args: Positional arguments passed to the function.
kwargs: Key-word arguments passed to the function... | def function[schedule, parameter[self, callback]]:
constant[Schedule the callback to be called asynchronously in a thread pool.
Args:
callback (Callable): The function to call.
args: Positional arguments passed to the function.
kwargs: Key-word arguments passed to th... | keyword[def] identifier[schedule] ( identifier[self] , identifier[callback] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_executor] . identifier[submit] ( identifier[callback] ,* identifier[args] ,** identifier[kwargs] ) | def schedule(self, callback, *args, **kwargs):
"""Schedule the callback to be called asynchronously in a thread pool.
Args:
callback (Callable): The function to call.
args: Positional arguments passed to the function.
kwargs: Key-word arguments passed to the function.
... |
def CheckPermissions(self, username, subject):
"""Checks if a given user has access to a given subject."""
if subject in self.authorized_users:
return ((username in self.authorized_users[subject]) or
self.group_access_manager.MemberOfAuthorizedGroup(
username, subject))
... | def function[CheckPermissions, parameter[self, username, subject]]:
constant[Checks if a given user has access to a given subject.]
if compare[name[subject] in name[self].authorized_users] begin[:]
return[<ast.BoolOp object at 0x7da1b1c1b8b0>]
<ast.Raise object at 0x7da1b1c18430> | keyword[def] identifier[CheckPermissions] ( identifier[self] , identifier[username] , identifier[subject] ):
literal[string]
keyword[if] identifier[subject] keyword[in] identifier[self] . identifier[authorized_users] :
keyword[return] (( identifier[username] keyword[in] identifier[self] . iden... | def CheckPermissions(self, username, subject):
"""Checks if a given user has access to a given subject."""
if subject in self.authorized_users:
return username in self.authorized_users[subject] or self.group_access_manager.MemberOfAuthorizedGroup(username, subject) # depends on [control=['if'], data=['... |
def find_end(self, text, start_token, end_token, ignore_end_token=None):
'''find the of a token.
Returns the offset in the string immediately after the matching end_token'''
if not text.startswith(start_token):
raise MAVParseError("invalid token start")
offset = len(start_tok... | def function[find_end, parameter[self, text, start_token, end_token, ignore_end_token]]:
constant[find the of a token.
Returns the offset in the string immediately after the matching end_token]
if <ast.UnaryOp object at 0x7da18dc04850> begin[:]
<ast.Raise object at 0x7da18dc05ea0>
... | keyword[def] identifier[find_end] ( identifier[self] , identifier[text] , identifier[start_token] , identifier[end_token] , identifier[ignore_end_token] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[text] . identifier[startswith] ( identifier[start_token] ):
... | def find_end(self, text, start_token, end_token, ignore_end_token=None):
"""find the of a token.
Returns the offset in the string immediately after the matching end_token"""
if not text.startswith(start_token):
raise MAVParseError('invalid token start') # depends on [control=['if'], data=[]]
... |
def strip_size(self, location='top', num_lines=None):
"""
Breadth of the strip background in inches
Parameters
----------
location : str in ``['top', 'right']``
Location of the strip text
num_lines : int
Number of text lines
"""
dp... | def function[strip_size, parameter[self, location, num_lines]]:
constant[
Breadth of the strip background in inches
Parameters
----------
location : str in ``['top', 'right']``
Location of the strip text
num_lines : int
Number of text lines
... | keyword[def] identifier[strip_size] ( identifier[self] , identifier[location] = literal[string] , identifier[num_lines] = keyword[None] ):
literal[string]
identifier[dpi] = literal[int]
identifier[theme] = identifier[self] . identifier[theme]
identifier[get_property] = identifie... | def strip_size(self, location='top', num_lines=None):
"""
Breadth of the strip background in inches
Parameters
----------
location : str in ``['top', 'right']``
Location of the strip text
num_lines : int
Number of text lines
"""
dpi = 72
... |
def trace(self, predicate):
"""
Starts tracing with the given callable.
Args:
predicate (callable that accepts a single :obj:`hunter.Event` argument):
Return:
self
"""
self._handler = predicate
if self.threading_support is None or self.thr... | def function[trace, parameter[self, predicate]]:
constant[
Starts tracing with the given callable.
Args:
predicate (callable that accepts a single :obj:`hunter.Event` argument):
Return:
self
]
name[self]._handler assign[=] name[predicate]
... | keyword[def] identifier[trace] ( identifier[self] , identifier[predicate] ):
literal[string]
identifier[self] . identifier[_handler] = identifier[predicate]
keyword[if] identifier[self] . identifier[threading_support] keyword[is] keyword[None] keyword[or] identifier[self] . identifie... | def trace(self, predicate):
"""
Starts tracing with the given callable.
Args:
predicate (callable that accepts a single :obj:`hunter.Event` argument):
Return:
self
"""
self._handler = predicate
if self.threading_support is None or self.threading_suppo... |
def get_office(self, row, division):
"""
Gets the Office object for the given row of election results.
Depends on knowing the division of the row of election results.
"""
AT_LARGE_STATES = ["AK", "DE", "MT", "ND", "SD", "VT", "WY"]
if division.level.name not in [
... | def function[get_office, parameter[self, row, division]]:
constant[
Gets the Office object for the given row of election results.
Depends on knowing the division of the row of election results.
]
variable[AT_LARGE_STATES] assign[=] list[[<ast.Constant object at 0x7da2045648e0>, <... | keyword[def] identifier[get_office] ( identifier[self] , identifier[row] , identifier[division] ):
literal[string]
identifier[AT_LARGE_STATES] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]
keyword[if] iden... | def get_office(self, row, division):
"""
Gets the Office object for the given row of election results.
Depends on knowing the division of the row of election results.
"""
AT_LARGE_STATES = ['AK', 'DE', 'MT', 'ND', 'SD', 'VT', 'WY']
if division.level.name not in [geography.DivisionLev... |
def _scan_two_qubit_ops_into_matrix(
self,
circuit: circuits.Circuit,
index: Optional[int],
qubits: Tuple[ops.Qid, ...]
) -> Tuple[List[ops.Operation], List[int], np.ndarray]:
"""Accumulates operations affecting the given pair of qubits.
The scan term... | def function[_scan_two_qubit_ops_into_matrix, parameter[self, circuit, index, qubits]]:
constant[Accumulates operations affecting the given pair of qubits.
The scan terminates when it hits the end of the circuit, finds an
operation without a known matrix, or finds an operation that interacts
... | keyword[def] identifier[_scan_two_qubit_ops_into_matrix] (
identifier[self] ,
identifier[circuit] : identifier[circuits] . identifier[Circuit] ,
identifier[index] : identifier[Optional] [ identifier[int] ],
identifier[qubits] : identifier[Tuple] [ identifier[ops] . identifier[Qid] ,...]
)-> identifier[Tuple] [ id... | def _scan_two_qubit_ops_into_matrix(self, circuit: circuits.Circuit, index: Optional[int], qubits: Tuple[ops.Qid, ...]) -> Tuple[List[ops.Operation], List[int], np.ndarray]:
"""Accumulates operations affecting the given pair of qubits.
The scan terminates when it hits the end of the circuit, finds an
... |
def is_valid(self):
"""
Is the current entity valid.
Returns
-----------
valid : bool
Is the current entity well formed
"""
valid = np.any((self.points - self.points[0]) != 0)
return valid | def function[is_valid, parameter[self]]:
constant[
Is the current entity valid.
Returns
-----------
valid : bool
Is the current entity well formed
]
variable[valid] assign[=] call[name[np].any, parameter[compare[binary_operation[name[self].points - call... | keyword[def] identifier[is_valid] ( identifier[self] ):
literal[string]
identifier[valid] = identifier[np] . identifier[any] (( identifier[self] . identifier[points] - identifier[self] . identifier[points] [ literal[int] ])!= literal[int] )
keyword[return] identifier[valid] | def is_valid(self):
"""
Is the current entity valid.
Returns
-----------
valid : bool
Is the current entity well formed
"""
valid = np.any(self.points - self.points[0] != 0)
return valid |
def add_template_events_to_network(self, columns, vectors):
""" Add a vector indexed """
# Just call through to the standard function
self.template_events = self.template_event_dict['network']
self.add_template_network_events(columns, vectors)
self.template_event_dict['network'] ... | def function[add_template_events_to_network, parameter[self, columns, vectors]]:
constant[ Add a vector indexed ]
name[self].template_events assign[=] call[name[self].template_event_dict][constant[network]]
call[name[self].add_template_network_events, parameter[name[columns], name[vectors]]]
... | keyword[def] identifier[add_template_events_to_network] ( identifier[self] , identifier[columns] , identifier[vectors] ):
literal[string]
identifier[self] . identifier[template_events] = identifier[self] . identifier[template_event_dict] [ literal[string] ]
identifier[self] . iden... | def add_template_events_to_network(self, columns, vectors):
""" Add a vector indexed """
# Just call through to the standard function
self.template_events = self.template_event_dict['network']
self.add_template_network_events(columns, vectors)
self.template_event_dict['network'] = self.template_even... |
def insertComponent(self, comp, row=0, col=0):
"""Inserts component into model
:param comp: Component to insert into the stimulus
:type comp: :class:`AbstractStimulusComponent<sparkle.stim.abstract_component.AbstractStimulusComponent>`
:param row: Track number to place comp in
:... | def function[insertComponent, parameter[self, comp, row, col]]:
constant[Inserts component into model
:param comp: Component to insert into the stimulus
:type comp: :class:`AbstractStimulusComponent<sparkle.stim.abstract_component.AbstractStimulusComponent>`
:param row: Track number to ... | keyword[def] identifier[insertComponent] ( identifier[self] , identifier[comp] , identifier[row] = literal[int] , identifier[col] = literal[int] ):
literal[string]
keyword[if] identifier[row] > identifier[len] ( identifier[self] . identifier[_segments] )- literal[int] :
identifier[sel... | def insertComponent(self, comp, row=0, col=0):
"""Inserts component into model
:param comp: Component to insert into the stimulus
:type comp: :class:`AbstractStimulusComponent<sparkle.stim.abstract_component.AbstractStimulusComponent>`
:param row: Track number to place comp in
:type... |
def likelihood_weighted_sample(self, evidence=None, size=1, return_type="dataframe"):
"""
Generates weighted sample(s) from joint distribution of the bayesian
network, that comply with the given evidence.
'Probabilistic Graphical Model Principles and Techniques', Koller and
Fried... | def function[likelihood_weighted_sample, parameter[self, evidence, size, return_type]]:
constant[
Generates weighted sample(s) from joint distribution of the bayesian
network, that comply with the given evidence.
'Probabilistic Graphical Model Principles and Techniques', Koller and
... | keyword[def] identifier[likelihood_weighted_sample] ( identifier[self] , identifier[evidence] = keyword[None] , identifier[size] = literal[int] , identifier[return_type] = literal[string] ):
literal[string]
identifier[types] =[( identifier[var_name] , literal[string] ) keyword[for] identifier[var_... | def likelihood_weighted_sample(self, evidence=None, size=1, return_type='dataframe'):
"""
Generates weighted sample(s) from joint distribution of the bayesian
network, that comply with the given evidence.
'Probabilistic Graphical Model Principles and Techniques', Koller and
Friedman,... |
def _notify_deleted_file(self):
"""
Notify user from external file deletion.
"""
self.file_deleted.emit(self.editor)
# file deleted, disable file watcher
self.enabled = False | def function[_notify_deleted_file, parameter[self]]:
constant[
Notify user from external file deletion.
]
call[name[self].file_deleted.emit, parameter[name[self].editor]]
name[self].enabled assign[=] constant[False] | keyword[def] identifier[_notify_deleted_file] ( identifier[self] ):
literal[string]
identifier[self] . identifier[file_deleted] . identifier[emit] ( identifier[self] . identifier[editor] )
identifier[self] . identifier[enabled] = keyword[False] | def _notify_deleted_file(self):
"""
Notify user from external file deletion.
"""
self.file_deleted.emit(self.editor)
# file deleted, disable file watcher
self.enabled = False |
def sync_skills_data(self):
""" Update internal skill_data_structure from disk. """
self.skills_data = self.load_skills_data()
if 'upgraded' in self.skills_data:
self.skills_data.pop('upgraded')
else:
self.skills_data_hash = skills_data_hash(self.skills_data) | def function[sync_skills_data, parameter[self]]:
constant[ Update internal skill_data_structure from disk. ]
name[self].skills_data assign[=] call[name[self].load_skills_data, parameter[]]
if compare[constant[upgraded] in name[self].skills_data] begin[:]
call[name[self].skills_da... | keyword[def] identifier[sync_skills_data] ( identifier[self] ):
literal[string]
identifier[self] . identifier[skills_data] = identifier[self] . identifier[load_skills_data] ()
keyword[if] literal[string] keyword[in] identifier[self] . identifier[skills_data] :
identifier[se... | def sync_skills_data(self):
""" Update internal skill_data_structure from disk. """
self.skills_data = self.load_skills_data()
if 'upgraded' in self.skills_data:
self.skills_data.pop('upgraded') # depends on [control=['if'], data=[]]
else:
self.skills_data_hash = skills_data_hash(self.s... |
def makeDependencyMap(aMap):
"""
create a dependency data structure as follows:
- Each key in aMap represents an item that depends on each item in the iterable which is that key's value
- Each Node represents an item which is a precursor to its parents and depends on its children
Returns a map whose keys are ... | def function[makeDependencyMap, parameter[aMap]]:
constant[
create a dependency data structure as follows:
- Each key in aMap represents an item that depends on each item in the iterable which is that key's value
- Each Node represents an item which is a precursor to its parents and depends on its childre... | keyword[def] identifier[makeDependencyMap] ( identifier[aMap] ):
literal[string]
identifier[index] ={}
keyword[for] identifier[i] keyword[in] identifier[aMap] . identifier[keys] ():
identifier[iNode] = identifier[index] . identifier[get] ( identifier[i] , keyword[None] )
keyword[if] keyword[no... | def makeDependencyMap(aMap):
"""
create a dependency data structure as follows:
- Each key in aMap represents an item that depends on each item in the iterable which is that key's value
- Each Node represents an item which is a precursor to its parents and depends on its children
Returns a map whose keys ar... |
def get_house_detail(self, html):
"""Get bedroom, bathroom, sqft and more information.
Example: http://www.zillow.com/homedetails/8510-Whittier-Blvd-Bethesda-MD-20817/37183103_zpid/
"""
if "I'm not a robot" in html:
raise exc.CaptchaError(url)
data = {"errors": dict... | def function[get_house_detail, parameter[self, html]]:
constant[Get bedroom, bathroom, sqft and more information.
Example: http://www.zillow.com/homedetails/8510-Whittier-Blvd-Bethesda-MD-20817/37183103_zpid/
]
if compare[constant[I'm not a robot] in name[html]] begin[:]
<ast.Ra... | keyword[def] identifier[get_house_detail] ( identifier[self] , identifier[html] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[html] :
keyword[raise] identifier[exc] . identifier[CaptchaError] ( identifier[url] )
identifier[data] ={ literal[string] ... | def get_house_detail(self, html):
"""Get bedroom, bathroom, sqft and more information.
Example: http://www.zillow.com/homedetails/8510-Whittier-Blvd-Bethesda-MD-20817/37183103_zpid/
"""
if "I'm not a robot" in html:
raise exc.CaptchaError(url) # depends on [control=['if'], data=[]]
... |
def rnoncentral_t(mu, lam, nu, size=None):
"""
Non-central Student's t random variates.
"""
tau = rgamma(nu / 2., nu / (2. * lam), size)
return rnormal(mu, tau) | def function[rnoncentral_t, parameter[mu, lam, nu, size]]:
constant[
Non-central Student's t random variates.
]
variable[tau] assign[=] call[name[rgamma], parameter[binary_operation[name[nu] / constant[2.0]], binary_operation[name[nu] / binary_operation[constant[2.0] * name[lam]]], name[size]]]
... | keyword[def] identifier[rnoncentral_t] ( identifier[mu] , identifier[lam] , identifier[nu] , identifier[size] = keyword[None] ):
literal[string]
identifier[tau] = identifier[rgamma] ( identifier[nu] / literal[int] , identifier[nu] /( literal[int] * identifier[lam] ), identifier[size] )
keyword[return]... | def rnoncentral_t(mu, lam, nu, size=None):
"""
Non-central Student's t random variates.
"""
tau = rgamma(nu / 2.0, nu / (2.0 * lam), size)
return rnormal(mu, tau) |
def density(self, r, rho0, Ra, Rs):
"""
computes the density
:param x:
:param y:
:param rho0:
:param Ra:
:param Rs:
:return:
"""
Ra, Rs = self._sort_ra_rs(Ra, Rs)
rho = rho0 / ((1 + (r / Ra) ** 2) * (1 + (r / Rs) ** 2))
retu... | def function[density, parameter[self, r, rho0, Ra, Rs]]:
constant[
computes the density
:param x:
:param y:
:param rho0:
:param Ra:
:param Rs:
:return:
]
<ast.Tuple object at 0x7da18dc9b3a0> assign[=] call[name[self]._sort_ra_rs, parameter[... | keyword[def] identifier[density] ( identifier[self] , identifier[r] , identifier[rho0] , identifier[Ra] , identifier[Rs] ):
literal[string]
identifier[Ra] , identifier[Rs] = identifier[self] . identifier[_sort_ra_rs] ( identifier[Ra] , identifier[Rs] )
identifier[rho] = identifier[rho0] /(... | def density(self, r, rho0, Ra, Rs):
"""
computes the density
:param x:
:param y:
:param rho0:
:param Ra:
:param Rs:
:return:
"""
(Ra, Rs) = self._sort_ra_rs(Ra, Rs)
rho = rho0 / ((1 + (r / Ra) ** 2) * (1 + (r / Rs) ** 2))
return rho |
def schedule_hangup(self, call_params):
"""REST Schedule Hangup Helper
"""
path = '/' + self.api_version + '/ScheduleHangup/'
method = 'POST'
return self.request(path, method, call_params) | def function[schedule_hangup, parameter[self, call_params]]:
constant[REST Schedule Hangup Helper
]
variable[path] assign[=] binary_operation[binary_operation[constant[/] + name[self].api_version] + constant[/ScheduleHangup/]]
variable[method] assign[=] constant[POST]
return[call[nam... | keyword[def] identifier[schedule_hangup] ( identifier[self] , identifier[call_params] ):
literal[string]
identifier[path] = literal[string] + identifier[self] . identifier[api_version] + literal[string]
identifier[method] = literal[string]
keyword[return] identifier[self] . ide... | def schedule_hangup(self, call_params):
"""REST Schedule Hangup Helper
"""
path = '/' + self.api_version + '/ScheduleHangup/'
method = 'POST'
return self.request(path, method, call_params) |
def type_assert_iter(
iterable,
cls,
cast_from=None,
cast_to=None,
dynamic=None,
objcls=None,
choices=None,
ctor=None,
allow_none=False,
):
""" Checks that every object in @iterable is an instance of @cls
Will also unmarshal JSON objects to Python objects if items in
... | def function[type_assert_iter, parameter[iterable, cls, cast_from, cast_to, dynamic, objcls, choices, ctor, allow_none]]:
constant[ Checks that every object in @iterable is an instance of @cls
Will also unmarshal JSON objects to Python objects if items in
@iterable are an instance of dict
... | keyword[def] identifier[type_assert_iter] (
identifier[iterable] ,
identifier[cls] ,
identifier[cast_from] = keyword[None] ,
identifier[cast_to] = keyword[None] ,
identifier[dynamic] = keyword[None] ,
identifier[objcls] = keyword[None] ,
identifier[choices] = keyword[None] ,
identifier[ctor] = keyword[None] ,... | def type_assert_iter(iterable, cls, cast_from=None, cast_to=None, dynamic=None, objcls=None, choices=None, ctor=None, allow_none=False):
""" Checks that every object in @iterable is an instance of @cls
Will also unmarshal JSON objects to Python objects if items in
@iterable are an instance of dict
... |
def solr_advanced_search(self, query, token=None, limit=20):
"""
Search item metadata using Apache Solr.
:param query: The Apache Lucene search query.
:type query: string
:param token: (optional) A valid token for the user in question.
:type token: None | string
... | def function[solr_advanced_search, parameter[self, query, token, limit]]:
constant[
Search item metadata using Apache Solr.
:param query: The Apache Lucene search query.
:type query: string
:param token: (optional) A valid token for the user in question.
:type token: Non... | keyword[def] identifier[solr_advanced_search] ( identifier[self] , identifier[query] , identifier[token] = keyword[None] , identifier[limit] = literal[int] ):
literal[string]
identifier[parameters] = identifier[dict] ()
identifier[parameters] [ literal[string] ]= identifier[query]
... | def solr_advanced_search(self, query, token=None, limit=20):
"""
Search item metadata using Apache Solr.
:param query: The Apache Lucene search query.
:type query: string
:param token: (optional) A valid token for the user in question.
:type token: None | string
:par... |
def tonos_oxia_converter(text, reverse=False):
"""For the Ancient Greek language. Converts characters accented with the
tonos (meant for Modern Greek) into the oxia equivalent. Without this
normalization, string comparisons will fail."""
for char_tonos, char_oxia in TONOS_OXIA.items():
if no... | def function[tonos_oxia_converter, parameter[text, reverse]]:
constant[For the Ancient Greek language. Converts characters accented with the
tonos (meant for Modern Greek) into the oxia equivalent. Without this
normalization, string comparisons will fail.]
for taget[tuple[[<ast.Name object a... | keyword[def] identifier[tonos_oxia_converter] ( identifier[text] , identifier[reverse] = keyword[False] ):
literal[string]
keyword[for] identifier[char_tonos] , identifier[char_oxia] keyword[in] identifier[TONOS_OXIA] . identifier[items] ():
keyword[if] keyword[not] identifier[reverse] :
... | def tonos_oxia_converter(text, reverse=False):
"""For the Ancient Greek language. Converts characters accented with the
tonos (meant for Modern Greek) into the oxia equivalent. Without this
normalization, string comparisons will fail."""
for (char_tonos, char_oxia) in TONOS_OXIA.items():
if ... |
def _ior(self, other):
"""Set multiplicity of each element to the maximum of the two collections.
if isinstance(other, _basebag):
This runs in O(other.num_unique_elements())
else:
This runs in O(len(other))
"""
# TODO do we have to create a bag from the other first?
if not isinstance(other, _basebag)... | def function[_ior, parameter[self, other]]:
constant[Set multiplicity of each element to the maximum of the two collections.
if isinstance(other, _basebag):
This runs in O(other.num_unique_elements())
else:
This runs in O(len(other))
]
if <ast.UnaryOp object at 0x7da1b260f910> begin[:]
... | keyword[def] identifier[_ior] ( identifier[self] , identifier[other] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[other] , identifier[_basebag] ):
identifier[other] = identifier[self] . identifier[_from_iterable] ( identifier[other] )
keyword[for] identifier[elem... | def _ior(self, other):
"""Set multiplicity of each element to the maximum of the two collections.
if isinstance(other, _basebag):
This runs in O(other.num_unique_elements())
else:
This runs in O(len(other))
""" # TODO do we have to create a bag from the other first?
if not isinstance(other, _baseb... |
def make_constants(builtin_only=False, stoplist=[], verbose=False):
"""
Return a decorator for optimizing global references.
Verify that the first argument is a function.
"""
if type(builtin_only) == type(make_constants):
raise ValueError("The make_constants decorator must have argumen... | def function[make_constants, parameter[builtin_only, stoplist, verbose]]:
constant[
Return a decorator for optimizing global references.
Verify that the first argument is a function.
]
if compare[call[name[type], parameter[name[builtin_only]]] equal[==] call[name[type], parameter[name[make_c... | keyword[def] identifier[make_constants] ( identifier[builtin_only] = keyword[False] , identifier[stoplist] =[], identifier[verbose] = keyword[False] ):
literal[string]
keyword[if] identifier[type] ( identifier[builtin_only] )== identifier[type] ( identifier[make_constants] ):
keyword[raise] i... | def make_constants(builtin_only=False, stoplist=[], verbose=False):
"""
Return a decorator for optimizing global references.
Verify that the first argument is a function.
"""
if type(builtin_only) == type(make_constants):
raise ValueError('The make_constants decorator must have arguments.') ... |
def get_variant_id(variant):
"""Get a variant id on the format chrom_pos_ref_alt"""
variant_id = '_'.join([
str(variant.CHROM),
str(variant.POS),
str(variant.REF),
str(variant.ALT[0])
]
)
return variant_id | def function[get_variant_id, parameter[variant]]:
constant[Get a variant id on the format chrom_pos_ref_alt]
variable[variant_id] assign[=] call[constant[_].join, parameter[list[[<ast.Call object at 0x7da20c7c8e50>, <ast.Call object at 0x7da18fe937c0>, <ast.Call object at 0x7da18fe91d80>, <ast.Call obje... | keyword[def] identifier[get_variant_id] ( identifier[variant] ):
literal[string]
identifier[variant_id] = literal[string] . identifier[join] ([
identifier[str] ( identifier[variant] . identifier[CHROM] ),
identifier[str] ( identifier[variant] . identifier[POS] ),
identifier[str] ( identifier... | def get_variant_id(variant):
"""Get a variant id on the format chrom_pos_ref_alt"""
variant_id = '_'.join([str(variant.CHROM), str(variant.POS), str(variant.REF), str(variant.ALT[0])])
return variant_id |
def set_ip(self, ip):
"""Change the current IP."""
self.set(ip=ip, netmask=self._nm) | def function[set_ip, parameter[self, ip]]:
constant[Change the current IP.]
call[name[self].set, parameter[]] | keyword[def] identifier[set_ip] ( identifier[self] , identifier[ip] ):
literal[string]
identifier[self] . identifier[set] ( identifier[ip] = identifier[ip] , identifier[netmask] = identifier[self] . identifier[_nm] ) | def set_ip(self, ip):
"""Change the current IP."""
self.set(ip=ip, netmask=self._nm) |
def render(self, is_unicode=False, pretty_print=False):
"""Last thing to do before rendering"""
for f in self.graph.xml_filters:
self.root = f(self.root)
args = {'encoding': 'utf-8'}
svg = b''
if etree.lxml:
args['pretty_print'] = pretty_print
if... | def function[render, parameter[self, is_unicode, pretty_print]]:
constant[Last thing to do before rendering]
for taget[name[f]] in starred[name[self].graph.xml_filters] begin[:]
name[self].root assign[=] call[name[f], parameter[name[self].root]]
variable[args] assign[=] dictionar... | keyword[def] identifier[render] ( identifier[self] , identifier[is_unicode] = keyword[False] , identifier[pretty_print] = keyword[False] ):
literal[string]
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[graph] . identifier[xml_filters] :
identifier[self] . iden... | def render(self, is_unicode=False, pretty_print=False):
"""Last thing to do before rendering"""
for f in self.graph.xml_filters:
self.root = f(self.root) # depends on [control=['for'], data=['f']]
args = {'encoding': 'utf-8'}
svg = b''
if etree.lxml:
args['pretty_print'] = pretty_pr... |
def webex_teams_webhook_events():
"""Processes incoming requests to the '/events' URI."""
if request.method == 'GET':
return ("""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Webex Tea... | def function[webex_teams_webhook_events, parameter[]]:
constant[Processes incoming requests to the '/events' URI.]
if compare[name[request].method equal[==] constant[GET]] begin[:]
return[call[constant[<!DOCTYPE html>
<html lang="en">
<head>
... | keyword[def] identifier[webex_teams_webhook_events] ():
literal[string]
keyword[if] identifier[request] . identifier[method] == literal[string] :
keyword[return] ( literal[string] . identifier[format] ( identifier[get_catfact] ()))
keyword[elif] identifier[request] . identifier[method] == l... | def webex_teams_webhook_events():
"""Processes incoming requests to the '/events' URI."""
if request.method == 'GET':
return '<!DOCTYPE html>\n <html lang="en">\n <head>\n <meta charset="UTF-8">\n <title>Webex Te... |
def get_mipmap_pixel(
self, left: float, top: float, right: float, bottom: float
) -> Tuple[int, int, int]:
"""Get the average color of a rectangle in this Image.
Parameters should stay within the following limits:
* 0 <= left < right < Image.width
* 0 <= top < bottom < Imag... | def function[get_mipmap_pixel, parameter[self, left, top, right, bottom]]:
constant[Get the average color of a rectangle in this Image.
Parameters should stay within the following limits:
* 0 <= left < right < Image.width
* 0 <= top < bottom < Image.height
Args:
lef... | keyword[def] identifier[get_mipmap_pixel] (
identifier[self] , identifier[left] : identifier[float] , identifier[top] : identifier[float] , identifier[right] : identifier[float] , identifier[bottom] : identifier[float]
)-> identifier[Tuple] [ identifier[int] , identifier[int] , identifier[int] ]:
literal[s... | def get_mipmap_pixel(self, left: float, top: float, right: float, bottom: float) -> Tuple[int, int, int]:
"""Get the average color of a rectangle in this Image.
Parameters should stay within the following limits:
* 0 <= left < right < Image.width
* 0 <= top < bottom < Image.height
... |
def get_seq_cluster(pdb_id_chain):
"""Get the sequence cluster of a PDB ID plus a pdb_id plus a chain,
Parameters
----------
pdb_id_chain : string
A string denoting a 4 character PDB ID plus a one character chain
offset with a dot: XXXX.X, as in 2F5N.A
Returns
-------
out... | def function[get_seq_cluster, parameter[pdb_id_chain]]:
constant[Get the sequence cluster of a PDB ID plus a pdb_id plus a chain,
Parameters
----------
pdb_id_chain : string
A string denoting a 4 character PDB ID plus a one character chain
offset with a dot: XXXX.X, as in 2F5N.A
... | keyword[def] identifier[get_seq_cluster] ( identifier[pdb_id_chain] ):
literal[string]
identifier[url_root] = literal[string]
identifier[out] = identifier[get_info] ( identifier[pdb_id_chain] , identifier[url_root] = identifier[url_root] )
identifier[out] = identifier[to_dict] ( identifier[out]... | def get_seq_cluster(pdb_id_chain):
"""Get the sequence cluster of a PDB ID plus a pdb_id plus a chain,
Parameters
----------
pdb_id_chain : string
A string denoting a 4 character PDB ID plus a one character chain
offset with a dot: XXXX.X, as in 2F5N.A
Returns
-------
out... |
def _objectmethods(self, obj: str, *args) -> list:
"""
This method parses the SAS log for artifacts (tables and graphics) that were created
from the procedure method call
:param obj: str -- proc object
:param args: list likely none
:return: list -- the tables and graphs ... | def function[_objectmethods, parameter[self, obj]]:
constant[
This method parses the SAS log for artifacts (tables and graphics) that were created
from the procedure method call
:param obj: str -- proc object
:param args: list likely none
:return: list -- the tables and ... | keyword[def] identifier[_objectmethods] ( identifier[self] , identifier[obj] : identifier[str] ,* identifier[args] )-> identifier[list] :
literal[string]
identifier[code] = literal[string]
identifier[code] += identifier[obj]
identifier[code] += literal[string]
identifi... | def _objectmethods(self, obj: str, *args) -> list:
"""
This method parses the SAS log for artifacts (tables and graphics) that were created
from the procedure method call
:param obj: str -- proc object
:param args: list likely none
:return: list -- the tables and graphs avai... |
def _wrap_layer(name, input_layer, build_func, dropout_rate=0.0, trainable=True):
"""Wrap layers with residual, normalization and dropout.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param build_func: A callable that takes the input tensor and generates the outpu... | def function[_wrap_layer, parameter[name, input_layer, build_func, dropout_rate, trainable]]:
constant[Wrap layers with residual, normalization and dropout.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param build_func: A callable that takes the input tensor a... | keyword[def] identifier[_wrap_layer] ( identifier[name] , identifier[input_layer] , identifier[build_func] , identifier[dropout_rate] = literal[int] , identifier[trainable] = keyword[True] ):
literal[string]
identifier[build_output] = identifier[build_func] ( identifier[input_layer] )
keyword[if] ide... | def _wrap_layer(name, input_layer, build_func, dropout_rate=0.0, trainable=True):
"""Wrap layers with residual, normalization and dropout.
:param name: Prefix of names for internal layers.
:param input_layer: Input layer.
:param build_func: A callable that takes the input tensor and generates the outpu... |
def streaming_step(self):
"""
Sync, handle and streaming for each integration step
Returns
-------
None
"""
system = self.system
if system.config.dime_enable:
system.streaming.sync_and_handle()
system.streaming.vars_to_modules()
... | def function[streaming_step, parameter[self]]:
constant[
Sync, handle and streaming for each integration step
Returns
-------
None
]
variable[system] assign[=] name[self].system
if name[system].config.dime_enable begin[:]
call[name[system]... | keyword[def] identifier[streaming_step] ( identifier[self] ):
literal[string]
identifier[system] = identifier[self] . identifier[system]
keyword[if] identifier[system] . identifier[config] . identifier[dime_enable] :
identifier[system] . identifier[streaming] . identifier[sy... | def streaming_step(self):
"""
Sync, handle and streaming for each integration step
Returns
-------
None
"""
system = self.system
if system.config.dime_enable:
system.streaming.sync_and_handle()
system.streaming.vars_to_modules()
system.streami... |
def visit_Compare(self, node):
"""Replace chained comparisons with calls to :func:`.napi_compare`."""
if len(node.ops) > 1:
func = Name(id=self._prefix + 'napi_compare', ctx=Load())
args = [node.left,
List(elts=[Str(op.__class__.__name__)
... | def function[visit_Compare, parameter[self, node]]:
constant[Replace chained comparisons with calls to :func:`.napi_compare`.]
if compare[call[name[len], parameter[name[node].ops]] greater[>] constant[1]] begin[:]
variable[func] assign[=] call[name[Name], parameter[]]
var... | keyword[def] identifier[visit_Compare] ( identifier[self] , identifier[node] ):
literal[string]
keyword[if] identifier[len] ( identifier[node] . identifier[ops] )> literal[int] :
identifier[func] = identifier[Name] ( identifier[id] = identifier[self] . identifier[_prefix] + literal[s... | def visit_Compare(self, node):
"""Replace chained comparisons with calls to :func:`.napi_compare`."""
if len(node.ops) > 1:
func = Name(id=self._prefix + 'napi_compare', ctx=Load())
args = [node.left, List(elts=[Str(op.__class__.__name__) for op in node.ops], ctx=Load()), List(elts=node.comparat... |
def binned_bitsets_proximity( f, chrom_col=0, start_col=1, end_col=2, strand_col=5, upstream=0, downstream=0 ):
"""Read a file into a dictionary of bitsets"""
last_chrom = None
last_bitset = None
bitsets = dict()
for line in f:
if line.startswith("#"): continue
# print "input=%s" % ( ... | def function[binned_bitsets_proximity, parameter[f, chrom_col, start_col, end_col, strand_col, upstream, downstream]]:
constant[Read a file into a dictionary of bitsets]
variable[last_chrom] assign[=] constant[None]
variable[last_bitset] assign[=] constant[None]
variable[bitsets] assign[... | keyword[def] identifier[binned_bitsets_proximity] ( identifier[f] , identifier[chrom_col] = literal[int] , identifier[start_col] = literal[int] , identifier[end_col] = literal[int] , identifier[strand_col] = literal[int] , identifier[upstream] = literal[int] , identifier[downstream] = literal[int] ):
literal[str... | def binned_bitsets_proximity(f, chrom_col=0, start_col=1, end_col=2, strand_col=5, upstream=0, downstream=0):
"""Read a file into a dictionary of bitsets"""
last_chrom = None
last_bitset = None
bitsets = dict()
for line in f:
if line.startswith('#'):
continue # depends on [contr... |
def copy_attr(self, other):
""" Copies all other attributes (not methods)
from the other object to this instance.
"""
if not isinstance(other, Symbol):
return # Nothing done if not a Symbol object
tmp = re.compile('__.*__')
for attr in (x for x in dir(other)... | def function[copy_attr, parameter[self, other]]:
constant[ Copies all other attributes (not methods)
from the other object to this instance.
]
if <ast.UnaryOp object at 0x7da18f8127a0> begin[:]
return[None]
variable[tmp] assign[=] call[name[re].compile, parameter[constant... | keyword[def] identifier[copy_attr] ( identifier[self] , identifier[other] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[other] , identifier[Symbol] ):
keyword[return]
identifier[tmp] = identifier[re] . identifier[compile] ( literal[string]... | def copy_attr(self, other):
""" Copies all other attributes (not methods)
from the other object to this instance.
"""
if not isinstance(other, Symbol):
return # Nothing done if not a Symbol object # depends on [control=['if'], data=[]]
tmp = re.compile('__.*__')
for attr in (x ... |
def pretty_memory_info():
'''
Pretty format memory info.
Returns
-------
str
Memory info.
Examples
--------
>>> pretty_memory_info()
'5MB memory usage'
'''
process = psutil.Process(os.getpid())
return '{}MB memory usage'.format(int(process.memory_info().rss / 2*... | def function[pretty_memory_info, parameter[]]:
constant[
Pretty format memory info.
Returns
-------
str
Memory info.
Examples
--------
>>> pretty_memory_info()
'5MB memory usage'
]
variable[process] assign[=] call[name[psutil].Process, parameter[call[name[os... | keyword[def] identifier[pretty_memory_info] ():
literal[string]
identifier[process] = identifier[psutil] . identifier[Process] ( identifier[os] . identifier[getpid] ())
keyword[return] literal[string] . identifier[format] ( identifier[int] ( identifier[process] . identifier[memory_info] (). identifie... | def pretty_memory_info():
"""
Pretty format memory info.
Returns
-------
str
Memory info.
Examples
--------
>>> pretty_memory_info()
'5MB memory usage'
"""
process = psutil.Process(os.getpid())
return '{}MB memory usage'.format(int(process.memory_info().rss / 2 ... |
def open(self):
'''Opens the stream for reading.'''
options = copy(self.__options)
# Get scheme and format if not already given
compression = None
if self.__scheme is None or self.__format is None:
detected_scheme, detected_format = helpers.detect_scheme_and_format(s... | def function[open, parameter[self]]:
constant[Opens the stream for reading.]
variable[options] assign[=] call[name[copy], parameter[name[self].__options]]
variable[compression] assign[=] constant[None]
if <ast.BoolOp object at 0x7da20c992890> begin[:]
<ast.Tuple object at... | keyword[def] identifier[open] ( identifier[self] ):
literal[string]
identifier[options] = identifier[copy] ( identifier[self] . identifier[__options] )
identifier[compression] = keyword[None]
keyword[if] identifier[self] . identifier[__scheme] keyword[is] keyword[Non... | def open(self):
"""Opens the stream for reading."""
options = copy(self.__options)
# Get scheme and format if not already given
compression = None
if self.__scheme is None or self.__format is None:
(detected_scheme, detected_format) = helpers.detect_scheme_and_format(self.__source)
s... |
def get_instance(self, payload):
"""
Build an instance of DayInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.bulk_exports.export.day.DayInstance
:rtype: twilio.rest.preview.bulk_exports.export.day.DayInstance
"""
return ... | def function[get_instance, parameter[self, payload]]:
constant[
Build an instance of DayInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.bulk_exports.export.day.DayInstance
:rtype: twilio.rest.preview.bulk_exports.export.day.DayInstance
... | keyword[def] identifier[get_instance] ( identifier[self] , identifier[payload] ):
literal[string]
keyword[return] identifier[DayInstance] ( identifier[self] . identifier[_version] , identifier[payload] , identifier[resource_type] = identifier[self] . identifier[_solution] [ literal[string] ],) | def get_instance(self, payload):
"""
Build an instance of DayInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.bulk_exports.export.day.DayInstance
:rtype: twilio.rest.preview.bulk_exports.export.day.DayInstance
"""
return DayInsta... |
def search(query, parent, options):
""" Perform Trac search """
# Extend the default max number of tickets to be fetched
query = "{0}&max={1}".format(query, MAX_TICKETS)
log.debug("Search query: {0}".format(query))
try:
result = parent.proxy.ticket.query(query)
... | def function[search, parameter[query, parent, options]]:
constant[ Perform Trac search ]
variable[query] assign[=] call[constant[{0}&max={1}].format, parameter[name[query], name[MAX_TICKETS]]]
call[name[log].debug, parameter[call[constant[Search query: {0}].format, parameter[name[query]]]]]
... | keyword[def] identifier[search] ( identifier[query] , identifier[parent] , identifier[options] ):
literal[string]
identifier[query] = literal[string] . identifier[format] ( identifier[query] , identifier[MAX_TICKETS] )
identifier[log] . identifier[debug] ( literal[string] . identi... | def search(query, parent, options):
""" Perform Trac search """
# Extend the default max number of tickets to be fetched
query = '{0}&max={1}'.format(query, MAX_TICKETS)
log.debug('Search query: {0}'.format(query))
try:
result = parent.proxy.ticket.query(query) # depends on [control=['try']... |
def _split_keys_v2(joined):
"""
Split two keys out a string created by _join_keys_v2.
"""
left, _, right = joined.rpartition('::')
return _decode_v2(left), _decode_v2(right) | def function[_split_keys_v2, parameter[joined]]:
constant[
Split two keys out a string created by _join_keys_v2.
]
<ast.Tuple object at 0x7da20c76eb60> assign[=] call[name[joined].rpartition, parameter[constant[::]]]
return[tuple[[<ast.Call object at 0x7da20c76d2a0>, <ast.Call object at 0x7d... | keyword[def] identifier[_split_keys_v2] ( identifier[joined] ):
literal[string]
identifier[left] , identifier[_] , identifier[right] = identifier[joined] . identifier[rpartition] ( literal[string] )
keyword[return] identifier[_decode_v2] ( identifier[left] ), identifier[_decode_v2] ( identifier[right... | def _split_keys_v2(joined):
"""
Split two keys out a string created by _join_keys_v2.
"""
(left, _, right) = joined.rpartition('::')
return (_decode_v2(left), _decode_v2(right)) |
def recursive_apply(inval, func):
'''Recursively apply a function to all levels of nested iterables
:param inval: the object to run the function on
:param func: the function that will be run on the inval
'''
if isinstance(inval, dict):
return {k: recursive_apply(v, func) for k, v in inval.i... | def function[recursive_apply, parameter[inval, func]]:
constant[Recursively apply a function to all levels of nested iterables
:param inval: the object to run the function on
:param func: the function that will be run on the inval
]
if call[name[isinstance], parameter[name[inval], name[dict... | keyword[def] identifier[recursive_apply] ( identifier[inval] , identifier[func] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[inval] , identifier[dict] ):
keyword[return] { identifier[k] : identifier[recursive_apply] ( identifier[v] , identifier[func] ) keyword[for] identifi... | def recursive_apply(inval, func):
"""Recursively apply a function to all levels of nested iterables
:param inval: the object to run the function on
:param func: the function that will be run on the inval
"""
if isinstance(inval, dict):
return {k: recursive_apply(v, func) for (k, v) in inval... |
def export_tour(tour_steps, name=None, filename="my_tour.js", url=None):
""" Exports a tour as a JS file.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase runs. "... | def function[export_tour, parameter[tour_steps, name, filename, url]]:
constant[ Exports a tour as a JS file.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase... | keyword[def] identifier[export_tour] ( identifier[tour_steps] , identifier[name] = keyword[None] , identifier[filename] = literal[string] , identifier[url] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[name] :
identifier[name] = literal[string]
keyword[if] identif... | def export_tour(tour_steps, name=None, filename='my_tour.js', url=None):
""" Exports a tour as a JS file.
It will include necessary resources as well, such as jQuery.
You'll be able to copy the tour directly into the Console of
any web browser to play the tour outside of SeleniumBase runs. "... |
def _update_cache(self):
"""
INPUT:
hyperparams: dictionary
OUTPUT: dictionary with the fields
K: kernel
Kinv: inverse of the kernel
L: chol(K)
alpha: solve(K,y)
W: D*Kinv * alpha*alpha^T
"""
cov_params_have_changed = ... | def function[_update_cache, parameter[self]]:
constant[
INPUT:
hyperparams: dictionary
OUTPUT: dictionary with the fields
K: kernel
Kinv: inverse of the kernel
L: chol(K)
alpha: solve(K,y)
W: D*Kinv * alpha*alpha^T
]
v... | keyword[def] identifier[_update_cache] ( identifier[self] ):
literal[string]
identifier[cov_params_have_changed] = identifier[self] . identifier[covar] . identifier[params_have_changed]
keyword[if] identifier[cov_params_have_changed] keyword[or] identifier[self] . identifier[Y_has_cha... | def _update_cache(self):
"""
INPUT:
hyperparams: dictionary
OUTPUT: dictionary with the fields
K: kernel
Kinv: inverse of the kernel
L: chol(K)
alpha: solve(K,y)
W: D*Kinv * alpha*alpha^T
"""
cov_params_have_changed = self.cov... |
def from_structures(structures, transformations=None, extend_collection=0):
"""
Alternative constructor from structures rather than
TransformedStructures.
Args:
structures: Sequence of structures
transformations: New transformations to be applied to all
... | def function[from_structures, parameter[structures, transformations, extend_collection]]:
constant[
Alternative constructor from structures rather than
TransformedStructures.
Args:
structures: Sequence of structures
transformations: New transformations to be appl... | keyword[def] identifier[from_structures] ( identifier[structures] , identifier[transformations] = keyword[None] , identifier[extend_collection] = literal[int] ):
literal[string]
identifier[tstruct] =[ identifier[TransformedStructure] ( identifier[s] ,[]) keyword[for] identifier[s] keyword[in] id... | def from_structures(structures, transformations=None, extend_collection=0):
"""
Alternative constructor from structures rather than
TransformedStructures.
Args:
structures: Sequence of structures
transformations: New transformations to be applied to all
... |
def calibrate_dom(
dom_id,
data,
detector,
livetime=None,
fit_ang_dist=False,
scale_mc_to_data=True,
ad_fit_shape='pexp',
fit_background=True,
ctmin=-1.
):
"""Calibrate intra DOM PMT time offsets, efficiencies and sigmas
Parameters
... | def function[calibrate_dom, parameter[dom_id, data, detector, livetime, fit_ang_dist, scale_mc_to_data, ad_fit_shape, fit_background, ctmin]]:
constant[Calibrate intra DOM PMT time offsets, efficiencies and sigmas
Parameters
----------
dom_id: DOM ID
data: dict of coincidences o... | keyword[def] identifier[calibrate_dom] (
identifier[dom_id] ,
identifier[data] ,
identifier[detector] ,
identifier[livetime] = keyword[None] ,
identifier[fit_ang_dist] = keyword[False] ,
identifier[scale_mc_to_data] = keyword[True] ,
identifier[ad_fit_shape] = literal[string] ,
identifier[fit_background] = ke... | def calibrate_dom(dom_id, data, detector, livetime=None, fit_ang_dist=False, scale_mc_to_data=True, ad_fit_shape='pexp', fit_background=True, ctmin=-1.0):
"""Calibrate intra DOM PMT time offsets, efficiencies and sigmas
Parameters
----------
dom_id: DOM ID
data: dict of coincidences... |
def percent_encode_plus(text, encode_set=QUERY_ENCODE_SET,
encoding='utf-8'):
'''Percent encode text for query strings.
Unlike Python's ``quote_plus``, this function accepts a blacklist instead
of a whitelist of safe characters.
'''
if ' ' not in text:
return percent... | def function[percent_encode_plus, parameter[text, encode_set, encoding]]:
constant[Percent encode text for query strings.
Unlike Python's ``quote_plus``, this function accepts a blacklist instead
of a whitelist of safe characters.
]
if compare[constant[ ] <ast.NotIn object at 0x7da2590d7190... | keyword[def] identifier[percent_encode_plus] ( identifier[text] , identifier[encode_set] = identifier[QUERY_ENCODE_SET] ,
identifier[encoding] = literal[string] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[text] :
keyword[return] identifier[percent_encod... | def percent_encode_plus(text, encode_set=QUERY_ENCODE_SET, encoding='utf-8'):
"""Percent encode text for query strings.
Unlike Python's ``quote_plus``, this function accepts a blacklist instead
of a whitelist of safe characters.
"""
if ' ' not in text:
return percent_encode(text, encode_set... |
def agent_version(self):
"""Get the version of the Juju machine agent.
May return None if the agent is not yet available.
"""
version = self.safe_data['agent-status']['version']
if version:
return client.Number.from_json(version)
else:
return None | def function[agent_version, parameter[self]]:
constant[Get the version of the Juju machine agent.
May return None if the agent is not yet available.
]
variable[version] assign[=] call[call[name[self].safe_data][constant[agent-status]]][constant[version]]
if name[version] begin[:... | keyword[def] identifier[agent_version] ( identifier[self] ):
literal[string]
identifier[version] = identifier[self] . identifier[safe_data] [ literal[string] ][ literal[string] ]
keyword[if] identifier[version] :
keyword[return] identifier[client] . identifier[Number] . iden... | def agent_version(self):
"""Get the version of the Juju machine agent.
May return None if the agent is not yet available.
"""
version = self.safe_data['agent-status']['version']
if version:
return client.Number.from_json(version) # depends on [control=['if'], data=[]]
else:
... |
def print_action(self, test_succeed, action):
'''
Print the detailed info of failed or always print tests.
'''
#self.info_print(">>> {0}",action.keys())
if not test_succeed or action['info']['always_show_run_output']:
output = action['output'].strip()
if o... | def function[print_action, parameter[self, test_succeed, action]]:
constant[
Print the detailed info of failed or always print tests.
]
if <ast.BoolOp object at 0x7da1b2058f40> begin[:]
variable[output] assign[=] call[call[name[action]][constant[output]].strip, parameter[... | keyword[def] identifier[print_action] ( identifier[self] , identifier[test_succeed] , identifier[action] ):
literal[string]
keyword[if] keyword[not] identifier[test_succeed] keyword[or] identifier[action] [ literal[string] ][ literal[string] ]:
identifier[output] = identif... | def print_action(self, test_succeed, action):
"""
Print the detailed info of failed or always print tests.
"""
#self.info_print(">>> {0}",action.keys())
if not test_succeed or action['info']['always_show_run_output']:
output = action['output'].strip()
if output != '':
... |
def _get_memmap(self):
"""Get the memory map for the SEVIRI data"""
with open(self.filename) as fp:
data_dtype = self._get_data_dtype()
hdr_size = native_header.itemsize
return np.memmap(fp, dtype=data_dtype,
shape=(self.mda['number_of_... | def function[_get_memmap, parameter[self]]:
constant[Get the memory map for the SEVIRI data]
with call[name[open], parameter[name[self].filename]] begin[:]
variable[data_dtype] assign[=] call[name[self]._get_data_dtype, parameter[]]
variable[hdr_size] assign[=] name[nativ... | keyword[def] identifier[_get_memmap] ( identifier[self] ):
literal[string]
keyword[with] identifier[open] ( identifier[self] . identifier[filename] ) keyword[as] identifier[fp] :
identifier[data_dtype] = identifier[self] . identifier[_get_data_dtype] ()
identifier[hdr_... | def _get_memmap(self):
"""Get the memory map for the SEVIRI data"""
with open(self.filename) as fp:
data_dtype = self._get_data_dtype()
hdr_size = native_header.itemsize
return np.memmap(fp, dtype=data_dtype, shape=(self.mda['number_of_lines'],), offset=hdr_size, mode='r') # depends on ... |
def check_attr(node, n):
""" Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
"""
if len(node.children) > n:
return node.children[n] | def function[check_attr, parameter[node, n]]:
constant[ Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
]
if compare[call[name[len], parameter[name[node].children]] greater[>] name[n]] begin[:]
return[call[name[node].chi... | keyword[def] identifier[check_attr] ( identifier[node] , identifier[n] ):
literal[string]
keyword[if] identifier[len] ( identifier[node] . identifier[children] )> identifier[n] :
keyword[return] identifier[node] . identifier[children] [ identifier[n] ] | def check_attr(node, n):
""" Check if ATTR has to be normalized
after this instruction has been translated
to intermediate code.
"""
if len(node.children) > n:
return node.children[n] # depends on [control=['if'], data=['n']] |
def C_wedge_meter_Miller(D, H):
r'''Calculates the coefficient of discharge of an wedge flow meter
used for measuring flow rate of fluid, based on the geometry of the
differential pressure flow meter.
For half-inch lines:
.. math::
C = 0.7883 + 0.107(1 - \beta^2)
For ... | def function[C_wedge_meter_Miller, parameter[D, H]]:
constant[Calculates the coefficient of discharge of an wedge flow meter
used for measuring flow rate of fluid, based on the geometry of the
differential pressure flow meter.
For half-inch lines:
.. math::
C = 0.7883 + 0.... | keyword[def] identifier[C_wedge_meter_Miller] ( identifier[D] , identifier[H] ):
literal[string]
identifier[beta] = identifier[diameter_ratio_wedge_meter] ( identifier[D] , identifier[H] )
keyword[if] identifier[D] <= literal[int] * identifier[inch] :
identifier[C] = literal[int] + lite... | def C_wedge_meter_Miller(D, H):
"""Calculates the coefficient of discharge of an wedge flow meter
used for measuring flow rate of fluid, based on the geometry of the
differential pressure flow meter.
For half-inch lines:
.. math::
C = 0.7883 + 0.107(1 - \\beta^2)
For ... |
def link_href(self, rel):
"""Look for link with specified rel, return href from it or None."""
link = self.link(rel)
if (link is not None):
link = link['href']
return(link) | def function[link_href, parameter[self, rel]]:
constant[Look for link with specified rel, return href from it or None.]
variable[link] assign[=] call[name[self].link, parameter[name[rel]]]
if compare[name[link] is_not constant[None]] begin[:]
variable[link] assign[=] call[name[li... | keyword[def] identifier[link_href] ( identifier[self] , identifier[rel] ):
literal[string]
identifier[link] = identifier[self] . identifier[link] ( identifier[rel] )
keyword[if] ( identifier[link] keyword[is] keyword[not] keyword[None] ):
identifier[link] = identifier[link]... | def link_href(self, rel):
"""Look for link with specified rel, return href from it or None."""
link = self.link(rel)
if link is not None:
link = link['href'] # depends on [control=['if'], data=['link']]
return link |
def disable_selinux():
""" disables selinux """
if contains(filename='/etc/selinux/config',
text='SELINUX=enforcing'):
sed('/etc/selinux/config',
'SELINUX=enforcing', 'SELINUX=disabled', use_sudo=True)
if contains(filename='/etc/selinux/config',
text='SE... | def function[disable_selinux, parameter[]]:
constant[ disables selinux ]
if call[name[contains], parameter[]] begin[:]
call[name[sed], parameter[constant[/etc/selinux/config], constant[SELINUX=enforcing], constant[SELINUX=disabled]]]
if call[name[contains], parameter[]] begin[:]
... | keyword[def] identifier[disable_selinux] ():
literal[string]
keyword[if] identifier[contains] ( identifier[filename] = literal[string] ,
identifier[text] = literal[string] ):
identifier[sed] ( literal[string] ,
literal[string] , literal[string] , identifier[use_sudo] = keyword[True... | def disable_selinux():
""" disables selinux """
if contains(filename='/etc/selinux/config', text='SELINUX=enforcing'):
sed('/etc/selinux/config', 'SELINUX=enforcing', 'SELINUX=disabled', use_sudo=True) # depends on [control=['if'], data=[]]
if contains(filename='/etc/selinux/config', text='SELINUX=... |
def update_readme_for_modules(modules):
"""
Update README.md updating the sections for the module names listed.
"""
readme = parse_readme()
module_docstrings = core_module_docstrings()
if modules == ["__all__"]:
modules = core_module_docstrings().keys()
for module in modules:
... | def function[update_readme_for_modules, parameter[modules]]:
constant[
Update README.md updating the sections for the module names listed.
]
variable[readme] assign[=] call[name[parse_readme], parameter[]]
variable[module_docstrings] assign[=] call[name[core_module_docstrings], parameter... | keyword[def] identifier[update_readme_for_modules] ( identifier[modules] ):
literal[string]
identifier[readme] = identifier[parse_readme] ()
identifier[module_docstrings] = identifier[core_module_docstrings] ()
keyword[if] identifier[modules] ==[ literal[string] ]:
identifier[modules] =... | def update_readme_for_modules(modules):
"""
Update README.md updating the sections for the module names listed.
"""
readme = parse_readme()
module_docstrings = core_module_docstrings()
if modules == ['__all__']:
modules = core_module_docstrings().keys() # depends on [control=['if'], dat... |
def orchestration_restore(self, saved_artifact_info, custom_params=None):
"""Orchestration restore
:param saved_artifact_info: json with all required data to restore configuration on the device
:param custom_params: custom parameters
"""
if saved_artifact_info is None or saved_... | def function[orchestration_restore, parameter[self, saved_artifact_info, custom_params]]:
constant[Orchestration restore
:param saved_artifact_info: json with all required data to restore configuration on the device
:param custom_params: custom parameters
]
if <ast.BoolOp object... | keyword[def] identifier[orchestration_restore] ( identifier[self] , identifier[saved_artifact_info] , identifier[custom_params] = keyword[None] ):
literal[string]
keyword[if] identifier[saved_artifact_info] keyword[is] keyword[None] keyword[or] identifier[saved_artifact_info] == literal[strin... | def orchestration_restore(self, saved_artifact_info, custom_params=None):
"""Orchestration restore
:param saved_artifact_info: json with all required data to restore configuration on the device
:param custom_params: custom parameters
"""
if saved_artifact_info is None or saved_artifact_... |
def get_fk_popup_field(cls, *args, **kwargs):
"""
generate fk field related to class wait popup crud
"""
kwargs['popup_name'] = cls.get_class_verbose_name()
kwargs['permissions_required'] = cls.permissions_required
if cls.template_name_fk is not None:
kwargs['... | def function[get_fk_popup_field, parameter[cls]]:
constant[
generate fk field related to class wait popup crud
]
call[name[kwargs]][constant[popup_name]] assign[=] call[name[cls].get_class_verbose_name, parameter[]]
call[name[kwargs]][constant[permissions_required]] assign[=] nam... | keyword[def] identifier[get_fk_popup_field] ( identifier[cls] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[cls] . identifier[get_class_verbose_name] ()
identifier[kwargs] [ literal[string] ]= identifier[cls] . identifier[p... | def get_fk_popup_field(cls, *args, **kwargs):
"""
generate fk field related to class wait popup crud
"""
kwargs['popup_name'] = cls.get_class_verbose_name()
kwargs['permissions_required'] = cls.permissions_required
if cls.template_name_fk is not None:
kwargs['template_name'] = cl... |
def start(self):
"""Sub-command start."""
self.discover()
# startup_info only gets loaded from protocol version 2 on,
# check if it's loaded
if not self.startup_info:
# hack to make environment startable with older protocol
# versions < 2: try to start no... | def function[start, parameter[self]]:
constant[Sub-command start.]
call[name[self].discover, parameter[]]
if <ast.UnaryOp object at 0x7da1b1602e60> begin[:]
if compare[call[name[len], parameter[call[name[self].get_tagged, parameter[list[[<ast.Constant object at 0x7da1b1601930>]]]... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[self] . identifier[discover] ()
keyword[if] keyword[not] identifier[self] . identifier[startup_info] :
keyword[if] identifier[len] ( identifier[self] . ident... | def start(self):
"""Sub-command start."""
self.discover()
# startup_info only gets loaded from protocol version 2 on,
# check if it's loaded
if not self.startup_info:
# hack to make environment startable with older protocol
# versions < 2: try to start nodes via init if all nodes are... |
def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
"""Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node in the tail or head of any hyperedge has not
previously been added to the hypergraph, it will automatically... | def function[add_hyperedges, parameter[self, hyperedges, attr_dict]]:
constant[Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node in the tail or head of any hyperedge has not
previously been added to the hypergraph, it will... | keyword[def] identifier[add_hyperedges] ( identifier[self] , identifier[hyperedges] , identifier[attr_dict] = keyword[None] ,** identifier[attr] ):
literal[string]
identifier[attr_dict] = identifier[self] . identifier[_combine_attribute_arguments] ( identifier[attr_dict] , identifier[attr] )
... | def add_hyperedges(self, hyperedges, attr_dict=None, **attr):
"""Adds multiple hyperedges to the graph, along with any related
attributes of the hyperedges.
If any node in the tail or head of any hyperedge has not
previously been added to the hypergraph, it will automatically
... |
def arp_packet(opcode, src_mac, src_ip, dst_mac, dst_ip):
"""
Generate ARP packet with ethernet encapsulated.
"""
# Generate ethernet header first.
pkt = packet.Packet()
eth_pkt = ethernet.ethernet(dst_mac, src_mac, ETH_TYPE_ARP)
pkt.add_protocol(eth_pkt)
... | def function[arp_packet, parameter[opcode, src_mac, src_ip, dst_mac, dst_ip]]:
constant[
Generate ARP packet with ethernet encapsulated.
]
variable[pkt] assign[=] call[name[packet].Packet, parameter[]]
variable[eth_pkt] assign[=] call[name[ethernet].ethernet, parameter[name[dst_m... | keyword[def] identifier[arp_packet] ( identifier[opcode] , identifier[src_mac] , identifier[src_ip] , identifier[dst_mac] , identifier[dst_ip] ):
literal[string]
identifier[pkt] = identifier[packet] . identifier[Packet] ()
identifier[eth_pkt] = identifier[ethernet] . identifier[et... | def arp_packet(opcode, src_mac, src_ip, dst_mac, dst_ip):
"""
Generate ARP packet with ethernet encapsulated.
"""
# Generate ethernet header first.
pkt = packet.Packet()
eth_pkt = ethernet.ethernet(dst_mac, src_mac, ETH_TYPE_ARP)
pkt.add_protocol(eth_pkt)
# Use IPv4 ARP wrapper f... |
def init_jcrop(min_size=None):
"""Initialize jcrop.
:param min_size: The minimal size of crop area.
"""
init_x = current_app.config['AVATARS_CROP_INIT_POS'][0]
init_y = current_app.config['AVATARS_CROP_INIT_POS'][1]
init_size = current_app.config['AVATARS_CROP_INIT_SIZE'... | def function[init_jcrop, parameter[min_size]]:
constant[Initialize jcrop.
:param min_size: The minimal size of crop area.
]
variable[init_x] assign[=] call[call[name[current_app].config][constant[AVATARS_CROP_INIT_POS]]][constant[0]]
variable[init_y] assign[=] call[call[name[cur... | keyword[def] identifier[init_jcrop] ( identifier[min_size] = keyword[None] ):
literal[string]
identifier[init_x] = identifier[current_app] . identifier[config] [ literal[string] ][ literal[int] ]
identifier[init_y] = identifier[current_app] . identifier[config] [ literal[string] ][ literal... | def init_jcrop(min_size=None):
"""Initialize jcrop.
:param min_size: The minimal size of crop area.
"""
init_x = current_app.config['AVATARS_CROP_INIT_POS'][0]
init_y = current_app.config['AVATARS_CROP_INIT_POS'][1]
init_size = current_app.config['AVATARS_CROP_INIT_SIZE'] or current_app... |
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
obj = Ses... | def function[save, parameter[self, must_create]]:
constant[
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
... | keyword[def] identifier[save] ( identifier[self] , identifier[must_create] = keyword[False] ):
literal[string]
identifier[obj] = identifier[Session] (
identifier[session_key] = identifier[self] . identifier[_get_or_create_session_key] (),
identifier[session_data] = identifier[self... | def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
obj = Session(ses... |
def receive_bytes(self, data):
"""Process bytes received from the network.
Arguments:
data (bytes): any length bytes received from a network connection
to a kafka broker.
Returns:
responses (list of (correlation_id, response)): any/all completed
... | def function[receive_bytes, parameter[self, data]]:
constant[Process bytes received from the network.
Arguments:
data (bytes): any length bytes received from a network connection
to a kafka broker.
Returns:
responses (list of (correlation_id, response)):... | keyword[def] identifier[receive_bytes] ( identifier[self] , identifier[data] ):
literal[string]
identifier[i] = literal[int]
identifier[n] = identifier[len] ( identifier[data] )
identifier[responses] =[]
keyword[while] identifier[i] < identifier[n] :
... | def receive_bytes(self, data):
"""Process bytes received from the network.
Arguments:
data (bytes): any length bytes received from a network connection
to a kafka broker.
Returns:
responses (list of (correlation_id, response)): any/all completed
... |
def dilate_obs(self, dilation_radius):
"""
Use a dilation filter to grow positive observation areas by a specified number of grid points
:param dilation_radius: Number of times to dilate the grid.
:return:
"""
for s in self.size_thresholds:
self.dilated_obs[s... | def function[dilate_obs, parameter[self, dilation_radius]]:
constant[
Use a dilation filter to grow positive observation areas by a specified number of grid points
:param dilation_radius: Number of times to dilate the grid.
:return:
]
for taget[name[s]] in starred[name[s... | keyword[def] identifier[dilate_obs] ( identifier[self] , identifier[dilation_radius] ):
literal[string]
keyword[for] identifier[s] keyword[in] identifier[self] . identifier[size_thresholds] :
identifier[self] . identifier[dilated_obs] [ identifier[s] ]= identifier[np] . identifier[z... | def dilate_obs(self, dilation_radius):
"""
Use a dilation filter to grow positive observation areas by a specified number of grid points
:param dilation_radius: Number of times to dilate the grid.
:return:
"""
for s in self.size_thresholds:
self.dilated_obs[s] = np.zeros... |
def split_root(self):
"""Splits this path into a pair (drive, location).
Note that, because all paths are normalized, a root of ``'.'`` will be
returned for relative paths.
"""
if not PY3 and hasattr(self._lib, 'splitunc'):
root, rest = self._lib.splitunc(self.path)
... | def function[split_root, parameter[self]]:
constant[Splits this path into a pair (drive, location).
Note that, because all paths are normalized, a root of ``'.'`` will be
returned for relative paths.
]
if <ast.BoolOp object at 0x7da1b2879000> begin[:]
<ast.Tuple ... | keyword[def] identifier[split_root] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[PY3] keyword[and] identifier[hasattr] ( identifier[self] . identifier[_lib] , literal[string] ):
identifier[root] , identifier[rest] = identifier[self] . identifier[_lib] .... | def split_root(self):
"""Splits this path into a pair (drive, location).
Note that, because all paths are normalized, a root of ``'.'`` will be
returned for relative paths.
"""
if not PY3 and hasattr(self._lib, 'splitunc'):
(root, rest) = self._lib.splitunc(self.path)
if... |
def RMSE(x1, x2=-1):
"""
Root-mean-square error - this function accepts two series of data
or directly one series with error.
**Args:**
* `x1` - first data series or error (1d array)
**Kwargs:**
* `x2` - second series (1d array) if first series was not error directly,\\
then this... | def function[RMSE, parameter[x1, x2]]:
constant[
Root-mean-square error - this function accepts two series of data
or directly one series with error.
**Args:**
* `x1` - first data series or error (1d array)
**Kwargs:**
* `x2` - second series (1d array) if first series was not error d... | keyword[def] identifier[RMSE] ( identifier[x1] , identifier[x2] =- literal[int] ):
literal[string]
identifier[e] = identifier[get_valid_error] ( identifier[x1] , identifier[x2] )
keyword[return] identifier[np] . identifier[sqrt] ( identifier[np] . identifier[dot] ( identifier[e] , identifier[e] )/ id... | def RMSE(x1, x2=-1):
"""
Root-mean-square error - this function accepts two series of data
or directly one series with error.
**Args:**
* `x1` - first data series or error (1d array)
**Kwargs:**
* `x2` - second series (1d array) if first series was not error directly,\\
then this... |
def _genLoggingFilePath():
""" Generate a filepath for the calling app """
appName = os.path.splitext(os.path.basename(sys.argv[0]))[0] or 'UnknownApp'
appLogDir = os.path.abspath(os.path.join(
os.environ['NTA_LOG_DIR'],
'numenta-logs-%s' % (os.environ['USER'],),
appName))
appLogFileName = '%s-%s-%s... | def function[_genLoggingFilePath, parameter[]]:
constant[ Generate a filepath for the calling app ]
variable[appName] assign[=] <ast.BoolOp object at 0x7da18dc07790>
variable[appLogDir] assign[=] call[name[os].path.abspath, parameter[call[name[os].path.join, parameter[call[name[os].environ][cons... | keyword[def] identifier[_genLoggingFilePath] ():
literal[string]
identifier[appName] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[os] . identifier[path] . identifier[basename] ( identifier[sys] . identifier[argv] [ literal[int] ]))[ literal[int] ] keyword[or] literal[string]
ide... | def _genLoggingFilePath():
""" Generate a filepath for the calling app """
appName = os.path.splitext(os.path.basename(sys.argv[0]))[0] or 'UnknownApp'
appLogDir = os.path.abspath(os.path.join(os.environ['NTA_LOG_DIR'], 'numenta-logs-%s' % (os.environ['USER'],), appName))
appLogFileName = '%s-%s-%s.log'... |
def _draw_cursor(self, dc, grid, row, col,
pen=None, brush=None):
"""Draws cursor as Rectangle in lower right corner"""
# If in full screen mode draw no cursor
if grid.main_window.IsFullScreen():
return
key = row, col, grid.current_table
rect = ... | def function[_draw_cursor, parameter[self, dc, grid, row, col, pen, brush]]:
constant[Draws cursor as Rectangle in lower right corner]
if call[name[grid].main_window.IsFullScreen, parameter[]] begin[:]
return[None]
variable[key] assign[=] tuple[[<ast.Name object at 0x7da1b17204f0>, <ast.... | keyword[def] identifier[_draw_cursor] ( identifier[self] , identifier[dc] , identifier[grid] , identifier[row] , identifier[col] ,
identifier[pen] = keyword[None] , identifier[brush] = keyword[None] ):
literal[string]
keyword[if] identifier[grid] . identifier[main_window] . identifier[I... | def _draw_cursor(self, dc, grid, row, col, pen=None, brush=None):
"""Draws cursor as Rectangle in lower right corner"""
# If in full screen mode draw no cursor
if grid.main_window.IsFullScreen():
return # depends on [control=['if'], data=[]]
key = (row, col, grid.current_table)
rect = grid.... |
def locateChild(self, ctx, segments):
"""
Retrieve a L{SharingIndex} for a particular user, or rend.NotFound.
"""
store = _storeFromUsername(
self.loginSystem.store, segments[0].decode('utf-8'))
if store is None:
return rend.NotFound
return (Sharin... | def function[locateChild, parameter[self, ctx, segments]]:
constant[
Retrieve a L{SharingIndex} for a particular user, or rend.NotFound.
]
variable[store] assign[=] call[name[_storeFromUsername], parameter[name[self].loginSystem.store, call[call[name[segments]][constant[0]].decode, param... | keyword[def] identifier[locateChild] ( identifier[self] , identifier[ctx] , identifier[segments] ):
literal[string]
identifier[store] = identifier[_storeFromUsername] (
identifier[self] . identifier[loginSystem] . identifier[store] , identifier[segments] [ literal[int] ]. identifier[decode... | def locateChild(self, ctx, segments):
"""
Retrieve a L{SharingIndex} for a particular user, or rend.NotFound.
"""
store = _storeFromUsername(self.loginSystem.store, segments[0].decode('utf-8'))
if store is None:
return rend.NotFound # depends on [control=['if'], data=[]]
return ... |
def createExperimentArgs():
"""Run the basic probability of false positives experiment."""
experimentArguments = []
# for n in [300, 500, 700, 900, 1100, 1300, 1500, 1700, 1900, 2100, 2300,
# 2500, 2700, 2900, 3100, 3300, 3500, 3700, 3900]:
for n in [1500, 1700, 1900, 2100]:
for a in [128]:
... | def function[createExperimentArgs, parameter[]]:
constant[Run the basic probability of false positives experiment.]
variable[experimentArguments] assign[=] list[[]]
for taget[name[n]] in starred[list[[<ast.Constant object at 0x7da1b0832d70>, <ast.Constant object at 0x7da1b0832d10>, <ast.Constant... | keyword[def] identifier[createExperimentArgs] ():
literal[string]
identifier[experimentArguments] =[]
keyword[for] identifier[n] keyword[in] [ literal[int] , literal[int] , literal[int] , literal[int] ]:
keyword[for] identifier[a] keyword[in] [ literal[int] ]:
keyword[if] ( identi... | def createExperimentArgs():
"""Run the basic probability of false positives experiment."""
experimentArguments = []
# for n in [300, 500, 700, 900, 1100, 1300, 1500, 1700, 1900, 2100, 2300,
# 2500, 2700, 2900, 3100, 3300, 3500, 3700, 3900]:
for n in [1500, 1700, 1900, 2100]:
for a ... |
def _compute_raw_moments(self, n_counter, k_counter):
# The symbols for expectations are simply the first order raw moments.
"""
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
:type n_counter: list[:class:`~means.core.descriptors.Momen... | def function[_compute_raw_moments, parameter[self, n_counter, k_counter]]:
constant[
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
:type n_counter: list[:class:`~means.core.descriptors.Moment`]
:param k_counter: a list of :class:`~mean... | keyword[def] identifier[_compute_raw_moments] ( identifier[self] , identifier[n_counter] , identifier[k_counter] ):
literal[string]
identifier[expectation_symbols] =[ identifier[pm] . identifier[symbol] keyword[for] identifier[pm] keyword[in] identifier[k_counter] keyword[if] identifier[pm]... | def _compute_raw_moments(self, n_counter, k_counter):
# The symbols for expectations are simply the first order raw moments.
'\n :param n_counter: a list of :class:`~means.core.descriptors.Moment`\\s representing central moments\n :type n_counter: list[:class:`~means.core.descriptors.Moment`]\n ... |
def pad_width(model, table_padding=0.85, tabs_padding=1.2):
"""
Computes the width of a model and sets up appropriate padding
for Tabs and DataTable types.
"""
if isinstance(model, Row):
vals = [pad_width(child) for child in model.children]
width = np.max([v for v in vals if v is not... | def function[pad_width, parameter[model, table_padding, tabs_padding]]:
constant[
Computes the width of a model and sets up appropriate padding
for Tabs and DataTable types.
]
if call[name[isinstance], parameter[name[model], name[Row]]] begin[:]
variable[vals] assign[=] <ast.... | keyword[def] identifier[pad_width] ( identifier[model] , identifier[table_padding] = literal[int] , identifier[tabs_padding] = literal[int] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[model] , identifier[Row] ):
identifier[vals] =[ identifier[pad_width] ( identifier[child] ... | def pad_width(model, table_padding=0.85, tabs_padding=1.2):
"""
Computes the width of a model and sets up appropriate padding
for Tabs and DataTable types.
"""
if isinstance(model, Row):
vals = [pad_width(child) for child in model.children]
width = np.max([v for v in vals if v is not... |
def next_state(self):
"""This is a method that will be called when the time remaining ends.
The current state can be: roasting, cooling, idle, sleeping, connecting,
or unkown."""
if(self.roaster.get_roaster_state() == 'roasting'):
self.roaster.time_remaining = 20
... | def function[next_state, parameter[self]]:
constant[This is a method that will be called when the time remaining ends.
The current state can be: roasting, cooling, idle, sleeping, connecting,
or unkown.]
if compare[call[name[self].roaster.get_roaster_state, parameter[]] equal[==] constan... | keyword[def] identifier[next_state] ( identifier[self] ):
literal[string]
keyword[if] ( identifier[self] . identifier[roaster] . identifier[get_roaster_state] ()== literal[string] ):
identifier[self] . identifier[roaster] . identifier[time_remaining] = literal[int]
identi... | def next_state(self):
"""This is a method that will be called when the time remaining ends.
The current state can be: roasting, cooling, idle, sleeping, connecting,
or unkown."""
if self.roaster.get_roaster_state() == 'roasting':
self.roaster.time_remaining = 20
self.roaster.cool... |
def dt_to_timestamp(dt):
"""Converts from a :class:`~datetime.datetime` object to an integer
timestamp, suitable interoperation with :func:`time.time` and
other `Epoch-based timestamps`.
.. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time
>>> abs(round(time.time() - dt_to_timestamp... | def function[dt_to_timestamp, parameter[dt]]:
constant[Converts from a :class:`~datetime.datetime` object to an integer
timestamp, suitable interoperation with :func:`time.time` and
other `Epoch-based timestamps`.
.. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time
>>> abs(roun... | keyword[def] identifier[dt_to_timestamp] ( identifier[dt] ):
literal[string]
keyword[if] identifier[dt] . identifier[tzinfo] :
identifier[td] = identifier[dt] - identifier[EPOCH_AWARE]
keyword[else] :
identifier[td] = identifier[dt] - identifier[EPOCH_NAIVE]
keyword[return] ... | def dt_to_timestamp(dt):
"""Converts from a :class:`~datetime.datetime` object to an integer
timestamp, suitable interoperation with :func:`time.time` and
other `Epoch-based timestamps`.
.. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time
>>> abs(round(time.time() - dt_to_timestamp... |
def pretty_descriptor(self):
"""
assemble a long member name from access flags, type, argument
types, exceptions as applicable
"""
f = " ".join(self.pretty_access_flags())
p = self.pretty_type()
n = self.get_name()
t = ",".join(self.pretty_exceptions())
... | def function[pretty_descriptor, parameter[self]]:
constant[
assemble a long member name from access flags, type, argument
types, exceptions as applicable
]
variable[f] assign[=] call[constant[ ].join, parameter[call[name[self].pretty_access_flags, parameter[]]]]
variable[... | keyword[def] identifier[pretty_descriptor] ( identifier[self] ):
literal[string]
identifier[f] = literal[string] . identifier[join] ( identifier[self] . identifier[pretty_access_flags] ())
identifier[p] = identifier[self] . identifier[pretty_type] ()
identifier[n] = identifier[se... | def pretty_descriptor(self):
"""
assemble a long member name from access flags, type, argument
types, exceptions as applicable
"""
f = ' '.join(self.pretty_access_flags())
p = self.pretty_type()
n = self.get_name()
t = ','.join(self.pretty_exceptions())
if n == '<init>':
... |
def set_terminal_size(fd, size):
"""Set the (width, height) size tuple for the given pty fd."""
sizebuf = array.array('h', reversed(size))
fcntl.ioctl(fd, termios.TIOCSWINSZ, sizebuf) | def function[set_terminal_size, parameter[fd, size]]:
constant[Set the (width, height) size tuple for the given pty fd.]
variable[sizebuf] assign[=] call[name[array].array, parameter[constant[h], call[name[reversed], parameter[name[size]]]]]
call[name[fcntl].ioctl, parameter[name[fd], name[termi... | keyword[def] identifier[set_terminal_size] ( identifier[fd] , identifier[size] ):
literal[string]
identifier[sizebuf] = identifier[array] . identifier[array] ( literal[string] , identifier[reversed] ( identifier[size] ))
identifier[fcntl] . identifier[ioctl] ( identifier[fd] , identifier[termios] . id... | def set_terminal_size(fd, size):
"""Set the (width, height) size tuple for the given pty fd."""
sizebuf = array.array('h', reversed(size))
fcntl.ioctl(fd, termios.TIOCSWINSZ, sizebuf) |
def serialize(self):
"""
:returns: A dictionary representation of the statement object.
:rtype: dict
"""
data = {}
for field_name in self.get_statement_field_names():
format_method = getattr(self, 'get_{}'.format(
field_name
), Non... | def function[serialize, parameter[self]]:
constant[
:returns: A dictionary representation of the statement object.
:rtype: dict
]
variable[data] assign[=] dictionary[[], []]
for taget[name[field_name]] in starred[call[name[self].get_statement_field_names, parameter[]]] be... | keyword[def] identifier[serialize] ( identifier[self] ):
literal[string]
identifier[data] ={}
keyword[for] identifier[field_name] keyword[in] identifier[self] . identifier[get_statement_field_names] ():
identifier[format_method] = identifier[getattr] ( identifier[self] , l... | def serialize(self):
"""
:returns: A dictionary representation of the statement object.
:rtype: dict
"""
data = {}
for field_name in self.get_statement_field_names():
format_method = getattr(self, 'get_{}'.format(field_name), None)
if format_method:
data[f... |
def get_attributes(path):
'''
Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
salt '*' file.get_attributes... | def function[get_attributes, parameter[path]]:
constant[
Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
... | keyword[def] identifier[get_attributes] ( identifier[path] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[path] ):
keyword[raise] identifier[CommandExecutionError] ( literal[string] . identifier[format] ( identifier[path] ))
... | def get_attributes(path):
"""
Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
salt '*' file.get_attributes... |
def get_time_server():
'''
Display the currently set network time server.
:return: the network time server
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time_server
'''
ret = salt.utils.mac_utils.execute_return_result(
'systemsetup -getnetworktim... | def function[get_time_server, parameter[]]:
constant[
Display the currently set network time server.
:return: the network time server
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time_server
]
variable[ret] assign[=] call[name[salt].utils.mac_ut... | keyword[def] identifier[get_time_server] ():
literal[string]
identifier[ret] = identifier[salt] . identifier[utils] . identifier[mac_utils] . identifier[execute_return_result] (
literal[string] )
keyword[return] identifier[salt] . identifier[utils] . identifier[mac_utils] . identifier[parse_retu... | def get_time_server():
"""
Display the currently set network time server.
:return: the network time server
:rtype: str
CLI Example:
.. code-block:: bash
salt '*' timezone.get_time_server
"""
ret = salt.utils.mac_utils.execute_return_result('systemsetup -getnetworktimeserver')... |
def to_comment(comment):
"""
Convert a string to a ``.properties`` file comment. All non-Latin-1
characters in the string are escaped using ``\\uXXXX`` escapes (after
converting non-BMP characters to surrogate pairs), a ``#`` is prepended to
the string, any CR LF or CR line breaks in the string are... | def function[to_comment, parameter[comment]]:
constant[
Convert a string to a ``.properties`` file comment. All non-Latin-1
characters in the string are escaped using ``\uXXXX`` escapes (after
converting non-BMP characters to surrogate pairs), a ``#`` is prepended to
the string, any CR LF or CR... | keyword[def] identifier[to_comment] ( identifier[comment] ):
literal[string]
keyword[return] literal[string] + identifier[re] . identifier[sub] ( literal[string] , identifier[_esc] ,
identifier[re] . identifier[sub] ( literal[string] , literal[string] ,
identifier[re] . identifier[sub] ( literal... | def to_comment(comment):
"""
Convert a string to a ``.properties`` file comment. All non-Latin-1
characters in the string are escaped using ``\\uXXXX`` escapes (after
converting non-BMP characters to surrogate pairs), a ``#`` is prepended to
the string, any CR LF or CR line breaks in the string are... |
def create_router(self, name, ext_network=None, admin_state_up=True):
'''
Creates a new router
'''
body = {'name': name,
'admin_state_up': admin_state_up}
if ext_network:
net_id = self._find_network_id(ext_network)
body['external_gateway_in... | def function[create_router, parameter[self, name, ext_network, admin_state_up]]:
constant[
Creates a new router
]
variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da1b1c466b0>, <ast.Constant object at 0x7da1b1c46530>], [<ast.Name object at 0x7da1b1c46020>, <ast.Name object... | keyword[def] identifier[create_router] ( identifier[self] , identifier[name] , identifier[ext_network] = keyword[None] , identifier[admin_state_up] = keyword[True] ):
literal[string]
identifier[body] ={ literal[string] : identifier[name] ,
literal[string] : identifier[admin_state_up] }
... | def create_router(self, name, ext_network=None, admin_state_up=True):
"""
Creates a new router
"""
body = {'name': name, 'admin_state_up': admin_state_up}
if ext_network:
net_id = self._find_network_id(ext_network)
body['external_gateway_info'] = {'network_id': net_id} # dep... |
def enter(self, node):
'''
Tries to invoke a method matching the pattern *enter_<type name>*, where
<type name> is the name of the type of the *node*.
'''
name = 'enter_' + node.__class__.__name__
fn = getattr(self, name, self.default_enter)
fn(node) | def function[enter, parameter[self, node]]:
constant[
Tries to invoke a method matching the pattern *enter_<type name>*, where
<type name> is the name of the type of the *node*.
]
variable[name] assign[=] binary_operation[constant[enter_] + name[node].__class__.__name__]
... | keyword[def] identifier[enter] ( identifier[self] , identifier[node] ):
literal[string]
identifier[name] = literal[string] + identifier[node] . identifier[__class__] . identifier[__name__]
identifier[fn] = identifier[getattr] ( identifier[self] , identifier[name] , identifier[self] . iden... | def enter(self, node):
"""
Tries to invoke a method matching the pattern *enter_<type name>*, where
<type name> is the name of the type of the *node*.
"""
name = 'enter_' + node.__class__.__name__
fn = getattr(self, name, self.default_enter)
fn(node) |
def value(self, value, *args, **kwargs):
"""
Takes a string value and returns the Date based on the format
"""
from datetime import datetime
value = self.obj.value(value, *args, **kwargs)
try:
rv = datetime.strptime(value, self.format)
except ValueErro... | def function[value, parameter[self, value]]:
constant[
Takes a string value and returns the Date based on the format
]
from relative_module[datetime] import module[datetime]
variable[value] assign[=] call[name[self].obj.value, parameter[name[value], <ast.Starred object at 0x7da1b15b3... | keyword[def] identifier[value] ( identifier[self] , identifier[value] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[datetime] keyword[import] identifier[datetime]
identifier[value] = identifier[self] . identifier[obj] . identifier[value] ( ident... | def value(self, value, *args, **kwargs):
"""
Takes a string value and returns the Date based on the format
"""
from datetime import datetime
value = self.obj.value(value, *args, **kwargs)
try:
rv = datetime.strptime(value, self.format) # depends on [control=['try'], data=[]]
... |
def get_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(
prog=__title__,
description=__description__,
)
parser.add_argument(
'--testdb', action='store_true',
help='create and use a database with test users'
)
parser.add_argument(
... | def function[get_args, parameter[]]:
constant[Parse command line arguments.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[--testdb]]]
call[name[parser].add_argument, parameter[constant[-v], constant[--verbo... | keyword[def] identifier[get_args] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[prog] = identifier[__title__] ,
identifier[description] = identifier[__description__] ,
)
identifier[parser] . identifier[add_argument] (
literal... | def get_args():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(prog=__title__, description=__description__)
parser.add_argument('--testdb', action='store_true', help='create and use a database with test users')
parser.add_argument('-v', '--verbose', action='store_true', help='print... |
def plot_xbt(fignum, XB, T, e, b):
""" function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
"""
plt.figure(num=fignum)
plt.clf()
if not isServer:
plt.figtext(.02, .01, version_num)
plt.xlabel('Field (T)')
plt.ylabel('S... | def function[plot_xbt, parameter[fignum, XB, T, e, b]]:
constant[ function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
]
call[name[plt].figure, parameter[]]
call[name[plt].clf, parameter[]]
if <ast.UnaryOp object at 0x... | keyword[def] identifier[plot_xbt] ( identifier[fignum] , identifier[XB] , identifier[T] , identifier[e] , identifier[b] ):
literal[string]
identifier[plt] . identifier[figure] ( identifier[num] = identifier[fignum] )
identifier[plt] . identifier[clf] ()
keyword[if] keyword[not] identifier[isSer... | def plot_xbt(fignum, XB, T, e, b):
""" function to plot series of chi measurements as a function of temperature, holding field constant and varying frequency
"""
plt.figure(num=fignum)
plt.clf()
if not isServer:
plt.figtext(0.02, 0.01, version_num) # depends on [control=['if'], data=[]]
... |
def to_text(self, origin=None, relativize=True, **kw):
"""Convert the message to text.
The I{origin}, I{relativize}, and any other keyword
arguments are passed to the rrset to_wire() method.
@rtype: string
"""
s = cStringIO.StringIO()
print >> s, 'id %d' % sel... | def function[to_text, parameter[self, origin, relativize]]:
constant[Convert the message to text.
The I{origin}, I{relativize}, and any other keyword
arguments are passed to the rrset to_wire() method.
@rtype: string
]
variable[s] assign[=] call[name[cStringIO].StringIO... | keyword[def] identifier[to_text] ( identifier[self] , identifier[origin] = keyword[None] , identifier[relativize] = keyword[True] ,** identifier[kw] ):
literal[string]
identifier[s] = identifier[cStringIO] . identifier[StringIO] ()
identifier[print] >> identifier[s] , literal[string] % id... | def to_text(self, origin=None, relativize=True, **kw):
"""Convert the message to text.
The I{origin}, I{relativize}, and any other keyword
arguments are passed to the rrset to_wire() method.
@rtype: string
"""
s = cStringIO.StringIO()
(print >> s, 'id %d' % self.id)
(pr... |
def make_tx_signatures(txs_to_sign, privkey_list, pubkey_list):
"""
Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list
Not sure what privkeys and pubkeys to supply?
Use get_input_addresses() to return a list of addresses.
Matching those addresses to keys is up to you ... | def function[make_tx_signatures, parameter[txs_to_sign, privkey_list, pubkey_list]]:
constant[
Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list
Not sure what privkeys and pubkeys to supply?
Use get_input_addresses() to return a list of addresses.
Matching those ... | keyword[def] identifier[make_tx_signatures] ( identifier[txs_to_sign] , identifier[privkey_list] , identifier[pubkey_list] ):
literal[string]
keyword[assert] identifier[len] ( identifier[privkey_list] )== identifier[len] ( identifier[pubkey_list] )== identifier[len] ( identifier[txs_to_sign] )
... | def make_tx_signatures(txs_to_sign, privkey_list, pubkey_list):
"""
Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list
Not sure what privkeys and pubkeys to supply?
Use get_input_addresses() to return a list of addresses.
Matching those addresses to keys is up to you ... |
def file_field(*args, **kwargs):
'''
File field
'''
file_field = wtforms.FileField(*args, **kwargs)
file_field.input_type = 'file_field'
return file_field | def function[file_field, parameter[]]:
constant[
File field
]
variable[file_field] assign[=] call[name[wtforms].FileField, parameter[<ast.Starred object at 0x7da18c4cdde0>]]
name[file_field].input_type assign[=] constant[file_field]
return[name[file_field]] | keyword[def] identifier[file_field] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[file_field] = identifier[wtforms] . identifier[FileField] (* identifier[args] ,** identifier[kwargs] )
identifier[file_field] . identifier[input_type] = literal[string]
keyword[return] i... | def file_field(*args, **kwargs):
"""
File field
"""
file_field = wtforms.FileField(*args, **kwargs)
file_field.input_type = 'file_field'
return file_field |
def get_reflectance_lut(self):
"""Read the LUT with reflectances as a function of wavelength, satellite zenith
secant, azimuth difference angle, and sun zenith secant
"""
if self._rayl is None:
lut_vars = get_reflectance_lut(self.reflectance_lut_filename)
self._r... | def function[get_reflectance_lut, parameter[self]]:
constant[Read the LUT with reflectances as a function of wavelength, satellite zenith
secant, azimuth difference angle, and sun zenith secant
]
if compare[name[self]._rayl is constant[None]] begin[:]
variable[lut_vars] ... | keyword[def] identifier[get_reflectance_lut] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_rayl] keyword[is] keyword[None] :
identifier[lut_vars] = identifier[get_reflectance_lut] ( identifier[self] . identifier[reflectance_lut_filename] )
... | def get_reflectance_lut(self):
"""Read the LUT with reflectances as a function of wavelength, satellite zenith
secant, azimuth difference angle, and sun zenith secant
"""
if self._rayl is None:
lut_vars = get_reflectance_lut(self.reflectance_lut_filename)
self._rayl = lut_vars[0... |
def main():
'''Main routine.'''
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
'--vmssname', '-n', required=True, action='store', help='VMSS Name')
arg_parser.add_argument('--rgname', '-g', required=True, action='store',
... | def function[main, parameter[]]:
constant[Main routine.]
variable[arg_parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[arg_parser].add_argument, parameter[constant[--vmssname], constant[-n]]]
call[name[arg_parser].add_argument, parameter[constant[--rgname], co... | keyword[def] identifier[main] ():
literal[string]
identifier[arg_parser] = identifier[argparse] . identifier[ArgumentParser] ()
identifier[arg_parser] . identifier[add_argument] (
literal[string] , literal[string] , identifier[required] = keyword[True] , identifier[action] = literal[string] ... | def main():
"""Main routine."""
# validate command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--vmssname', '-n', required=True, action='store', help='VMSS Name')
arg_parser.add_argument('--rgname', '-g', required=True, action='store', help='Resource Group Name')
... |
def is_exchange(self, reaction_id):
"""Whether the given reaction is an exchange reaction."""
reaction = self.get_reaction(reaction_id)
return (len(reaction.left) == 0) != (len(reaction.right) == 0) | def function[is_exchange, parameter[self, reaction_id]]:
constant[Whether the given reaction is an exchange reaction.]
variable[reaction] assign[=] call[name[self].get_reaction, parameter[name[reaction_id]]]
return[compare[compare[call[name[len], parameter[name[reaction].left]] equal[==] constant[0]... | keyword[def] identifier[is_exchange] ( identifier[self] , identifier[reaction_id] ):
literal[string]
identifier[reaction] = identifier[self] . identifier[get_reaction] ( identifier[reaction_id] )
keyword[return] ( identifier[len] ( identifier[reaction] . identifier[left] )== literal[int] )... | def is_exchange(self, reaction_id):
"""Whether the given reaction is an exchange reaction."""
reaction = self.get_reaction(reaction_id)
return (len(reaction.left) == 0) != (len(reaction.right) == 0) |
def parse(cls, text):
"""
Parse the given text. Returns a tuple:
(list_of_parts, start_pos_of_the_last_part).
"""
OUTSIDE, IN_DOUBLE, IN_SINGLE = 0, 1, 2
iterator = enumerate(text)
state = OUTSIDE
parts = []
current_part = ''
part_start_po... | def function[parse, parameter[cls, text]]:
constant[
Parse the given text. Returns a tuple:
(list_of_parts, start_pos_of_the_last_part).
]
<ast.Tuple object at 0x7da2049601c0> assign[=] tuple[[<ast.Constant object at 0x7da204963130>, <ast.Constant object at 0x7da204961ba0>, <ast.... | keyword[def] identifier[parse] ( identifier[cls] , identifier[text] ):
literal[string]
identifier[OUTSIDE] , identifier[IN_DOUBLE] , identifier[IN_SINGLE] = literal[int] , literal[int] , literal[int]
identifier[iterator] = identifier[enumerate] ( identifier[text] )
identifier[st... | def parse(cls, text):
"""
Parse the given text. Returns a tuple:
(list_of_parts, start_pos_of_the_last_part).
"""
(OUTSIDE, IN_DOUBLE, IN_SINGLE) = (0, 1, 2)
iterator = enumerate(text)
state = OUTSIDE
parts = []
current_part = ''
part_start_pos = 0
for (i, c) in i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.