code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def getType(self, short=False):
"""Return a string describing the type of the location, i.e. origin, on axis, off axis etc.
::
>>> l = Location()
>>> l.getType()
'origin'
>>> l = Location(pop=1)
>>> l.getType()
'on-axi... | def function[getType, parameter[self, short]]:
constant[Return a string describing the type of the location, i.e. origin, on axis, off axis etc.
::
>>> l = Location()
>>> l.getType()
'origin'
>>> l = Location(pop=1)
>>> l.getType(... | keyword[def] identifier[getType] ( identifier[self] , identifier[short] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[isOrigin] ():
keyword[return] literal[string]
identifier[t] =[]
identifier[onAxis] = identifier[self] . identifier[... | def getType(self, short=False):
"""Return a string describing the type of the location, i.e. origin, on axis, off axis etc.
::
>>> l = Location()
>>> l.getType()
'origin'
>>> l = Location(pop=1)
>>> l.getType()
'on-axis, p... |
def is_dir_or_file(dirname):
'''Checks if a path is an actual directory that exists or a file'''
if not os.path.isdir(dirname) and not os.path.isfile(dirname):
msg = "{0} is not a directory nor a file".format(dirname)
raise argparse.ArgumentTypeError(msg)
else:
return dirname | def function[is_dir_or_file, parameter[dirname]]:
constant[Checks if a path is an actual directory that exists or a file]
if <ast.BoolOp object at 0x7da18f09cfd0> begin[:]
variable[msg] assign[=] call[constant[{0} is not a directory nor a file].format, parameter[name[dirname]]]
<... | keyword[def] identifier[is_dir_or_file] ( identifier[dirname] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[dirname] ) keyword[and] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[dirname] ):
iden... | def is_dir_or_file(dirname):
"""Checks if a path is an actual directory that exists or a file"""
if not os.path.isdir(dirname) and (not os.path.isfile(dirname)):
msg = '{0} is not a directory nor a file'.format(dirname)
raise argparse.ArgumentTypeError(msg) # depends on [control=['if'], data=[]... |
def add_behave_arguments(parser): # noqa
"""
Additional command line arguments extracted directly from behave
"""
# Option strings that conflict with Django
conflicts = [
'--no-color',
'--version',
'-c',
'-k',
'-v',
'-S',
'--simple',
]
... | def function[add_behave_arguments, parameter[parser]]:
constant[
Additional command line arguments extracted directly from behave
]
variable[conflicts] assign[=] list[[<ast.Constant object at 0x7da1b2344460>, <ast.Constant object at 0x7da1b2346da0>, <ast.Constant object at 0x7da1b2344130>, <ast.... | keyword[def] identifier[add_behave_arguments] ( identifier[parser] ):
literal[string]
identifier[conflicts] =[
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
]
identifier[parser... | def add_behave_arguments(parser): # noqa
'\n Additional command line arguments extracted directly from behave\n '
# Option strings that conflict with Django
conflicts = ['--no-color', '--version', '-c', '-k', '-v', '-S', '--simple']
parser.add_argument('paths', action='store', nargs='*', help='Fe... |
def score(text, *score_functions):
"""Score ``text`` using ``score_functions``.
Examples:
>>> score("abc", function_a)
>>> score("abc", function_a, function_b)
Args:
text (str): The text to score
*score_functions (variable length argument list): functions to score with
... | def function[score, parameter[text]]:
constant[Score ``text`` using ``score_functions``.
Examples:
>>> score("abc", function_a)
>>> score("abc", function_a, function_b)
Args:
text (str): The text to score
*score_functions (variable length argument list): functions to sc... | keyword[def] identifier[score] ( identifier[text] ,* identifier[score_functions] ):
literal[string]
keyword[if] keyword[not] identifier[score_functions] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier[statistics] . identifier[mean] ( identifier[func... | def score(text, *score_functions):
"""Score ``text`` using ``score_functions``.
Examples:
>>> score("abc", function_a)
>>> score("abc", function_a, function_b)
Args:
text (str): The text to score
*score_functions (variable length argument list): functions to score with
... |
def depth_august_average_ground_temperature(self, value=None):
"""Corresponds to IDD Field `depth_august_average_ground_temperature`
Args:
value (float): value for IDD Field `depth_august_average_ground_temperature`
Unit: C
if `value` is None it will not be c... | def function[depth_august_average_ground_temperature, parameter[self, value]]:
constant[Corresponds to IDD Field `depth_august_average_ground_temperature`
Args:
value (float): value for IDD Field `depth_august_average_ground_temperature`
Unit: C
if `value` is... | keyword[def] identifier[depth_august_average_ground_temperature] ( identifier[self] , identifier[value] = keyword[None] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[try] :
identifier[value] = identifier[float] ( ... | def depth_august_average_ground_temperature(self, value=None):
"""Corresponds to IDD Field `depth_august_average_ground_temperature`
Args:
value (float): value for IDD Field `depth_august_average_ground_temperature`
Unit: C
if `value` is None it will not be check... |
def get_available_images(request, project_id=None, images_cache=None):
"""Returns a list of available images
Returns a list of images that are public, shared, community or owned by
the given project_id. If project_id is not specified, only public and
community images are returned.
:param images_ca... | def function[get_available_images, parameter[request, project_id, images_cache]]:
constant[Returns a list of available images
Returns a list of images that are public, shared, community or owned by
the given project_id. If project_id is not specified, only public and
community images are returned.
... | keyword[def] identifier[get_available_images] ( identifier[request] , identifier[project_id] = keyword[None] , identifier[images_cache] = keyword[None] ):
literal[string]
keyword[if] identifier[images_cache] keyword[is] keyword[None] :
identifier[images_cache] ={}
identifier[public_images... | def get_available_images(request, project_id=None, images_cache=None):
"""Returns a list of available images
Returns a list of images that are public, shared, community or owned by
the given project_id. If project_id is not specified, only public and
community images are returned.
:param images_ca... |
def get_version(version):
"""
Returns a PEP 440-compliant version number from VERSION.
Created by modifying django.utils.version.get_version
"""
# Now build the two parts of the version number:
# major = X.Y[.Z]
# sub = .devN - for development releases
# | {a|b|rc}N - for alpha, be... | def function[get_version, parameter[version]]:
constant[
Returns a PEP 440-compliant version number from VERSION.
Created by modifying django.utils.version.get_version
]
assert[compare[call[name[len], parameter[name[version]]] equal[==] constant[5]]]
variable[version_parts] assign[=] <a... | keyword[def] identifier[get_version] ( identifier[version] ):
literal[string]
keyword[assert] identifier[len] ( identifier[version] )== literal[int]
identifier[version_parts] = identifier[version] [: literal[int] ] keyword[if] identifier[version] [ literal[int] ]== liter... | def get_version(version):
"""
Returns a PEP 440-compliant version number from VERSION.
Created by modifying django.utils.version.get_version
"""
# Now build the two parts of the version number:
# major = X.Y[.Z]
# sub = .devN - for development releases
# | {a|b|rc}N - for alpha, bet... |
def mass_mailing_recipients():
"""
Returns iterable of all mass email recipients.
Default behavior will be to return list of all active users' emails.
This can be changed by providing callback in settings return some other list of users,
when user emails are stored in many, non default models.
T... | def function[mass_mailing_recipients, parameter[]]:
constant[
Returns iterable of all mass email recipients.
Default behavior will be to return list of all active users' emails.
This can be changed by providing callback in settings return some other list of users,
when user emails are stored in ... | keyword[def] identifier[mass_mailing_recipients] ():
literal[string]
keyword[if] identifier[hasattr] ( identifier[settings] , literal[string] ):
identifier[callback_name] = identifier[settings] . identifier[MASS_EMAIL_RECIPIENTS] . identifier[split] ( literal[string] )
identifier[module_... | def mass_mailing_recipients():
"""
Returns iterable of all mass email recipients.
Default behavior will be to return list of all active users' emails.
This can be changed by providing callback in settings return some other list of users,
when user emails are stored in many, non default models.
T... |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get("properties", {})
raw_content = properties.get("ipSecConfiguration", None)
if raw_content is not None:
ip_sec = IPSecConfiguration.from_raw_data(raw_content)
... | def function[process_raw_data, parameter[cls, raw_data]]:
constant[Create a new model using raw API response.]
variable[properties] assign[=] call[name[raw_data].get, parameter[constant[properties], dictionary[[], []]]]
variable[raw_content] assign[=] call[name[properties].get, parameter[constan... | keyword[def] identifier[process_raw_data] ( identifier[cls] , identifier[raw_data] ):
literal[string]
identifier[properties] = identifier[raw_data] . identifier[get] ( literal[string] ,{})
identifier[raw_content] = identifier[properties] . identifier[get] ( literal[string] , keyword[None]... | def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data.get('properties', {})
raw_content = properties.get('ipSecConfiguration', None)
if raw_content is not None:
ip_sec = IPSecConfiguration.from_raw_data(raw_content)
properties['ipSecC... |
def _printTaxonomy(self, hrlinetop=True):
"""
print(a local taxonomy for the object)
"""
if not self.currentEntity: # ==> ontology level
return
if hrlinetop:
self._print("----------------")
self._print("TAXONOMY:", "IMPORTANT")
x = self.cu... | def function[_printTaxonomy, parameter[self, hrlinetop]]:
constant[
print(a local taxonomy for the object)
]
if <ast.UnaryOp object at 0x7da1b11aaaa0> begin[:]
return[None]
if name[hrlinetop] begin[:]
call[name[self]._print, parameter[constant[------------... | keyword[def] identifier[_printTaxonomy] ( identifier[self] , identifier[hrlinetop] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[currentEntity] :
keyword[return]
keyword[if] identifier[hrlinetop] :
identifier[self] .... | def _printTaxonomy(self, hrlinetop=True):
"""
print(a local taxonomy for the object)
"""
if not self.currentEntity: # ==> ontology level
return # depends on [control=['if'], data=[]]
if hrlinetop:
self._print('----------------') # depends on [control=['if'], data=[]]
s... |
def get_readout_time(self, child, duration):
"""Calculate the readout time of the detector from the EPICS driver:
- Set exposure and acquire period to same value
- Acquire period will be set to lowest acceptable value
- Difference will be readout time (this value is affected ... | def function[get_readout_time, parameter[self, child, duration]]:
constant[Calculate the readout time of the detector from the EPICS driver:
- Set exposure and acquire period to same value
- Acquire period will be set to lowest acceptable value
- Difference will be readout ti... | keyword[def] identifier[get_readout_time] ( identifier[self] , identifier[child] , identifier[duration] ):
literal[string]
identifier[child] . identifier[exposure] . identifier[put_value] ( identifier[duration] )
identifier[child] . identifier[acquirePeriod] . identifier[put_value] ( ident... | def get_readout_time(self, child, duration):
"""Calculate the readout time of the detector from the EPICS driver:
- Set exposure and acquire period to same value
- Acquire period will be set to lowest acceptable value
- Difference will be readout time (this value is affected by
... |
def write_profile(name, repo, token):
"""Save a profile to the CONFIG_FILE.
After you use this method to save a profile, you can load it anytime
later with the ``read_profile()`` function defined above.
Args:
name
The name of the profile to save.
repo
The Gith... | def function[write_profile, parameter[name, repo, token]]:
constant[Save a profile to the CONFIG_FILE.
After you use this method to save a profile, you can load it anytime
later with the ``read_profile()`` function defined above.
Args:
name
The name of the profile to save.
... | keyword[def] identifier[write_profile] ( identifier[name] , identifier[repo] , identifier[token] ):
literal[string]
identifier[make_sure_folder_exists] ( identifier[CONFIG_FOLDER] )
identifier[config] = identifier[configparser] . identifier[ConfigParser] ()
identifier[config] . identifier[read] (... | def write_profile(name, repo, token):
"""Save a profile to the CONFIG_FILE.
After you use this method to save a profile, you can load it anytime
later with the ``read_profile()`` function defined above.
Args:
name
The name of the profile to save.
repo
The Gith... |
def write(self, path, wrap_ttl=None, **kwargs):
"""POST /<path>
:param path:
:type path:
:param wrap_ttl:
:type wrap_ttl:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
response = self._adapter.post('/v1/{0}'.format(path), json=... | def function[write, parameter[self, path, wrap_ttl]]:
constant[POST /<path>
:param path:
:type path:
:param wrap_ttl:
:type wrap_ttl:
:param kwargs:
:type kwargs:
:return:
:rtype:
]
variable[response] assign[=] call[name[self]._ada... | keyword[def] identifier[write] ( identifier[self] , identifier[path] , identifier[wrap_ttl] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[response] = identifier[self] . identifier[_adapter] . identifier[post] ( literal[string] . identifier[format] ( identifier[path] ), identi... | def write(self, path, wrap_ttl=None, **kwargs):
"""POST /<path>
:param path:
:type path:
:param wrap_ttl:
:type wrap_ttl:
:param kwargs:
:type kwargs:
:return:
:rtype:
"""
response = self._adapter.post('/v1/{0}'.format(path), json=kwargs, ... |
def rtruncated_pareto(alpha, m, b, size=None):
"""
Random bounded Pareto variates.
"""
u = random_number(size)
return (-(u * b ** alpha - u * m ** alpha - b ** alpha) /
(b ** alpha * m ** alpha)) ** (-1. / alpha) | def function[rtruncated_pareto, parameter[alpha, m, b, size]]:
constant[
Random bounded Pareto variates.
]
variable[u] assign[=] call[name[random_number], parameter[name[size]]]
return[binary_operation[binary_operation[<ast.UnaryOp object at 0x7da20e957700> / binary_operation[binary_operatio... | keyword[def] identifier[rtruncated_pareto] ( identifier[alpha] , identifier[m] , identifier[b] , identifier[size] = keyword[None] ):
literal[string]
identifier[u] = identifier[random_number] ( identifier[size] )
keyword[return] (-( identifier[u] * identifier[b] ** identifier[alpha] - identifier[u] * i... | def rtruncated_pareto(alpha, m, b, size=None):
"""
Random bounded Pareto variates.
"""
u = random_number(size)
return (-(u * b ** alpha - u * m ** alpha - b ** alpha) / (b ** alpha * m ** alpha)) ** (-1.0 / alpha) |
def contains_field_list(self, path, name):
"""
Returns True if a multi-valued field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
... | def function[contains_field_list, parameter[self, path, name]]:
constant[
Returns True if a multi-valued field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component o... | keyword[def] identifier[contains_field_list] ( identifier[self] , identifier[path] , identifier[name] ):
literal[string]
keyword[try] :
identifier[self] . identifier[get_field_list] ( identifier[path] , identifier[name] )
keyword[return] keyword[True]
keyword[ex... | def contains_field_list(self, path, name):
"""
Returns True if a multi-valued field exists at the specified path, otherwise False.
:param path: str or Path instance
:param name:
:type name: str
:return:
:raises ValueError: A component of path is a field name.
... |
def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
... | def function[circular, parameter[cls, shape, pixel_scale, radius_arcsec, centre, invert]]:
constant[Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units o... | keyword[def] identifier[circular] ( identifier[cls] , identifier[shape] , identifier[pixel_scale] , identifier[radius_arcsec] , identifier[centre] =( literal[int] , literal[int] ), identifier[invert] = keyword[False] ):
literal[string]
identifier[mask] = identifier[mask_util] . identifier[mask_circ... | def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0.0, 0.0), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
... |
def process_iq(self, stanza):
"""Process IQ stanza received.
:Parameters:
- `stanza`: the stanza received
:Types:
- `stanza`: `Iq`
If a matching handler is available pass the stanza to it. Otherwise
ignore it if it is "error" or "result" stanza or retur... | def function[process_iq, parameter[self, stanza]]:
constant[Process IQ stanza received.
:Parameters:
- `stanza`: the stanza received
:Types:
- `stanza`: `Iq`
If a matching handler is available pass the stanza to it. Otherwise
ignore it if it is "error" ... | keyword[def] identifier[process_iq] ( identifier[self] , identifier[stanza] ):
literal[string]
identifier[typ] = identifier[stanza] . identifier[stanza_type]
keyword[if] identifier[typ] keyword[in] ( literal[string] , literal[string] ):
keyword[return] identifier[self] . ... | def process_iq(self, stanza):
"""Process IQ stanza received.
:Parameters:
- `stanza`: the stanza received
:Types:
- `stanza`: `Iq`
If a matching handler is available pass the stanza to it. Otherwise
ignore it if it is "error" or "result" stanza or return
... |
def subscribe(self, callback_url, timeout=None):
"""
Set up a subscription to the events offered by this service.
"""
url = urljoin(self._url_base, self._event_sub_url)
headers = dict(
HOST=urlparse(url).netloc,
CALLBACK='<%s>' % callback_url,
... | def function[subscribe, parameter[self, callback_url, timeout]]:
constant[
Set up a subscription to the events offered by this service.
]
variable[url] assign[=] call[name[urljoin], parameter[name[self]._url_base, name[self]._event_sub_url]]
variable[headers] assign[=] call[name[... | keyword[def] identifier[subscribe] ( identifier[self] , identifier[callback_url] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[url] = identifier[urljoin] ( identifier[self] . identifier[_url_base] , identifier[self] . identifier[_event_sub_url] )
identifier[headers] =... | def subscribe(self, callback_url, timeout=None):
"""
Set up a subscription to the events offered by this service.
"""
url = urljoin(self._url_base, self._event_sub_url)
headers = dict(HOST=urlparse(url).netloc, CALLBACK='<%s>' % callback_url, NT='upnp:event')
if timeout is not None:
... |
def fill_subparser(subparser):
"""Sets up a subparser to download the MNIST dataset files.
The following MNIST dataset files are downloaded from Yann LeCun's
website [LECUN]:
`train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`,
`t10k-images-idx3-ubyte.gz`, `t10k-labels-idx1-ubyte.gz`.
P... | def function[fill_subparser, parameter[subparser]]:
constant[Sets up a subparser to download the MNIST dataset files.
The following MNIST dataset files are downloaded from Yann LeCun's
website [LECUN]:
`train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`,
`t10k-images-idx3-ubyte.gz`, `t10... | keyword[def] identifier[fill_subparser] ( identifier[subparser] ):
literal[string]
identifier[filenames] =[ literal[string] , literal[string] ,
literal[string] , literal[string] ]
identifier[urls] =[ literal[string] + identifier[f] keyword[for] identifier[f] keyword[in] identifier[filenames] ... | def fill_subparser(subparser):
"""Sets up a subparser to download the MNIST dataset files.
The following MNIST dataset files are downloaded from Yann LeCun's
website [LECUN]:
`train-images-idx3-ubyte.gz`, `train-labels-idx1-ubyte.gz`,
`t10k-images-idx3-ubyte.gz`, `t10k-labels-idx1-ubyte.gz`.
P... |
def handle_packets(pk):
"""handle_packets
:param pk: data packet that kamene sends in
"""
log.info(("processing with pub={}")
.format(pub))
# get the lowest layer
eth = pk.getlayer(kamene.Ether)
should_forward = False
send_msg = {"data": {},
"created": rn... | def function[handle_packets, parameter[pk]]:
constant[handle_packets
:param pk: data packet that kamene sends in
]
call[name[log].info, parameter[call[constant[processing with pub={}].format, parameter[name[pub]]]]]
variable[eth] assign[=] call[name[pk].getlayer, parameter[name[kamene].... | keyword[def] identifier[handle_packets] ( identifier[pk] ):
literal[string]
identifier[log] . identifier[info] (( literal[string] )
. identifier[format] ( identifier[pub] ))
identifier[eth] = identifier[pk] . identifier[getlayer] ( identifier[kamene] . identifier[Ether] )
identifier[s... | def handle_packets(pk):
"""handle_packets
:param pk: data packet that kamene sends in
"""
log.info('processing with pub={}'.format(pub))
# get the lowest layer
eth = pk.getlayer(kamene.Ether)
should_forward = False
send_msg = {'data': {}, 'created': rnow(), 'source': SOURCE}
if eth:... |
def authenticate(remote_addr, password, cert, key, verify_cert=True):
'''
Authenticate with a remote LXDaemon.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr and its a TCP Address!
Examples:
https://myserver.lan:84... | def function[authenticate, parameter[remote_addr, password, cert, key, verify_cert]]:
constant[
Authenticate with a remote LXDaemon.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr and its a TCP Address!
Examples:
... | keyword[def] identifier[authenticate] ( identifier[remote_addr] , identifier[password] , identifier[cert] , identifier[key] , identifier[verify_cert] = keyword[True] ):
literal[string]
identifier[client] = identifier[pylxd_client_get] ( identifier[remote_addr] , identifier[cert] , identifier[key] , identif... | def authenticate(remote_addr, password, cert, key, verify_cert=True):
"""
Authenticate with a remote LXDaemon.
remote_addr :
An URL to a remote Server, you also have to give cert and key if you
provide remote_addr and its a TCP Address!
Examples:
https://myserver.lan:84... |
def zipWithIndex(self):
"""
Zips this RDD with its element indices.
The ordering is first based on the partition index and then the
ordering of items within each partition. So the first item in
the first partition gets index 0, and the last item in the last
partition rec... | def function[zipWithIndex, parameter[self]]:
constant[
Zips this RDD with its element indices.
The ordering is first based on the partition index and then the
ordering of items within each partition. So the first item in
the first partition gets index 0, and the last item in the... | keyword[def] identifier[zipWithIndex] ( identifier[self] ):
literal[string]
identifier[starts] =[ literal[int] ]
keyword[if] identifier[self] . identifier[getNumPartitions] ()> literal[int] :
identifier[nums] = identifier[self] . identifier[mapPartitions] ( keyword[lambda] i... | def zipWithIndex(self):
"""
Zips this RDD with its element indices.
The ordering is first based on the partition index and then the
ordering of items within each partition. So the first item in
the first partition gets index 0, and the last item in the last
partition receive... |
def _get_max_sigma(self, R):
"""Calculate maximum sigma of scanner RAS coordinates
Parameters
----------
R : 2D array, with shape [n_voxel, n_dim]
The coordinate matrix of fMRI data from one subject
Returns
-------
max_sigma : float
The... | def function[_get_max_sigma, parameter[self, R]]:
constant[Calculate maximum sigma of scanner RAS coordinates
Parameters
----------
R : 2D array, with shape [n_voxel, n_dim]
The coordinate matrix of fMRI data from one subject
Returns
-------
max_si... | keyword[def] identifier[_get_max_sigma] ( identifier[self] , identifier[R] ):
literal[string]
identifier[max_sigma] = literal[int] * identifier[math] . identifier[pow] ( identifier[np] . identifier[nanmax] ( identifier[np] . identifier[std] ( identifier[R] , identifier[axis] = literal[int] )), lit... | def _get_max_sigma(self, R):
"""Calculate maximum sigma of scanner RAS coordinates
Parameters
----------
R : 2D array, with shape [n_voxel, n_dim]
The coordinate matrix of fMRI data from one subject
Returns
-------
max_sigma : float
The max... |
def create_security_group(self, name, description, vpc_id=None):
"""
Create a new security group for your account.
This will create the security group within the region you
are currently connected to.
:type name: string
:param name: The name of the new security group
... | def function[create_security_group, parameter[self, name, description, vpc_id]]:
constant[
Create a new security group for your account.
This will create the security group within the region you
are currently connected to.
:type name: string
:param name: The name of the ... | keyword[def] identifier[create_security_group] ( identifier[self] , identifier[name] , identifier[description] , identifier[vpc_id] = keyword[None] ):
literal[string]
identifier[params] ={
literal[string] : identifier[name] ,
literal[string] : identifier[description]
}
... | def create_security_group(self, name, description, vpc_id=None):
"""
Create a new security group for your account.
This will create the security group within the region you
are currently connected to.
:type name: string
:param name: The name of the new security group
... |
def context(self, name, ctx):
"""
Execute the block with the given context applied. This manager
ensures that the context is removed even if an exception is raised
within the context.
"""
self.enter_context(name, ctx)
try:
yield
finally:
... | def function[context, parameter[self, name, ctx]]:
constant[
Execute the block with the given context applied. This manager
ensures that the context is removed even if an exception is raised
within the context.
]
call[name[self].enter_context, parameter[name[name], name[... | keyword[def] identifier[context] ( identifier[self] , identifier[name] , identifier[ctx] ):
literal[string]
identifier[self] . identifier[enter_context] ( identifier[name] , identifier[ctx] )
keyword[try] :
keyword[yield]
keyword[finally] :
identifier[se... | def context(self, name, ctx):
"""
Execute the block with the given context applied. This manager
ensures that the context is removed even if an exception is raised
within the context.
"""
self.enter_context(name, ctx)
try:
yield # depends on [control=['try'], data=[... |
def _tokens_from_patsy(node):
"""
Yields all the individual tokens from within a patsy formula
as parsed by patsy.parse_formula.parse_formula.
Parameters
----------
node : patsy.parse_formula.ParseNode
"""
for n in node.args:
for t in _tokens_from_patsy(n):
yield t
... | def function[_tokens_from_patsy, parameter[node]]:
constant[
Yields all the individual tokens from within a patsy formula
as parsed by patsy.parse_formula.parse_formula.
Parameters
----------
node : patsy.parse_formula.ParseNode
]
for taget[name[n]] in starred[name[node].args] ... | keyword[def] identifier[_tokens_from_patsy] ( identifier[node] ):
literal[string]
keyword[for] identifier[n] keyword[in] identifier[node] . identifier[args] :
keyword[for] identifier[t] keyword[in] identifier[_tokens_from_patsy] ( identifier[n] ):
keyword[yield] identifier[t]
... | def _tokens_from_patsy(node):
"""
Yields all the individual tokens from within a patsy formula
as parsed by patsy.parse_formula.parse_formula.
Parameters
----------
node : patsy.parse_formula.ParseNode
"""
for n in node.args:
for t in _tokens_from_patsy(n):
yield t ... |
def subscribeContext(self, objectID, domain, dist, varIDs=(
tc.VAR_ROAD_ID, tc.VAR_LANEPOSITION), begin=0, end=2**31 - 1):
"""subscribe(string, int, double, list(integer), int, int) -> None
Subscribe to one or more object values of the given domain around the
given objectID in a giv... | def function[subscribeContext, parameter[self, objectID, domain, dist, varIDs, begin, end]]:
constant[subscribe(string, int, double, list(integer), int, int) -> None
Subscribe to one or more object values of the given domain around the
given objectID in a given radius
]
call[nam... | keyword[def] identifier[subscribeContext] ( identifier[self] , identifier[objectID] , identifier[domain] , identifier[dist] , identifier[varIDs] =(
identifier[tc] . identifier[VAR_ROAD_ID] , identifier[tc] . identifier[VAR_LANEPOSITION] ), identifier[begin] = literal[int] , identifier[end] = literal[int] ** literal[... | def subscribeContext(self, objectID, domain, dist, varIDs=(tc.VAR_ROAD_ID, tc.VAR_LANEPOSITION), begin=0, end=2 ** 31 - 1):
"""subscribe(string, int, double, list(integer), int, int) -> None
Subscribe to one or more object values of the given domain around the
given objectID in a given radius
... |
def getDPI(filepath):
"""
Return (width, height) for a given img file content
no requirements
"""
xDPI = -1
yDPI = -1
with open(filepath, 'rb') as fhandle:
head = fhandle.read(24)
size = len(head)
# handle GIFs
# GIFs doesn't have density
if size >= 10... | def function[getDPI, parameter[filepath]]:
constant[
Return (width, height) for a given img file content
no requirements
]
variable[xDPI] assign[=] <ast.UnaryOp object at 0x7da1b0ebf2b0>
variable[yDPI] assign[=] <ast.UnaryOp object at 0x7da1b0ebdf30>
with call[name[open], par... | keyword[def] identifier[getDPI] ( identifier[filepath] ):
literal[string]
identifier[xDPI] =- literal[int]
identifier[yDPI] =- literal[int]
keyword[with] identifier[open] ( identifier[filepath] , literal[string] ) keyword[as] identifier[fhandle] :
identifier[head] = identifier[fhandl... | def getDPI(filepath):
"""
Return (width, height) for a given img file content
no requirements
"""
xDPI = -1
yDPI = -1
with open(filepath, 'rb') as fhandle:
head = fhandle.read(24)
size = len(head)
# handle GIFs
# GIFs doesn't have density
if size >= 10... |
def rollforward(self, date):
"""Roll date forward to nearest start of quarter"""
if self.onOffset(date):
return date
else:
return date + QuarterBegin(month=self.month) | def function[rollforward, parameter[self, date]]:
constant[Roll date forward to nearest start of quarter]
if call[name[self].onOffset, parameter[name[date]]] begin[:]
return[name[date]] | keyword[def] identifier[rollforward] ( identifier[self] , identifier[date] ):
literal[string]
keyword[if] identifier[self] . identifier[onOffset] ( identifier[date] ):
keyword[return] identifier[date]
keyword[else] :
keyword[return] identifier[date] + identifi... | def rollforward(self, date):
"""Roll date forward to nearest start of quarter"""
if self.onOffset(date):
return date # depends on [control=['if'], data=[]]
else:
return date + QuarterBegin(month=self.month) |
def do_gc(self, args):
"""gc - print out garbage collection information"""
### humm...
instance_type = getattr(types, 'InstanceType', object)
# snapshot of counts
type2count = {}
type2all = {}
for o in gc.get_objects():
if type(o) == instance_type:
... | def function[do_gc, parameter[self, args]]:
constant[gc - print out garbage collection information]
variable[instance_type] assign[=] call[name[getattr], parameter[name[types], constant[InstanceType], name[object]]]
variable[type2count] assign[=] dictionary[[], []]
variable[type2all] ass... | keyword[def] identifier[do_gc] ( identifier[self] , identifier[args] ):
literal[string]
identifier[instance_type] = identifier[getattr] ( identifier[types] , literal[string] , identifier[object] )
identifier[type2count] ={}
identifier[type2all] ={}
key... | def do_gc(self, args):
"""gc - print out garbage collection information"""
### humm...
instance_type = getattr(types, 'InstanceType', object)
# snapshot of counts
type2count = {}
type2all = {}
for o in gc.get_objects():
if type(o) == instance_type:
type2count[o.__class__]... |
def _generate_create_dict(self,
size=None,
hostname=None,
domain=None,
location=None,
os=None,
port_speed=None,
... | def function[_generate_create_dict, parameter[self, size, hostname, domain, location, os, port_speed, ssh_keys, post_uri, hourly, no_public, extras]]:
constant[Translates arguments into a dictionary for creating a server.]
variable[extras] assign[=] <ast.BoolOp object at 0x7da18bcca3e0>
variable... | keyword[def] identifier[_generate_create_dict] ( identifier[self] ,
identifier[size] = keyword[None] ,
identifier[hostname] = keyword[None] ,
identifier[domain] = keyword[None] ,
identifier[location] = keyword[None] ,
identifier[os] = keyword[None] ,
identifier[port_speed] = keyword[None] ,
identifier[ssh_keys... | def _generate_create_dict(self, size=None, hostname=None, domain=None, location=None, os=None, port_speed=None, ssh_keys=None, post_uri=None, hourly=True, no_public=False, extras=None):
"""Translates arguments into a dictionary for creating a server."""
extras = extras or []
package = self._get_package()
... |
def distinfo_dirname(cls, name, version):
"""
The *name* and *version* parameters are converted into their
filename-escaped form, i.e. any ``'-'`` characters are replaced
with ``'_'`` other than the one in ``'dist-info'`` and the one
separating the name from the version number.
... | def function[distinfo_dirname, parameter[cls, name, version]]:
constant[
The *name* and *version* parameters are converted into their
filename-escaped form, i.e. any ``'-'`` characters are replaced
with ``'_'`` other than the one in ``'dist-info'`` and the one
separating the name... | keyword[def] identifier[distinfo_dirname] ( identifier[cls] , identifier[name] , identifier[version] ):
literal[string]
identifier[name] = identifier[name] . identifier[replace] ( literal[string] , literal[string] )
keyword[return] literal[string] . identifier[join] ([ identifier[name] , ... | def distinfo_dirname(cls, name, version):
"""
The *name* and *version* parameters are converted into their
filename-escaped form, i.e. any ``'-'`` characters are replaced
with ``'_'`` other than the one in ``'dist-info'`` and the one
separating the name from the version number.
... |
def return_params(islitlet, csu_bar_slit_center, params, parmodel):
"""Return individual model parameters from object of type Parameters.
Parameters
----------
islitlet : int
Number of slitlet.
csu_bar_slit_center : float
CSU bar slit center, in mm.
params : :class:`~lmfit.param... | def function[return_params, parameter[islitlet, csu_bar_slit_center, params, parmodel]]:
constant[Return individual model parameters from object of type Parameters.
Parameters
----------
islitlet : int
Number of slitlet.
csu_bar_slit_center : float
CSU bar slit center, in mm.
... | keyword[def] identifier[return_params] ( identifier[islitlet] , identifier[csu_bar_slit_center] , identifier[params] , identifier[parmodel] ):
literal[string]
keyword[if] identifier[parmodel] == literal[string] :
identifier[c2] = identifier[params] [ literal[string] ]. identifier[value... | def return_params(islitlet, csu_bar_slit_center, params, parmodel):
"""Return individual model parameters from object of type Parameters.
Parameters
----------
islitlet : int
Number of slitlet.
csu_bar_slit_center : float
CSU bar slit center, in mm.
params : :class:`~lmfit.param... |
def process_parsed_args(opts: Namespace, error_fun: Optional[Callable], connect: bool=True) -> Namespace:
"""
Set the defaults for the crc and ontology schemas
:param opts: parsed arguments
:param error_fun: Function to call if error
:param connect: actually connect. (For debugging)
:return: nam... | def function[process_parsed_args, parameter[opts, error_fun, connect]]:
constant[
Set the defaults for the crc and ontology schemas
:param opts: parsed arguments
:param error_fun: Function to call if error
:param connect: actually connect. (For debugging)
:return: namespace with additional e... | keyword[def] identifier[process_parsed_args] ( identifier[opts] : identifier[Namespace] , identifier[error_fun] : identifier[Optional] [ identifier[Callable] ], identifier[connect] : identifier[bool] = keyword[True] )-> identifier[Namespace] :
literal[string]
keyword[def] identifier[setdefault] ( identifi... | def process_parsed_args(opts: Namespace, error_fun: Optional[Callable], connect: bool=True) -> Namespace:
"""
Set the defaults for the crc and ontology schemas
:param opts: parsed arguments
:param error_fun: Function to call if error
:param connect: actually connect. (For debugging)
:return: nam... |
def register(name=''):
"For backwards compatibility, we support @register(name) syntax."
def reg(widget):
"""A decorator registering a widget class in the widget registry."""
w = widget.class_traits()
Widget.widget_types.register(w['_model_module'].default_value,
... | def function[register, parameter[name]]:
constant[For backwards compatibility, we support @register(name) syntax.]
def function[reg, parameter[widget]]:
constant[A decorator registering a widget class in the widget registry.]
variable[w] assign[=] call[name[widget].class_... | keyword[def] identifier[register] ( identifier[name] = literal[string] ):
literal[string]
keyword[def] identifier[reg] ( identifier[widget] ):
literal[string]
identifier[w] = identifier[widget] . identifier[class_traits] ()
identifier[Widget] . identifier[widget_types] . identi... | def register(name=''):
"""For backwards compatibility, we support @register(name) syntax."""
def reg(widget):
"""A decorator registering a widget class in the widget registry."""
w = widget.class_traits()
Widget.widget_types.register(w['_model_module'].default_value, w['_model_module_ve... |
def close(self):
'''close the graph'''
self.close_graph.set()
if self.is_alive():
self.child.join(2) | def function[close, parameter[self]]:
constant[close the graph]
call[name[self].close_graph.set, parameter[]]
if call[name[self].is_alive, parameter[]] begin[:]
call[name[self].child.join, parameter[constant[2]]] | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[close_graph] . identifier[set] ()
keyword[if] identifier[self] . identifier[is_alive] ():
identifier[self] . identifier[child] . identifier[join] ( literal[int] ) | def close(self):
"""close the graph"""
self.close_graph.set()
if self.is_alive():
self.child.join(2) # depends on [control=['if'], data=[]] |
def modularity_und_sign(W, ci, qtype='sta'):
'''
This function simply calculates the signed modularity for a given
partition. It does not do automatic partition generation right now.
Parameters
----------
W : NxN np.ndarray
undirected weighted/binary connection matrix with positive and
... | def function[modularity_und_sign, parameter[W, ci, qtype]]:
constant[
This function simply calculates the signed modularity for a given
partition. It does not do automatic partition generation right now.
Parameters
----------
W : NxN np.ndarray
undirected weighted/binary connection ... | keyword[def] identifier[modularity_und_sign] ( identifier[W] , identifier[ci] , identifier[qtype] = literal[string] ):
literal[string]
identifier[n] = identifier[len] ( identifier[W] )
identifier[_] , identifier[ci] = identifier[np] . identifier[unique] ( identifier[ci] , identifier[return_inverse] = ... | def modularity_und_sign(W, ci, qtype='sta'):
"""
This function simply calculates the signed modularity for a given
partition. It does not do automatic partition generation right now.
Parameters
----------
W : NxN np.ndarray
undirected weighted/binary connection matrix with positive and
... |
def get_xyz(self, xyz_axis=0):
"""Return a vector array of the x, y, and z coordinates.
Parameters
----------
xyz_axis : int, optional
The axis in the final array along which the x, y, z components
should be stored (default: 0).
Returns
-------
... | def function[get_xyz, parameter[self, xyz_axis]]:
constant[Return a vector array of the x, y, and z coordinates.
Parameters
----------
xyz_axis : int, optional
The axis in the final array along which the x, y, z components
should be stored (default: 0).
... | keyword[def] identifier[get_xyz] ( identifier[self] , identifier[xyz_axis] = literal[int] ):
literal[string]
identifier[result_ndim] = identifier[self] . identifier[ndim] + literal[int]
keyword[if] keyword[not] - identifier[result_ndim] <= identifier[xyz_axis] < identif... | def get_xyz(self, xyz_axis=0):
"""Return a vector array of the x, y, and z coordinates.
Parameters
----------
xyz_axis : int, optional
The axis in the final array along which the x, y, z components
should be stored (default: 0).
Returns
-------
... |
def Jz(self,**kwargs):
"""
NAME:
Jz
PURPOSE:
Calculate the vertical action
INPUT:
+scipy.integrate.quad keywords
OUTPUT:
J_z(z,vz)/ro/vc + estimate of the error
HISTORY:
2012-06-01 - Written - Bovy (IAS)
"""
... | def function[Jz, parameter[self]]:
constant[
NAME:
Jz
PURPOSE:
Calculate the vertical action
INPUT:
+scipy.integrate.quad keywords
OUTPUT:
J_z(z,vz)/ro/vc + estimate of the error
HISTORY:
2012-06-01 - Written - Bovy (... | keyword[def] identifier[Jz] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[return] identifier[self] . identifier[_Jz]
identifier[zmax] = identifier[self] . identifier[calczmax] ()
... | def Jz(self, **kwargs):
"""
NAME:
Jz
PURPOSE:
Calculate the vertical action
INPUT:
+scipy.integrate.quad keywords
OUTPUT:
J_z(z,vz)/ro/vc + estimate of the error
HISTORY:
2012-06-01 - Written - Bovy (IAS)
"""
... |
def setCurrentRule( self, rule ):
"""
Sets the current query rule for this widget, updating its widget \
editor if the types do not match.
:param rule | <QueryRule> || None
"""
curr_rule = self.currentRule()
if ( curr_rule == rule ):
retu... | def function[setCurrentRule, parameter[self, rule]]:
constant[
Sets the current query rule for this widget, updating its widget editor if the types do not match.
:param rule | <QueryRule> || None
]
variable[curr_rule] assign[=] call[name[self].currentRule, p... | keyword[def] identifier[setCurrentRule] ( identifier[self] , identifier[rule] ):
literal[string]
identifier[curr_rule] = identifier[self] . identifier[currentRule] ()
keyword[if] ( identifier[curr_rule] == identifier[rule] ):
keyword[return]
identifier[self] . ident... | def setCurrentRule(self, rule):
"""
Sets the current query rule for this widget, updating its widget editor if the types do not match.
:param rule | <QueryRule> || None
"""
curr_rule = self.currentRule()
if curr_rule == rule:
return # depends on [contro... |
def _from_dict(cls, _dict):
"""Initialize a SemanticRolesResultObject object from a json dictionary."""
args = {}
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'keywords' in _dict:
args['keywords'] = [
SemanticRolesKeyword._from_dict(x)
... | def function[_from_dict, parameter[cls, _dict]]:
constant[Initialize a SemanticRolesResultObject object from a json dictionary.]
variable[args] assign[=] dictionary[[], []]
if compare[constant[text] in name[_dict]] begin[:]
call[name[args]][constant[text]] assign[=] call[name[_di... | keyword[def] identifier[_from_dict] ( identifier[cls] , identifier[_dict] ):
literal[string]
identifier[args] ={}
keyword[if] literal[string] keyword[in] identifier[_dict] :
identifier[args] [ literal[string] ]= identifier[_dict] . identifier[get] ( literal[string] )
... | def _from_dict(cls, _dict):
"""Initialize a SemanticRolesResultObject object from a json dictionary."""
args = {}
if 'text' in _dict:
args['text'] = _dict.get('text') # depends on [control=['if'], data=['_dict']]
if 'keywords' in _dict:
args['keywords'] = [SemanticRolesKeyword._from_dic... |
def gravitational_force(position_a, mass_a, position_b, mass_b):
"""Returns the gravitational force between the two bodies a and b."""
distance = distance_between(position_a, position_b)
# Calculate the direction and magnitude of the force.
angle = math.atan2(position_a[1] - position_b[1], position_a[0... | def function[gravitational_force, parameter[position_a, mass_a, position_b, mass_b]]:
constant[Returns the gravitational force between the two bodies a and b.]
variable[distance] assign[=] call[name[distance_between], parameter[name[position_a], name[position_b]]]
variable[angle] assign[=] call[... | keyword[def] identifier[gravitational_force] ( identifier[position_a] , identifier[mass_a] , identifier[position_b] , identifier[mass_b] ):
literal[string]
identifier[distance] = identifier[distance_between] ( identifier[position_a] , identifier[position_b] )
identifier[angle] = identifier[math]... | def gravitational_force(position_a, mass_a, position_b, mass_b):
"""Returns the gravitational force between the two bodies a and b."""
distance = distance_between(position_a, position_b)
# Calculate the direction and magnitude of the force.
angle = math.atan2(position_a[1] - position_b[1], position_a[0]... |
def inline_css(self, html):
"""Inlines CSS defined in external style sheets.
"""
premailer = Premailer(html)
inlined_html = premailer.transform(pretty_print=True)
return inlined_html | def function[inline_css, parameter[self, html]]:
constant[Inlines CSS defined in external style sheets.
]
variable[premailer] assign[=] call[name[Premailer], parameter[name[html]]]
variable[inlined_html] assign[=] call[name[premailer].transform, parameter[]]
return[name[inlined_html]... | keyword[def] identifier[inline_css] ( identifier[self] , identifier[html] ):
literal[string]
identifier[premailer] = identifier[Premailer] ( identifier[html] )
identifier[inlined_html] = identifier[premailer] . identifier[transform] ( identifier[pretty_print] = keyword[True] )
key... | def inline_css(self, html):
"""Inlines CSS defined in external style sheets.
"""
premailer = Premailer(html)
inlined_html = premailer.transform(pretty_print=True)
return inlined_html |
def approximate_eig(self, epsilon=1e-6):
""" Compute low-rank approximation of the eigenvalue decomposition of target matrix.
If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive.
Parameters
----------
epsilon : float, o... | def function[approximate_eig, parameter[self, epsilon]]:
constant[ Compute low-rank approximation of the eigenvalue decomposition of target matrix.
If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive.
Parameters
----------
... | keyword[def] identifier[approximate_eig] ( identifier[self] , identifier[epsilon] = literal[int] ):
literal[string]
identifier[L] = identifier[self] . identifier[approximate_cholesky] ( identifier[epsilon] = identifier[epsilon] )
identifier[LL] = identifier[np] . identifier[dot] ( identifi... | def approximate_eig(self, epsilon=1e-06):
""" Compute low-rank approximation of the eigenvalue decomposition of target matrix.
If spd is True, the decomposition will be conducted while ensuring that the spectrum of `A_k^{-1}` is positive.
Parameters
----------
epsilon : float, opti... |
def create_unused_courses_report(self, account_id, term_id=None):
"""
Convenience method for create_report, for creating an unused courses
report.
"""
return self.create_report(ReportType.UNUSED_COURSES, account_id,
term_id) | def function[create_unused_courses_report, parameter[self, account_id, term_id]]:
constant[
Convenience method for create_report, for creating an unused courses
report.
]
return[call[name[self].create_report, parameter[name[ReportType].UNUSED_COURSES, name[account_id], name[term_id]]... | keyword[def] identifier[create_unused_courses_report] ( identifier[self] , identifier[account_id] , identifier[term_id] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[create_report] ( identifier[ReportType] . identifier[UNUSED_COURSES] , identifier[account_id] ,
... | def create_unused_courses_report(self, account_id, term_id=None):
"""
Convenience method for create_report, for creating an unused courses
report.
"""
return self.create_report(ReportType.UNUSED_COURSES, account_id, term_id) |
def mapConcat(func, *iterables):
"""Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
>>> mapConcat(la... | def function[mapConcat, parameter[func]]:
constant[Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
... | keyword[def] identifier[mapConcat] ( identifier[func] ,* identifier[iterables] ):
literal[string]
keyword[return] [ identifier[e] keyword[for] identifier[l] keyword[in] identifier[imap] ( identifier[func] ,* identifier[iterables] ) keyword[for] identifier[e] keyword[in] identifier[l] ] | def mapConcat(func, *iterables):
"""Similar to `map` but the instead of collecting the return values of
`func` in a list, the items of each return value are instaed collected
(so `func` must return an iterable type).
Examples:
>>> mapConcat(lambda x:[x], [1,2,3])
[1, 2, 3]
>>> mapConcat(la... |
def render(self, **kwargs):
"""Render the GeoJson/TopoJson and color scale objects."""
if self.color_scale:
# ColorMap needs Map as its parent
assert isinstance(self._parent, Map), ('Choropleth must be added'
' to a Map object.')... | def function[render, parameter[self]]:
constant[Render the GeoJson/TopoJson and color scale objects.]
if name[self].color_scale begin[:]
assert[call[name[isinstance], parameter[name[self]._parent, name[Map]]]]
name[self].color_scale._parent assign[=] name[self]._parent
ca... | keyword[def] identifier[render] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[color_scale] :
keyword[assert] identifier[isinstance] ( identifier[self] . identifier[_parent] , identifier[Map] ),( literal[string]
... | def render(self, **kwargs):
"""Render the GeoJson/TopoJson and color scale objects."""
if self.color_scale:
# ColorMap needs Map as its parent
assert isinstance(self._parent, Map), 'Choropleth must be added to a Map object.'
self.color_scale._parent = self._parent # depends on [control=... |
def with_target_audience(self, target_audience):
"""Create a copy of these credentials with the specified target
audience.
Args:
target_audience (str): The intended audience for these credentials,
used when requesting the ID Token.
Returns:
google.au... | def function[with_target_audience, parameter[self, target_audience]]:
constant[Create a copy of these credentials with the specified target
audience.
Args:
target_audience (str): The intended audience for these credentials,
used when requesting the ID Token.
Ret... | keyword[def] identifier[with_target_audience] ( identifier[self] , identifier[target_audience] ):
literal[string]
keyword[return] identifier[self] . identifier[__class__] (
identifier[self] . identifier[_signer] ,
identifier[service_account_email] = identifier[self] . identifier[... | def with_target_audience(self, target_audience):
"""Create a copy of these credentials with the specified target
audience.
Args:
target_audience (str): The intended audience for these credentials,
used when requesting the ID Token.
Returns:
google.auth.s... |
def to_file_object(self, name, out_dir):
"""Dump to a pickle file and return an File object reference of this list
Parameters
----------
name : str
An identifier of this file. Needs to be unique.
out_dir : path
path to place this file
Returns
... | def function[to_file_object, parameter[self, name, out_dir]]:
constant[Dump to a pickle file and return an File object reference of this list
Parameters
----------
name : str
An identifier of this file. Needs to be unique.
out_dir : path
path to place thi... | keyword[def] identifier[to_file_object] ( identifier[self] , identifier[name] , identifier[out_dir] ):
literal[string]
identifier[make_analysis_dir] ( identifier[out_dir] )
identifier[file_ref] = identifier[File] ( literal[string] , identifier[name] , identifier[self] . identifier[get_tim... | def to_file_object(self, name, out_dir):
"""Dump to a pickle file and return an File object reference of this list
Parameters
----------
name : str
An identifier of this file. Needs to be unique.
out_dir : path
path to place this file
Returns
... |
def run():
"""Run the examples"""
# NOTE(kiennt): Until now, this example isn't finished yet,
# because we don't have any completed driver
# Get a network client with openstack driver.
network_client = client.Client(version=_VERSION,
resource=_RESOURCES[0], p... | def function[run, parameter[]]:
constant[Run the examples]
variable[network_client] assign[=] call[name[client].Client, parameter[]]
call[name[network_client].delete, parameter[constant[4b983028-0f8c-4b63-b10c-6e8420bb7903]]] | keyword[def] identifier[run] ():
literal[string]
identifier[network_client] = identifier[client] . identifier[Client] ( identifier[version] = identifier[_VERSION] ,
identifier[resource] = identifier[_RESOURCES] [ literal[int] ], identifier[provider] = identifier[_PROVIDER] )
... | def run():
"""Run the examples"""
# NOTE(kiennt): Until now, this example isn't finished yet,
# because we don't have any completed driver
# Get a network client with openstack driver.
network_client = client.Client(version=_VERSION, resource=_RESOURCES[0], provider=_PROVIDER)
# ne... |
def _pad_block(self, handle):
'''Pad the file with 0s to the end of the next block boundary.'''
extra = handle.tell() % 512
if extra:
handle.write(b'\x00' * (512 - extra)) | def function[_pad_block, parameter[self, handle]]:
constant[Pad the file with 0s to the end of the next block boundary.]
variable[extra] assign[=] binary_operation[call[name[handle].tell, parameter[]] <ast.Mod object at 0x7da2590d6920> constant[512]]
if name[extra] begin[:]
call[... | keyword[def] identifier[_pad_block] ( identifier[self] , identifier[handle] ):
literal[string]
identifier[extra] = identifier[handle] . identifier[tell] ()% literal[int]
keyword[if] identifier[extra] :
identifier[handle] . identifier[write] ( literal[string] *( literal[int] ... | def _pad_block(self, handle):
"""Pad the file with 0s to the end of the next block boundary."""
extra = handle.tell() % 512
if extra:
handle.write(b'\x00' * (512 - extra)) # depends on [control=['if'], data=[]] |
def update_status(modeladmin, request, queryset, status):
"""The workhorse function for the admin action functions that follow."""
# We loop over the objects here rather than use queryset.update() for
# two reasons:
#
# 1. No one should ever be updating zillions of Topics or Questions, so
# ... | def function[update_status, parameter[modeladmin, request, queryset, status]]:
constant[The workhorse function for the admin action functions that follow.]
for taget[name[obj]] in starred[name[queryset]] begin[:]
name[obj].status assign[=] name[status]
call[name[obj].save... | keyword[def] identifier[update_status] ( identifier[modeladmin] , identifier[request] , identifier[queryset] , identifier[status] ):
literal[string]
keyword[for] identifier[obj] keyword[in] identifier[queryset] :
identifier[obj] . identifier[status] = identifi... | def update_status(modeladmin, request, queryset, status):
"""The workhorse function for the admin action functions that follow."""
# We loop over the objects here rather than use queryset.update() for
# two reasons:
#
# 1. No one should ever be updating zillions of Topics or Questions, so
# ... |
def layer_norm_vars(filters):
"""Create Variables for layer norm."""
scale = tf.get_variable(
"layer_norm_scale", [filters], initializer=tf.ones_initializer())
bias = tf.get_variable(
"layer_norm_bias", [filters], initializer=tf.zeros_initializer())
return scale, bias | def function[layer_norm_vars, parameter[filters]]:
constant[Create Variables for layer norm.]
variable[scale] assign[=] call[name[tf].get_variable, parameter[constant[layer_norm_scale], list[[<ast.Name object at 0x7da18dc040a0>]]]]
variable[bias] assign[=] call[name[tf].get_variable, parameter[c... | keyword[def] identifier[layer_norm_vars] ( identifier[filters] ):
literal[string]
identifier[scale] = identifier[tf] . identifier[get_variable] (
literal[string] ,[ identifier[filters] ], identifier[initializer] = identifier[tf] . identifier[ones_initializer] ())
identifier[bias] = identifier[tf] . ident... | def layer_norm_vars(filters):
"""Create Variables for layer norm."""
scale = tf.get_variable('layer_norm_scale', [filters], initializer=tf.ones_initializer())
bias = tf.get_variable('layer_norm_bias', [filters], initializer=tf.zeros_initializer())
return (scale, bias) |
def encode(raw: Any) -> str:
"""
Encode credential attribute value, leaving any (stringified) int32 alone: indy-sdk predicates
operate on int32 values properly only when their encoded values match their raw values.
To disambiguate for decoding, the operation reserves a sentinel for the null value and o... | def function[encode, parameter[raw]]:
constant[
Encode credential attribute value, leaving any (stringified) int32 alone: indy-sdk predicates
operate on int32 values properly only when their encoded values match their raw values.
To disambiguate for decoding, the operation reserves a sentinel for t... | keyword[def] identifier[encode] ( identifier[raw] : identifier[Any] )-> identifier[str] :
literal[string]
keyword[if] identifier[raw] keyword[is] keyword[None] :
keyword[return] identifier[str] ( identifier[I32_BOUND] )
identifier[stringified] = identifier[str] ( identifier[raw] )
... | def encode(raw: Any) -> str:
"""
Encode credential attribute value, leaving any (stringified) int32 alone: indy-sdk predicates
operate on int32 values properly only when their encoded values match their raw values.
To disambiguate for decoding, the operation reserves a sentinel for the null value and o... |
def _get_casing_permutations(cls, input_string):
""" Takes a string and gives all possible permutations of casing for comparative purposes
:param input_string: str, name of object
:return: Generator(str), iterator of all possible permutations of casing for the input_string
"""
i... | def function[_get_casing_permutations, parameter[cls, input_string]]:
constant[ Takes a string and gives all possible permutations of casing for comparative purposes
:param input_string: str, name of object
:return: Generator(str), iterator of all possible permutations of casing for the input_s... | keyword[def] identifier[_get_casing_permutations] ( identifier[cls] , identifier[input_string] ):
literal[string]
keyword[if] keyword[not] identifier[input_string] :
keyword[yield] literal[string]
keyword[else] :
identifier[first] = identifier[input_string] [:... | def _get_casing_permutations(cls, input_string):
""" Takes a string and gives all possible permutations of casing for comparative purposes
:param input_string: str, name of object
:return: Generator(str), iterator of all possible permutations of casing for the input_string
"""
if not in... |
def get_region(b):
"""Tries to get the bucket region from Location.LocationConstraint
Special cases:
LocationConstraint EU defaults to eu-west-1
LocationConstraint null defaults to us-east-1
Args:
b (object): A bucket object
Returns:
string: an aws region string
""... | def function[get_region, parameter[b]]:
constant[Tries to get the bucket region from Location.LocationConstraint
Special cases:
LocationConstraint EU defaults to eu-west-1
LocationConstraint null defaults to us-east-1
Args:
b (object): A bucket object
Returns:
stri... | keyword[def] identifier[get_region] ( identifier[b] ):
literal[string]
identifier[remap] ={ keyword[None] : literal[string] , literal[string] : literal[string] }
identifier[region] = identifier[b] . identifier[get] ( literal[string] ,{}). identifier[get] ( literal[string] )
keyword[return] ident... | def get_region(b):
"""Tries to get the bucket region from Location.LocationConstraint
Special cases:
LocationConstraint EU defaults to eu-west-1
LocationConstraint null defaults to us-east-1
Args:
b (object): A bucket object
Returns:
string: an aws region string
""... |
def gather_lines(self):
"""
Return the number of lines.
"""
total_lines = 0
for file in self.all_files:
full_path = os.path.join(self.paths["role"], file)
with open(full_path, "r") as f:
for line in f:
total_lines += 1
... | def function[gather_lines, parameter[self]]:
constant[
Return the number of lines.
]
variable[total_lines] assign[=] constant[0]
for taget[name[file]] in starred[name[self].all_files] begin[:]
variable[full_path] assign[=] call[name[os].path.join, parameter[call[n... | keyword[def] identifier[gather_lines] ( identifier[self] ):
literal[string]
identifier[total_lines] = literal[int]
keyword[for] identifier[file] keyword[in] identifier[self] . identifier[all_files] :
identifier[full_path] = identifier[os] . identifier[path] . identifier[jo... | def gather_lines(self):
"""
Return the number of lines.
"""
total_lines = 0
for file in self.all_files:
full_path = os.path.join(self.paths['role'], file)
with open(full_path, 'r') as f:
for line in f:
total_lines += 1 # depends on [control=['for'... |
def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False): # pylint: disable=too-many-arguments
"""Find Notes based on the specified criteria.
Args:
query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the ... | def function[find, parameter[self, query, func, labels, colors, pinned, archived, trashed]]:
constant[Find Notes based on the specified criteria.
Args:
query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the title and text.
func (Union[callab... | keyword[def] identifier[find] ( identifier[self] , identifier[query] = keyword[None] , identifier[func] = keyword[None] , identifier[labels] = keyword[None] , identifier[colors] = keyword[None] , identifier[pinned] = keyword[None] , identifier[archived] = keyword[None] , identifier[trashed] = keyword[False] ):
... | def find(self, query=None, func=None, labels=None, colors=None, pinned=None, archived=None, trashed=False): # pylint: disable=too-many-arguments
'Find Notes based on the specified criteria.\n\n Args:\n query (Union[_sre.SRE_Pattern, str, None]): A str or regular expression to match against the ti... |
def main():
"""
NAME
find_EI.py
DESCRIPTION
Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function.
Finds flattening factor that gives elongation/inclination pair consistent with TK03.
Finds bootstrap confidence bounds
SYNTAX... | def function[main, parameter[]]:
constant[
NAME
find_EI.py
DESCRIPTION
Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function.
Finds flattening factor that gives elongation/inclination pair consistent with TK03.
Finds bootstra... | keyword[def] identifier[main] ():
literal[string]
identifier[fmt] , identifier[nb] = literal[string] , literal[int]
identifier[plot] = literal[int]
keyword[if] literal[string] keyword[in] identifier[sys] . identifier[argv] :
identifier[print] ( identifier[main] . identifier[__doc__]... | def main():
"""
NAME
find_EI.py
DESCRIPTION
Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function.
Finds flattening factor that gives elongation/inclination pair consistent with TK03.
Finds bootstrap confidence bounds
SYNTAX... |
def _urlextract_cli():
"""
urlextract - command line program that will print all URLs to stdout
Usage: urlextract [input_file] [-u] [-v]
input_file - text file with URLs to extract
"""
import argparse
def get_args():
"""
Parse programs arguments
"""
parser =... | def function[_urlextract_cli, parameter[]]:
constant[
urlextract - command line program that will print all URLs to stdout
Usage: urlextract [input_file] [-u] [-v]
input_file - text file with URLs to extract
]
import module[argparse]
def function[get_args, parameter[]]:
... | keyword[def] identifier[_urlextract_cli] ():
literal[string]
keyword[import] identifier[argparse]
keyword[def] identifier[get_args] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] = literal[string]
... | def _urlextract_cli():
"""
urlextract - command line program that will print all URLs to stdout
Usage: urlextract [input_file] [-u] [-v]
input_file - text file with URLs to extract
"""
import argparse
def get_args():
"""
Parse programs arguments
"""
parser =... |
def close(self):
"""Close connection to device."""
if self._transport:
self._transport.close()
self._transport = None
self._chacha = None | def function[close, parameter[self]]:
constant[Close connection to device.]
if name[self]._transport begin[:]
call[name[self]._transport.close, parameter[]]
name[self]._transport assign[=] constant[None]
name[self]._chacha assign[=] constant[None] | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_transport] :
identifier[self] . identifier[_transport] . identifier[close] ()
identifier[self] . identifier[_transport] = keyword[None]
identifier[self] .... | def close(self):
"""Close connection to device."""
if self._transport:
self._transport.close() # depends on [control=['if'], data=[]]
self._transport = None
self._chacha = None |
def pangocairo_create_context(cr):
"""
If python-gi-cairo is not installed, using PangoCairo.create_context
dies with an unhelpful KeyError, check for that and output somethig
useful.
"""
# TODO move this to core.backend
try:
return PangoCairo.create_context(cr)
except KeyError a... | def function[pangocairo_create_context, parameter[cr]]:
constant[
If python-gi-cairo is not installed, using PangoCairo.create_context
dies with an unhelpful KeyError, check for that and output somethig
useful.
]
<ast.Try object at 0x7da18dc06110> | keyword[def] identifier[pangocairo_create_context] ( identifier[cr] ):
literal[string]
keyword[try] :
keyword[return] identifier[PangoCairo] . identifier[create_context] ( identifier[cr] )
keyword[except] identifier[KeyError] keyword[as] identifier[e] :
keyword[if] identifi... | def pangocairo_create_context(cr):
"""
If python-gi-cairo is not installed, using PangoCairo.create_context
dies with an unhelpful KeyError, check for that and output somethig
useful.
"""
# TODO move this to core.backend
try:
return PangoCairo.create_context(cr) # depends on [contro... |
def delete_before(self, segment_info):
"""
Delete all base backups and WAL before a given segment
This is the most commonly-used deletion operator; to delete
old backups and WAL.
"""
# This will delete all base backup data before segment_info.
self._delete_base... | def function[delete_before, parameter[self, segment_info]]:
constant[
Delete all base backups and WAL before a given segment
This is the most commonly-used deletion operator; to delete
old backups and WAL.
]
call[name[self]._delete_base_backups_before, parameter[name[se... | keyword[def] identifier[delete_before] ( identifier[self] , identifier[segment_info] ):
literal[string]
identifier[self] . identifier[_delete_base_backups_before] ( identifier[segment_info] )
identifier[self] . identifier[_delete_wals_before] ( identifier[segment_info] ... | def delete_before(self, segment_info):
"""
Delete all base backups and WAL before a given segment
This is the most commonly-used deletion operator; to delete
old backups and WAL.
"""
# This will delete all base backup data before segment_info.
self._delete_base_backups_befo... |
def register_updates(self, *updates):
"""
Register updates that will be executed in each iteration.
"""
for key, node in updates:
if key not in self._registered_updates:
self.updates.append((key, node))
self._registered_updates.add(key) | def function[register_updates, parameter[self]]:
constant[
Register updates that will be executed in each iteration.
]
for taget[tuple[[<ast.Name object at 0x7da1b0381780>, <ast.Name object at 0x7da1b0380fa0>]]] in starred[name[updates]] begin[:]
if compare[name[key] <ast... | keyword[def] identifier[register_updates] ( identifier[self] ,* identifier[updates] ):
literal[string]
keyword[for] identifier[key] , identifier[node] keyword[in] identifier[updates] :
keyword[if] identifier[key] keyword[not] keyword[in] identifier[self] . identifier[_registered... | def register_updates(self, *updates):
"""
Register updates that will be executed in each iteration.
"""
for (key, node) in updates:
if key not in self._registered_updates:
self.updates.append((key, node))
self._registered_updates.add(key) # depends on [control=['... |
def seasons(ephemeris):
"""Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter.
"""
earth = ephemeris... | def function[seasons, parameter[ephemeris]]:
constant[Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter.... | keyword[def] identifier[seasons] ( identifier[ephemeris] ):
literal[string]
identifier[earth] = identifier[ephemeris] [ literal[string] ]
identifier[sun] = identifier[ephemeris] [ literal[string] ]
keyword[def] identifier[season_at] ( identifier[t] ):
literal[string]
identifi... | def seasons(ephemeris):
"""Build a function of time that returns the quarter of the year.
The function that this returns will expect a single argument that is
a :class:`~skyfield.timelib.Time` and will return 0 through 3 for
the seasons Spring, Summer, Autumn, and Winter.
"""
earth = ephemeris... |
def sources_add(name, ruby=None, user=None):
'''
Make sure that a gem source is added.
name
The URL of the gem source to be added
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run the ``gem`` command
... | def function[sources_add, parameter[name, ruby, user]]:
constant[
Make sure that a gem source is added.
name
The URL of the gem source to be added
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run t... | keyword[def] identifier[sources_add] ( identifier[name] , identifier[ruby] = keyword[None] , identifier[user] = keyword[None] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] , literal[string] : keyword[None] , literal[string] : literal[string] , literal[string] :{}}
keyword[i... | def sources_add(name, ruby=None, user=None):
"""
Make sure that a gem source is added.
name
The URL of the gem source to be added
ruby: None
For RVM or rbenv installations: the ruby version and gemset to target.
user: None
The user under which to run the ``gem`` command
... |
def InitFromNotification(self, notification, is_pending=False):
"""Initializes this object from an existing notification.
Args:
notification: A rdfvalues.flows.Notification object.
is_pending: Indicates whether the user has already seen this notification
or not.
Returns:
The curr... | def function[InitFromNotification, parameter[self, notification, is_pending]]:
constant[Initializes this object from an existing notification.
Args:
notification: A rdfvalues.flows.Notification object.
is_pending: Indicates whether the user has already seen this notification
or not.
... | keyword[def] identifier[InitFromNotification] ( identifier[self] , identifier[notification] , identifier[is_pending] = keyword[False] ):
literal[string]
identifier[self] . identifier[timestamp] = identifier[notification] . identifier[timestamp]
identifier[self] . identifier[message] = identifier[noti... | def InitFromNotification(self, notification, is_pending=False):
"""Initializes this object from an existing notification.
Args:
notification: A rdfvalues.flows.Notification object.
is_pending: Indicates whether the user has already seen this notification
or not.
Returns:
The curr... |
def getStatuses(self, repo_user, repo_name, sha):
"""
:param sha: Full sha to list the statuses from.
:return: A defered with the result from GitHub.
"""
return self.api.makeRequest(
['repos', repo_user, repo_name, 'statuses', sha],
method='GET') | def function[getStatuses, parameter[self, repo_user, repo_name, sha]]:
constant[
:param sha: Full sha to list the statuses from.
:return: A defered with the result from GitHub.
]
return[call[name[self].api.makeRequest, parameter[list[[<ast.Constant object at 0x7da1b27e0700>, <ast.Nam... | keyword[def] identifier[getStatuses] ( identifier[self] , identifier[repo_user] , identifier[repo_name] , identifier[sha] ):
literal[string]
keyword[return] identifier[self] . identifier[api] . identifier[makeRequest] (
[ literal[string] , identifier[repo_user] , identifier[repo_name] , li... | def getStatuses(self, repo_user, repo_name, sha):
"""
:param sha: Full sha to list the statuses from.
:return: A defered with the result from GitHub.
"""
return self.api.makeRequest(['repos', repo_user, repo_name, 'statuses', sha], method='GET') |
def parent(groups,ID):
"""given a groups dictionary and an ID, return its actual parent ID."""
if ID in groups.keys():
return ID # already a parent
if not ID in groups.keys():
for actualParent in groups.keys():
if ID in groups[actualParent]:
return actualParent # ... | def function[parent, parameter[groups, ID]]:
constant[given a groups dictionary and an ID, return its actual parent ID.]
if compare[name[ID] in call[name[groups].keys, parameter[]]] begin[:]
return[name[ID]]
if <ast.UnaryOp object at 0x7da1afe06e90> begin[:]
for taget[nam... | keyword[def] identifier[parent] ( identifier[groups] , identifier[ID] ):
literal[string]
keyword[if] identifier[ID] keyword[in] identifier[groups] . identifier[keys] ():
keyword[return] identifier[ID]
keyword[if] keyword[not] identifier[ID] keyword[in] identifier[groups] . identifier... | def parent(groups, ID):
"""given a groups dictionary and an ID, return its actual parent ID."""
if ID in groups.keys():
return ID # already a parent # depends on [control=['if'], data=['ID']]
if not ID in groups.keys():
for actualParent in groups.keys():
if ID in groups[actualP... |
def _drop_tables(self):
"""
Clear the subdomain db's tables
"""
drop_cmd = "DROP TABLE IF EXISTS {};"
for table in [self.subdomain_table, self.blocked_table]:
cursor = self.conn.cursor()
db_query_execute(cursor, drop_cmd.format(table), ()) | def function[_drop_tables, parameter[self]]:
constant[
Clear the subdomain db's tables
]
variable[drop_cmd] assign[=] constant[DROP TABLE IF EXISTS {};]
for taget[name[table]] in starred[list[[<ast.Attribute object at 0x7da1b2347c70>, <ast.Attribute object at 0x7da1b2346d40>]]] b... | keyword[def] identifier[_drop_tables] ( identifier[self] ):
literal[string]
identifier[drop_cmd] = literal[string]
keyword[for] identifier[table] keyword[in] [ identifier[self] . identifier[subdomain_table] , identifier[self] . identifier[blocked_table] ]:
identifier[cursor... | def _drop_tables(self):
"""
Clear the subdomain db's tables
"""
drop_cmd = 'DROP TABLE IF EXISTS {};'
for table in [self.subdomain_table, self.blocked_table]:
cursor = self.conn.cursor()
db_query_execute(cursor, drop_cmd.format(table), ()) # depends on [control=['for'], data... |
def xrefs(self, nid, bidirectional=False):
"""
Fetches xrefs for a node
Arguments
---------
nid : str
Node identifier for entity to be queried
bidirection : bool
If True, include nodes xreffed to nid
Return
------
list[str... | def function[xrefs, parameter[self, nid, bidirectional]]:
constant[
Fetches xrefs for a node
Arguments
---------
nid : str
Node identifier for entity to be queried
bidirection : bool
If True, include nodes xreffed to nid
Return
--... | keyword[def] identifier[xrefs] ( identifier[self] , identifier[nid] , identifier[bidirectional] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[xref_graph] keyword[is] keyword[not] keyword[None] :
identifier[xg] = identifier[self] . identifier[xref_gra... | def xrefs(self, nid, bidirectional=False):
"""
Fetches xrefs for a node
Arguments
---------
nid : str
Node identifier for entity to be queried
bidirection : bool
If True, include nodes xreffed to nid
Return
------
list[str]
... |
def error_respond(self, error):
"""Create an error response to this request.
When processing the request produces an error condition this method can be used to
create the error response object.
:param error: Specifies what error occurred.
:type error: str or Exception
:... | def function[error_respond, parameter[self, error]]:
constant[Create an error response to this request.
When processing the request produces an error condition this method can be used to
create the error response object.
:param error: Specifies what error occurred.
:type error:... | keyword[def] identifier[error_respond] ( identifier[self] , identifier[error] ):
literal[string]
keyword[if] identifier[self] . identifier[unique_id] keyword[is] keyword[None] :
keyword[return] keyword[None]
identifier[response] = identifier[JSONRPCErrorResponse] ()
... | def error_respond(self, error):
"""Create an error response to this request.
When processing the request produces an error condition this method can be used to
create the error response object.
:param error: Specifies what error occurred.
:type error: str or Exception
:retu... |
def compile_command(context, backend, config):
"""
Compile Sass project sources to CSS
"""
logger = logging.getLogger("boussole")
logger.info(u"Building project")
# Discover settings file
try:
discovering = Discover(backends=[SettingsBackendJson,
... | def function[compile_command, parameter[context, backend, config]]:
constant[
Compile Sass project sources to CSS
]
variable[logger] assign[=] call[name[logging].getLogger, parameter[constant[boussole]]]
call[name[logger].info, parameter[constant[Building project]]]
<ast.Try object a... | keyword[def] identifier[compile_command] ( identifier[context] , identifier[backend] , identifier[config] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( literal[string] )
identifier[logger] . identifier[info] ( literal[string] )
keyword[try] :
... | def compile_command(context, backend, config):
"""
Compile Sass project sources to CSS
"""
logger = logging.getLogger('boussole')
logger.info(u'Building project')
# Discover settings file
try:
discovering = Discover(backends=[SettingsBackendJson, SettingsBackendYaml])
(config... |
def resolve_url(self, url, follow_redirect=True):
"""Attempts to find a plugin that can use this URL.
The default protocol (http) will be prefixed to the URL if
not specified.
Raises :exc:`NoPluginError` on failure.
:param url: a URL to match against loaded plugins
:pa... | def function[resolve_url, parameter[self, url, follow_redirect]]:
constant[Attempts to find a plugin that can use this URL.
The default protocol (http) will be prefixed to the URL if
not specified.
Raises :exc:`NoPluginError` on failure.
:param url: a URL to match against load... | keyword[def] identifier[resolve_url] ( identifier[self] , identifier[url] , identifier[follow_redirect] = keyword[True] ):
literal[string]
identifier[url] = identifier[update_scheme] ( literal[string] , identifier[url] )
identifier[available_plugins] =[]
keyword[for] identifier[... | def resolve_url(self, url, follow_redirect=True):
"""Attempts to find a plugin that can use this URL.
The default protocol (http) will be prefixed to the URL if
not specified.
Raises :exc:`NoPluginError` on failure.
:param url: a URL to match against loaded plugins
:param ... |
def get_creation_date(
self,
bucket: str,
key: str,
) -> datetime:
"""
Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is ... | def function[get_creation_date, parameter[self, bucket, key]]:
constant[
Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is being retrieved.
:return: the ... | keyword[def] identifier[get_creation_date] (
identifier[self] ,
identifier[bucket] : identifier[str] ,
identifier[key] : identifier[str] ,
)-> identifier[datetime] :
literal[string]
keyword[return] identifier[self] . identifier[get_last_modified_date] ( identifier[bucket] , id... | def get_creation_date(self, bucket: str, key: str) -> datetime:
"""
Retrieves the creation date for a given key in a given bucket.
:param bucket: the bucket the object resides in.
:param key: the key of the object for which the creation date is being retrieved.
:return: the creation ... |
def send_rpc_async(self, conn_id, address, rpc_id, payload, timeout, callback):
"""Asynchronously send an RPC to this IOTile device."""
future = self._loop.launch_coroutine(self._adapter.send_rpc(conn_id, address, rpc_id, payload, timeout))
def format_response(future):
payload = No... | def function[send_rpc_async, parameter[self, conn_id, address, rpc_id, payload, timeout, callback]]:
constant[Asynchronously send an RPC to this IOTile device.]
variable[future] assign[=] call[name[self]._loop.launch_coroutine, parameter[call[name[self]._adapter.send_rpc, parameter[name[conn_id], name[a... | keyword[def] identifier[send_rpc_async] ( identifier[self] , identifier[conn_id] , identifier[address] , identifier[rpc_id] , identifier[payload] , identifier[timeout] , identifier[callback] ):
literal[string]
identifier[future] = identifier[self] . identifier[_loop] . identifier[launch_coroutine]... | def send_rpc_async(self, conn_id, address, rpc_id, payload, timeout, callback):
"""Asynchronously send an RPC to this IOTile device."""
future = self._loop.launch_coroutine(self._adapter.send_rpc(conn_id, address, rpc_id, payload, timeout))
def format_response(future):
payload = None
except... |
def require_variable(df, variable, unit=None, year=None, exclude_on_fail=False,
**kwargs):
"""Check whether all scenarios have a required variable
Parameters
----------
df: IamDataFrame instance
args: see `IamDataFrame.require_variable()` for details
kwargs: passed to `df.f... | def function[require_variable, parameter[df, variable, unit, year, exclude_on_fail]]:
constant[Check whether all scenarios have a required variable
Parameters
----------
df: IamDataFrame instance
args: see `IamDataFrame.require_variable()` for details
kwargs: passed to `df.filter()`
]
... | keyword[def] identifier[require_variable] ( identifier[df] , identifier[variable] , identifier[unit] = keyword[None] , identifier[year] = keyword[None] , identifier[exclude_on_fail] = keyword[False] ,
** identifier[kwargs] ):
literal[string]
identifier[fdf] = identifier[df] . identifier[filter] (** identif... | def require_variable(df, variable, unit=None, year=None, exclude_on_fail=False, **kwargs):
"""Check whether all scenarios have a required variable
Parameters
----------
df: IamDataFrame instance
args: see `IamDataFrame.require_variable()` for details
kwargs: passed to `df.filter()`
"""
... |
def _parse_proc_cgroups(self):
"""Parse /proc/cgroups"""
"""
#subsys_name hierarchy num_cgroups enabled
cpuset 0 1 1
ns 0 1 1
cpu 1 10 1
cpuacct 0 1 1
memory 0 1 1
devices 0 1 1
freezer 0 1 1
net_cls 0 1 1
"""
for l... | def function[_parse_proc_cgroups, parameter[self]]:
constant[Parse /proc/cgroups]
constant[
#subsys_name hierarchy num_cgroups enabled
cpuset 0 1 1
ns 0 1 1
cpu 1 10 1
cpuacct 0 1 1
memory 0 1 1
devices 0 1 1
freezer 0 1 1
net_cls 0... | keyword[def] identifier[_parse_proc_cgroups] ( identifier[self] ):
literal[string]
literal[string]
keyword[for] identifier[line] keyword[in] identifier[fileops] . identifier[readlines] ( literal[string] ):
identifier[m] = identifier[self] . identifier[_RE_CGROUPS] . ident... | def _parse_proc_cgroups(self):
"""Parse /proc/cgroups"""
'\n #subsys_name\thierarchy\tnum_cgroups\tenabled\n cpuset\t0\t1\t1\n ns\t0\t1\t1\n cpu\t1\t10\t1\n cpuacct\t0\t1\t1\n memory\t0\t1\t1\n devices\t0\t1\t1\n freezer\t0\t1\t1\n net_cls\t0\t1\t1\... |
def init(name, storage_backend='dir', trust_password=None,
network_address=None, network_port=None, storage_create_device=None,
storage_create_loop=None, storage_pool=None,
done_file='%SALT_CONFIG_DIR%/lxd_initialized'):
'''
Initalizes the LXD Daemon, as LXD doesn't tell if its initia... | def function[init, parameter[name, storage_backend, trust_password, network_address, network_port, storage_create_device, storage_create_loop, storage_pool, done_file]]:
constant[
Initalizes the LXD Daemon, as LXD doesn't tell if its initialized
we touch the the done_file and check if it exist.
Thi... | keyword[def] identifier[init] ( identifier[name] , identifier[storage_backend] = literal[string] , identifier[trust_password] = keyword[None] ,
identifier[network_address] = keyword[None] , identifier[network_port] = keyword[None] , identifier[storage_create_device] = keyword[None] ,
identifier[storage_create_loop]... | def init(name, storage_backend='dir', trust_password=None, network_address=None, network_port=None, storage_create_device=None, storage_create_loop=None, storage_pool=None, done_file='%SALT_CONFIG_DIR%/lxd_initialized'):
"""
Initalizes the LXD Daemon, as LXD doesn't tell if its initialized
we touch the the ... |
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'T... | def function[list_storage, parameter[kwargs, conn, call]]:
constant[
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
]
if compare[name[call] not_equal[!=] constant[function]... | keyword[def] identifier[list_storage] ( identifier[kwargs] = keyword[None] , identifier[conn] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] != literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
... | def list_storage(kwargs=None, conn=None, call=None):
"""
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
"""
if call != 'function':
raise SaltCloudSystemExit('The list_stora... |
def configure(log_file):
'''
Configure root logger to log INFO to stderr and DEBUG to log file.
The log file is appended to. Stderr uses a terse format, while the log file
uses a verbose unambiguous format.
Root level is set to INFO.
Parameters
----------
log_file : ~pathlib.Path
... | def function[configure, parameter[log_file]]:
constant[
Configure root logger to log INFO to stderr and DEBUG to log file.
The log file is appended to. Stderr uses a terse format, while the log file
uses a verbose unambiguous format.
Root level is set to INFO.
Parameters
----------
... | keyword[def] identifier[configure] ( identifier[log_file] ):
literal[string]
identifier[root_logger] = identifier[logging] . identifier[getLogger] ()
identifier[root_logger] . identifier[setLevel] ( identifier[logging] . identifier[INFO] )
identifier[stderr_handler] = identifier[loggin... | def configure(log_file):
"""
Configure root logger to log INFO to stderr and DEBUG to log file.
The log file is appended to. Stderr uses a terse format, while the log file
uses a verbose unambiguous format.
Root level is set to INFO.
Parameters
----------
log_file : ~pathlib.Path
... |
def description(self, description):
"""
Sets the description of this AdditionalRecipient.
The description of the additional recipient.
:param description: The description of this AdditionalRecipient.
:type: str
"""
if description is None:
raise Value... | def function[description, parameter[self, description]]:
constant[
Sets the description of this AdditionalRecipient.
The description of the additional recipient.
:param description: The description of this AdditionalRecipient.
:type: str
]
if compare[name[descrip... | keyword[def] identifier[description] ( identifier[self] , identifier[description] ):
literal[string]
keyword[if] identifier[description] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] identifier[len] ( identifier[descrip... | def description(self, description):
"""
Sets the description of this AdditionalRecipient.
The description of the additional recipient.
:param description: The description of this AdditionalRecipient.
:type: str
"""
if description is None:
raise ValueError('Invali... |
def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example)
win... | def function[_max_gain_split, parameter[self, examples]]:
constant[
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
]
variable[gains] assign[=] call[name[self]._new_set_of_gain_counters, parameter[]]
for taget[name[example]] in starred... | keyword[def] identifier[_max_gain_split] ( identifier[self] , identifier[examples] ):
literal[string]
identifier[gains] = identifier[self] . identifier[_new_set_of_gain_counters] ()
keyword[for] identifier[example] keyword[in] identifier[examples] :
keyword[for] identifier... | def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example) # depends on [control=['for'],... |
def get(self, url, params=None, **kwargs):
""" Shorthand for self.oauth_request(url, 'get')
:param str url: url to send get oauth request to
:param dict params: request parameter to get the service data
:param kwargs: extra params to send to request api
:return: Response of the ... | def function[get, parameter[self, url, params]]:
constant[ Shorthand for self.oauth_request(url, 'get')
:param str url: url to send get oauth request to
:param dict params: request parameter to get the service data
:param kwargs: extra params to send to request api
:return: Resp... | keyword[def] identifier[get] ( identifier[self] , identifier[url] , identifier[params] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[oauth_request] ( identifier[url] , literal[string] , identifier[params] = identifier[params] ,** identifier... | def get(self, url, params=None, **kwargs):
""" Shorthand for self.oauth_request(url, 'get')
:param str url: url to send get oauth request to
:param dict params: request parameter to get the service data
:param kwargs: extra params to send to request api
:return: Response of the requ... |
def _classify_load_memory(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify load-memory gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "dst_reg <- mem[src_reg + offset]" pattern.
for dst_reg, dst_val in... | def function[_classify_load_memory, parameter[self, regs_init, regs_fini, mem_fini, written_regs, read_regs]]:
constant[Classify load-memory gadgets.
]
variable[matches] assign[=] list[[]]
variable[regs_init_inv] assign[=] call[name[self]._invert_dictionary, parameter[name[regs_init]]]
... | keyword[def] identifier[_classify_load_memory] ( identifier[self] , identifier[regs_init] , identifier[regs_fini] , identifier[mem_fini] , identifier[written_regs] , identifier[read_regs] ):
literal[string]
identifier[matches] =[]
identifier[regs_init_inv] = identifier[self] . identifier[... | def _classify_load_memory(self, regs_init, regs_fini, mem_fini, written_regs, read_regs):
"""Classify load-memory gadgets.
"""
matches = []
regs_init_inv = self._invert_dictionary(regs_init)
# Check for "dst_reg <- mem[src_reg + offset]" pattern.
for (dst_reg, dst_val) in regs_fini.items():
... |
def create(self, resource, data):
'''
A base function that performs a default create POST request for a given object
'''
service_def, resource_def, path = self._get_service_information(
resource)
self._validate(resource, data)
return self.call(path=path, dat... | def function[create, parameter[self, resource, data]]:
constant[
A base function that performs a default create POST request for a given object
]
<ast.Tuple object at 0x7da204565540> assign[=] call[name[self]._get_service_information, parameter[name[resource]]]
call[name[self]._v... | keyword[def] identifier[create] ( identifier[self] , identifier[resource] , identifier[data] ):
literal[string]
identifier[service_def] , identifier[resource_def] , identifier[path] = identifier[self] . identifier[_get_service_information] (
identifier[resource] )
identifier[self... | def create(self, resource, data):
"""
A base function that performs a default create POST request for a given object
"""
(service_def, resource_def, path) = self._get_service_information(resource)
self._validate(resource, data)
return self.call(path=path, data=data, method='post') |
def order_transforms(transforms):
"""Orders transforms to ensure proper chaining.
For example, if `transforms = [B, A, C]`, and `A` produces outputs needed
by `B`, the transforms will be re-rorderd to `[A, B, C]`.
Parameters
----------
transforms : list
List of transform instances to o... | def function[order_transforms, parameter[transforms]]:
constant[Orders transforms to ensure proper chaining.
For example, if `transforms = [B, A, C]`, and `A` produces outputs needed
by `B`, the transforms will be re-rorderd to `[A, B, C]`.
Parameters
----------
transforms : list
L... | keyword[def] identifier[order_transforms] ( identifier[transforms] ):
literal[string]
identifier[outputs] = identifier[set] (). identifier[union] (*[ identifier[t] . identifier[outputs] keyword[for] identifier[t] keyword[in] identifier[transforms] ])
identifier[out] =[]
identifier[remain... | def order_transforms(transforms):
"""Orders transforms to ensure proper chaining.
For example, if `transforms = [B, A, C]`, and `A` produces outputs needed
by `B`, the transforms will be re-rorderd to `[A, B, C]`.
Parameters
----------
transforms : list
List of transform instances to o... |
def reports(self, **kwargs):
"""Get all reports for this node. Additional arguments may also be
specified that will be passed to the query function.
"""
return self.__api.reports(
query=EqualsOperator("certname", self.name),
**kwargs) | def function[reports, parameter[self]]:
constant[Get all reports for this node. Additional arguments may also be
specified that will be passed to the query function.
]
return[call[name[self].__api.reports, parameter[]]] | keyword[def] identifier[reports] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[__api] . identifier[reports] (
identifier[query] = identifier[EqualsOperator] ( literal[string] , identifier[self] . identifier[name] ),
** i... | def reports(self, **kwargs):
"""Get all reports for this node. Additional arguments may also be
specified that will be passed to the query function.
"""
return self.__api.reports(query=EqualsOperator('certname', self.name), **kwargs) |
def sample(self, label):
"""
generate random padding boxes according to parameters
if satifactory padding generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Returns:
----------
... | def function[sample, parameter[self, label]]:
constant[
generate random padding boxes according to parameters
if satifactory padding generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Retu... | keyword[def] identifier[sample] ( identifier[self] , identifier[label] ):
literal[string]
identifier[samples] =[]
identifier[count] = literal[int]
keyword[for] identifier[trial] keyword[in] identifier[range] ( identifier[self] . identifier[max_trials] ):
keyword[i... | def sample(self, label):
"""
generate random padding boxes according to parameters
if satifactory padding generated, apply to ground-truth as well
Parameters:
----------
label : numpy.array (n x 5 matrix)
ground-truths
Returns:
----------
... |
def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs):
"""
Wrapping the isochrone and kernel simulate functions.
"""
mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus)
lon, lat = kernel.simulate(len(mag_1))
return mag_1, mag_2, lon, lat | def function[satellite, parameter[isochrone, kernel, stellar_mass, distance_modulus]]:
constant[
Wrapping the isochrone and kernel simulate functions.
]
<ast.Tuple object at 0x7da1b2346fe0> assign[=] call[name[isochrone].simulate, parameter[name[stellar_mass], name[distance_modulus]]]
<a... | keyword[def] identifier[satellite] ( identifier[isochrone] , identifier[kernel] , identifier[stellar_mass] , identifier[distance_modulus] ,** identifier[kwargs] ):
literal[string]
identifier[mag_1] , identifier[mag_2] = identifier[isochrone] . identifier[simulate] ( identifier[stellar_mass] , identifier[di... | def satellite(isochrone, kernel, stellar_mass, distance_modulus, **kwargs):
"""
Wrapping the isochrone and kernel simulate functions.
"""
(mag_1, mag_2) = isochrone.simulate(stellar_mass, distance_modulus)
(lon, lat) = kernel.simulate(len(mag_1))
return (mag_1, mag_2, lon, lat) |
def set_boot_arch(arch='default'):
'''
Set the kernel to boot in 32 or 64 bit mode on next boot.
.. note::
When this function fails with the error ``changes to kernel
architecture failed to save!``, then the boot arch is not updated.
This is either an Apple bug, not available on the... | def function[set_boot_arch, parameter[arch]]:
constant[
Set the kernel to boot in 32 or 64 bit mode on next boot.
.. note::
When this function fails with the error ``changes to kernel
architecture failed to save!``, then the boot arch is not updated.
This is either an Apple bug,... | keyword[def] identifier[set_boot_arch] ( identifier[arch] = literal[string] ):
literal[string]
keyword[if] identifier[arch] keyword[not] keyword[in] [ literal[string] , literal[string] , literal[string] ]:
identifier[msg] = literal[string] literal[string] literal[string] . identifier[format] ... | def set_boot_arch(arch='default'):
"""
Set the kernel to boot in 32 or 64 bit mode on next boot.
.. note::
When this function fails with the error ``changes to kernel
architecture failed to save!``, then the boot arch is not updated.
This is either an Apple bug, not available on the... |
def without(self, *keys):
"""
Get all items except for those with the specified keys.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection
"""
items = copy(self.items)
keys = reversed(sorted(keys))
for key in keys:
d... | def function[without, parameter[self]]:
constant[
Get all items except for those with the specified keys.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection
]
variable[items] assign[=] call[name[copy], parameter[name[self].items]]
varia... | keyword[def] identifier[without] ( identifier[self] ,* identifier[keys] ):
literal[string]
identifier[items] = identifier[copy] ( identifier[self] . identifier[items] )
identifier[keys] = identifier[reversed] ( identifier[sorted] ( identifier[keys] ))
keyword[for] identifier[ke... | def without(self, *keys):
"""
Get all items except for those with the specified keys.
:param keys: The keys to remove
:type keys: tuple
:rtype: Collection
"""
items = copy(self.items)
keys = reversed(sorted(keys))
for key in keys:
del items[key] # depen... |
def writeANVLString(ANVLDict, ordering=UNTL_XML_ORDER):
"""Take a dictionary and write out the key/value pairs
in ANVL format.
"""
lines = []
# Loop through the ordering for the data.
for key in ordering:
# Make sure the element exists in the data set.
if key in ANVLDict:
... | def function[writeANVLString, parameter[ANVLDict, ordering]]:
constant[Take a dictionary and write out the key/value pairs
in ANVL format.
]
variable[lines] assign[=] list[[]]
for taget[name[key]] in starred[name[ordering]] begin[:]
if compare[name[key] in name[ANVLDict]]... | keyword[def] identifier[writeANVLString] ( identifier[ANVLDict] , identifier[ordering] = identifier[UNTL_XML_ORDER] ):
literal[string]
identifier[lines] =[]
keyword[for] identifier[key] keyword[in] identifier[ordering] :
keyword[if] identifier[key] keyword[in] identifier[ANVLD... | def writeANVLString(ANVLDict, ordering=UNTL_XML_ORDER):
"""Take a dictionary and write out the key/value pairs
in ANVL format.
"""
lines = []
# Loop through the ordering for the data.
for key in ordering:
# Make sure the element exists in the data set.
if key in ANVLDict:
... |
def guid_to_squid(guid):
'''
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed... | def function[guid_to_squid, parameter[guid]]:
constant[
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final comp... | keyword[def] identifier[guid_to_squid] ( identifier[guid] ):
literal[string]
identifier[guid_pattern] = identifier[re] . identifier[compile] ( literal[string] )
identifier[guid_match] = identifier[guid_pattern] . identifier[match] ( identifier[guid] )
identifier[squid] = literal[string]
key... | def guid_to_squid(guid):
"""
Converts a GUID to a compressed guid (SQUID)
Each Guid has 5 parts separated by '-'. For the first three each one will be
totally reversed, and for the remaining two each one will be reversed by
every other character. Then the final compressed Guid will be constructed... |
def flow_rate(vol_per_rev, rpm):
"""Return the flow rate from a pump given the volume of fluid pumped per
revolution and the desired pump speed.
:param vol_per_rev: Volume of fluid output per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:param rpm: Desired pump speed in revolu... | def function[flow_rate, parameter[vol_per_rev, rpm]]:
constant[Return the flow rate from a pump given the volume of fluid pumped per
revolution and the desired pump speed.
:param vol_per_rev: Volume of fluid output per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:param rp... | keyword[def] identifier[flow_rate] ( identifier[vol_per_rev] , identifier[rpm] ):
literal[string]
keyword[return] ( identifier[vol_per_rev] * identifier[rpm] ). identifier[to] ( identifier[u] . identifier[mL] / identifier[u] . identifier[s] ) | def flow_rate(vol_per_rev, rpm):
"""Return the flow rate from a pump given the volume of fluid pumped per
revolution and the desired pump speed.
:param vol_per_rev: Volume of fluid output per revolution (dependent on pump and tubing)
:type vol_per_rev: float
:param rpm: Desired pump speed in revolu... |
def create_graph_from_data(self, data, **kwargs):
"""Run the PC algorithm.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by PC on the given data.
"""
# Building setup w/ arguments.
self.argu... | def function[create_graph_from_data, parameter[self, data]]:
constant[Run the PC algorithm.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by PC on the given data.
]
call[name[self].arguments][consta... | keyword[def] identifier[create_graph_from_data] ( identifier[self] , identifier[data] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[arguments] [ literal[string] ]= identifier[self] . identifier[dir_CI_test] [ identifier[self] . identifier[CI_test] ]
ident... | def create_graph_from_data(self, data, **kwargs):
"""Run the PC algorithm.
Args:
data (pandas.DataFrame): DataFrame containing the data
Returns:
networkx.DiGraph: Solution given by PC on the given data.
"""
# Building setup w/ arguments.
self.arguments['{CITE... |
def get_location_from_taobao(ip):
"""
{
"code":0,
"data":{
"country":"\u65e5\u672c",
"country_id":"JP",
"area":"",
"area_id":"",
"region":"",
"region_id":"",
"city":"",
"city_id":"",
"coun... | def function[get_location_from_taobao, parameter[ip]]:
constant[
{
"code":0,
"data":{
"country":"日本",
"country_id":"JP",
"area":"",
"area_id":"",
"region":"",
"region_id":"",
"city":"",
"city_id":... | keyword[def] identifier[get_location_from_taobao] ( identifier[ip] ):
literal[string]
keyword[global] identifier[taobao]
identifier[response] = identifier[requests] . identifier[get] ( identifier[taobao] % identifier[ip] )
keyword[if] keyword[not] identifier[response] . identifier[status_code... | def get_location_from_taobao(ip):
"""
{
"code":0,
"data":{
"country":"日本",
"country_id":"JP",
"area":"",
"area_id":"",
"region":"",
"region_id":"",
"city":"",
"city_id":"",
"county":"",
... |
def setup_random_indices_local_geometry(self, coordination):
"""
Sets up random indices for the local geometry, for testing purposes
:param coordination: coordination of the local geometry
"""
self.icentral_site = 0
self.indices = list(range(1, coordination + 1))
... | def function[setup_random_indices_local_geometry, parameter[self, coordination]]:
constant[
Sets up random indices for the local geometry, for testing purposes
:param coordination: coordination of the local geometry
]
name[self].icentral_site assign[=] constant[0]
name[se... | keyword[def] identifier[setup_random_indices_local_geometry] ( identifier[self] , identifier[coordination] ):
literal[string]
identifier[self] . identifier[icentral_site] = literal[int]
identifier[self] . identifier[indices] = identifier[list] ( identifier[range] ( literal[int] , identifi... | def setup_random_indices_local_geometry(self, coordination):
"""
Sets up random indices for the local geometry, for testing purposes
:param coordination: coordination of the local geometry
"""
self.icentral_site = 0
self.indices = list(range(1, coordination + 1))
np.random.shuffl... |
def get(self):
"""Return the number of seconds elapsed since object creation,
or since last call to this function, whichever is more recent."""
elapsed = datetime.now() - self._previous
self._previous += elapsed
return elapsed.total_seconds() | def function[get, parameter[self]]:
constant[Return the number of seconds elapsed since object creation,
or since last call to this function, whichever is more recent.]
variable[elapsed] assign[=] binary_operation[call[name[datetime].now, parameter[]] - name[self]._previous]
<ast.AugAssign o... | keyword[def] identifier[get] ( identifier[self] ):
literal[string]
identifier[elapsed] = identifier[datetime] . identifier[now] ()- identifier[self] . identifier[_previous]
identifier[self] . identifier[_previous] += identifier[elapsed]
keyword[return] identifier[elapsed] . ide... | def get(self):
"""Return the number of seconds elapsed since object creation,
or since last call to this function, whichever is more recent."""
elapsed = datetime.now() - self._previous
self._previous += elapsed
return elapsed.total_seconds() |
def duplicate(self, fullname, shortname, categoryid,
visible=True, **kwargs):
"""
Duplicates an existing course with options.
Note: Can be very slow running.
:param string fullname: The new course's full name
:param string shortname: The new course's short name... | def function[duplicate, parameter[self, fullname, shortname, categoryid, visible]]:
constant[
Duplicates an existing course with options.
Note: Can be very slow running.
:param string fullname: The new course's full name
:param string shortname: The new course's short name
... | keyword[def] identifier[duplicate] ( identifier[self] , identifier[fullname] , identifier[shortname] , identifier[categoryid] ,
identifier[visible] = keyword[True] ,** identifier[kwargs] ):
literal[string]
identifier[allowed_options] =[ literal[string] , literal[string... | def duplicate(self, fullname, shortname, categoryid, visible=True, **kwargs):
"""
Duplicates an existing course with options.
Note: Can be very slow running.
:param string fullname: The new course's full name
:param string shortname: The new course's short name
:param string... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.