code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def copy_public_vars(self):
"""
Like get_vars(), but does not include any private variables and
deep copies each variable.
"""
vars = self.get_vars()
vars = dict([k for k in list(vars.items()) if not k[0].startswith('_')])
return deepcopy(vars) | Like get_vars(), but does not include any private variables and
deep copies each variable. |
def square_sum(list_vector):
"""!
@brief Calculates square sum of vector that is represented by list, each element can be represented by list - multidimensional elements.
@param[in] list_vector (list): Input vector.
@return (double) Square sum of vector.
"""
square_... | !
@brief Calculates square sum of vector that is represented by list, each element can be represented by list - multidimensional elements.
@param[in] list_vector (list): Input vector.
@return (double) Square sum of vector. |
def is_admin(self):
"""
Check that the user has a role with the code 'admin'
"""
for ur in self.roleusers:
if ur.role.code == 'admin':
return True
return False | Check that the user has a role with the code 'admin' |
def cortex_rgba_plot_2D(the_map, rgba, axes=None, triangulation=None):
'''
cortex_rgba_plot_2D(map, rgba, axes) plots the given cortical map on the given axes using the
given (n x 4) matrix of vertex colors and yields the resulting polygon collection object.
cortex_rgba_plot_2D(map, rgba) uses matplot... | cortex_rgba_plot_2D(map, rgba, axes) plots the given cortical map on the given axes using the
given (n x 4) matrix of vertex colors and yields the resulting polygon collection object.
cortex_rgba_plot_2D(map, rgba) uses matplotlib.pyplot.gca() for the axes.
The option triangulation may also be passed if ... |
def ensure_text(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if isinstance(s, binary_type):
return s.decode(encodin... | Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str` |
def configure_discover(self, ns, definition):
"""
Register a swagger endpoint for a set of operations.
"""
@self.add_route(ns.singleton_path, Operation.Discover, ns)
def discover():
swagger = build_swagger(self.graph, ns, self.find_matching_endpoints(ns))
... | Register a swagger endpoint for a set of operations. |
def starting_offset(source_code, offset):
"""Return the offset in which the completion should be inserted
Usually code assist proposals should be inserted like::
completion = proposal.name
result = (source_code[:starting_offset] +
completion + source_code[offset:])
Where... | Return the offset in which the completion should be inserted
Usually code assist proposals should be inserted like::
completion = proposal.name
result = (source_code[:starting_offset] +
completion + source_code[offset:])
Where starting_offset is the offset returned by this f... |
def get_example_extractions(fname):
"Get extractions from one of the examples in `cag_examples`."
with open(fname, 'r') as f:
sentences = f.read().splitlines()
rdf_xml_dict = {}
for sentence in sentences:
logger.info("Reading \"%s\"..." % sentence)
html = tc.send_query(sentence, ... | Get extractions from one of the examples in `cag_examples`. |
def _recolumn(tmy3_dataframe):
"""
Rename the columns of the TMY3 DataFrame.
Parameters
----------
tmy3_dataframe : DataFrame
inplace : bool
passed to DataFrame.rename()
Returns
-------
Recolumned DataFrame.
"""
# paste in the header as one long line
raw_columns... | Rename the columns of the TMY3 DataFrame.
Parameters
----------
tmy3_dataframe : DataFrame
inplace : bool
passed to DataFrame.rename()
Returns
-------
Recolumned DataFrame. |
def import_ed25519_privatekey_from_file(filepath, password=None, prompt=False):
"""
<Purpose>
Import the encrypted ed25519 key file in 'filepath', decrypt it, and return
the key object in 'securesystemslib.formats.ED25519KEY_SCHEMA' format.
The private key (may also contain the public part) is encrypte... | <Purpose>
Import the encrypted ed25519 key file in 'filepath', decrypt it, and return
the key object in 'securesystemslib.formats.ED25519KEY_SCHEMA' format.
The private key (may also contain the public part) is encrypted with AES
256 and CTR the mode of operation. The password is strengthened with
... |
def t_intnumber(self, t):
r'-?\d+'
t.value = int(t.value)
t.type = 'NUMBER'
return t | r'-?\d+ |
def def_alignment(self, year):
"""Returns the name of the defensive alignment the team ran in the
given year.
:year: Int representing the season year.
:returns: A string representing the defensive alignment.
"""
scheme_text = self._year_info_pq(year, 'Defensive Alignment... | Returns the name of the defensive alignment the team ran in the
given year.
:year: Int representing the season year.
:returns: A string representing the defensive alignment. |
def unzip_data():
"""
Extract all files from downloaded FEH data zip file.
"""
with ZipFile(os.path.join(CACHE_FOLDER, CACHE_ZIP), 'r') as zf:
zf.extractall(path=CACHE_FOLDER) | Extract all files from downloaded FEH data zip file. |
def load(self):
"""Read the internally formatet hdf5 relative spectral response data"""
import h5py
no_detectors_message = False
with h5py.File(self.filename, 'r') as h5f:
self.band_names = [b.decode('utf-8') for b in h5f.attrs['band_names'].tolist()]
self.descri... | Read the internally formatet hdf5 relative spectral response data |
def start_channels(self, shell=True, sub=True, stdin=True, hb=True):
"""Starts the channels for this kernel.
This will create the channels if they do not exist and then start
them. If port numbers of 0 are being used (random ports) then you
must first call :method:`start_kernel`. If the... | Starts the channels for this kernel.
This will create the channels if they do not exist and then start
them. If port numbers of 0 are being used (random ports) then you
must first call :method:`start_kernel`. If the channels have been
stopped and you call this, :class:`RuntimeError` wil... |
def get(self, value):
"""
Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem
"""
_nothing = object()
item = s... | Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem |
def check_config_mode(self, check_string=")#", pattern=""):
"""Checks if the device is in configuration mode"""
return super(CalixB6Base, self).check_config_mode(check_string=check_string) | Checks if the device is in configuration mode |
def add_output_option(parser):
"""output option"""
parser.add_argument("-o", "--outdir", dest="outdir", type=str, default='GSEApy_reports',
metavar='', action="store",
help="The GSEApy output directory. Default: the current working directory")
parser.add_argu... | output option |
def run(self):
"""
Execute all current and future payloads
Blocks and executes payloads until :py:meth:`stop` is called.
It is an error for any orphaned payload to return or raise.
"""
self._logger.info('runner started: %s', self)
try:
with self._lock... | Execute all current and future payloads
Blocks and executes payloads until :py:meth:`stop` is called.
It is an error for any orphaned payload to return or raise. |
def csv_to_num_matrix(csv_file_path):
"""Load a CSV file consisting only of numbers into a Python matrix of floats.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv)
"""
mtx = []
with open(csv_file_path) as csv_data_file:
for row in csv_data_file:
... | Load a CSV file consisting only of numbers into a Python matrix of floats.
Args:
csv_file_path: Full path to a valid CSV file (e.g. c:/ladybug/test.csv) |
def search(self, keyword, source_in=None, **kwargs):
"""search song/artist/album by keyword
TODO: search album or artist
"""
for provider in self._providers:
if source_in is not None:
if provider.identifier not in source_in:
continue
... | search song/artist/album by keyword
TODO: search album or artist |
def tajima_d(ac, pos=None, start=None, stop=None, min_sites=3):
"""Calculate the value of Tajima's D over a given region.
Parameters
----------
ac : array_like, int, shape (n_variants, n_alleles)
Allele counts array.
pos : array_like, int, shape (n_items,), optional
Variant position... | Calculate the value of Tajima's D over a given region.
Parameters
----------
ac : array_like, int, shape (n_variants, n_alleles)
Allele counts array.
pos : array_like, int, shape (n_items,), optional
Variant positions, using 1-based coordinates, in ascending order.
start : int, opti... |
def to_json(self):
"""Serializes all the data in this query range into json form.
Returns:
all the data in json-compatible map.
"""
if self._key_ranges is None:
key_ranges_json = None
else:
key_ranges_json = []
for k in self._key_ranges:
if k:
key_ranges_js... | Serializes all the data in this query range into json form.
Returns:
all the data in json-compatible map. |
def rotate(x, y, degree):
"""Rotate a coordinate around point (0,0).
- x and y specify the coordinate.
- degree is a number from 0 to 360.
Returns a new coordinate.
"""
radian = float(degree) * 2 * math.pi / 360.0
newx = math.cos(radian) * x - math.sin(radian) * y
newy = math.sin(radian)... | Rotate a coordinate around point (0,0).
- x and y specify the coordinate.
- degree is a number from 0 to 360.
Returns a new coordinate. |
def disconnect(self):
"Disconnects from the Redis server"
self._parser.on_disconnect()
if self._sock is None:
return
if self._selector is not None:
self._selector.close()
self._selector = None
try:
if os.getpid() == self.pid:
... | Disconnects from the Redis server |
def instance_ik_model_receiver(fn):
"""
A method decorator that filters out sign_original_specals coming from models that don't
have fields that function as ImageFieldSourceGroup sources.
"""
@wraps(fn)
def receiver(self, sender, **kwargs):
# print 'inspect.isclass(sender? %s'%(inspect.... | A method decorator that filters out sign_original_specals coming from models that don't
have fields that function as ImageFieldSourceGroup sources. |
def entry(argv):
'''
Command entry
'''
command_dic = {
'migrate': run_migrate,
'init': run_init,
'send_nologin': run_send_nologin,
'send_all': run_send_all,
'review': run_review,
'sitemap': run_sitemap,
'editmap': run_editmap,
'check_kind':... | Command entry |
def decode_body(body, content_type):
"""Decode event body"""
if isinstance(body, dict):
return body
else:
try:
decoded_body = base64.b64decode(body)
except:
return body
if content_type == 'application/json':
... | Decode event body |
def run(configObj, wcsmap=None):
""" Interface for running `wdrizzle` from TEAL or Python command-line.
This code performs all file ``I/O`` to set up the use of the drizzle code for
a single exposure to replicate the functionality of the original `wdrizzle`.
"""
# Insure all output filenames speci... | Interface for running `wdrizzle` from TEAL or Python command-line.
This code performs all file ``I/O`` to set up the use of the drizzle code for
a single exposure to replicate the functionality of the original `wdrizzle`. |
def add_existence(self, rev):
"""Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already abo... | Add existence constraint for the field.
This is necessary because the normal meaning of 'x > 0' is: x > 0 and is present.
Without the existence constraint, MongoDB will treat 'x > 0' as: 'x' > 0 *or* is absent.
Of course, if the constraint is already about existence, nothing is done.
:... |
def _onerror(cls, kmsg, result):
""" To execute on execution failure
:param kser.schemas.Message kmsg: Kafka message
:param kser.result.Result result: Execution result
:return: Execution result
:rtype: kser.result.Result
"""
logger.error(
"{}.Failed: ... | To execute on execution failure
:param kser.schemas.Message kmsg: Kafka message
:param kser.result.Result result: Execution result
:return: Execution result
:rtype: kser.result.Result |
def next_image_partname(self, ext):
"""
Return a |PackURI| instance representing the next available image
partname, by sequence number. *ext* is used as the extention on the
returned partname.
"""
def first_available_image_idx():
image_idxs = sorted([
... | Return a |PackURI| instance representing the next available image
partname, by sequence number. *ext* is used as the extention on the
returned partname. |
def merge_version(self, merge_id, version_id):
"""Get merge version detail"""
path = urijoin(self.base_url,
GitLabClient.PROJECTS, self.owner + '%2F' + self.repository,
GitLabClient.MERGES, merge_id, GitLabClient.VERSIONS, version_id)
response = se... | Get merge version detail |
def init():
"""
Execute init tasks for all components (virtualenv, pip).
"""
print(yellow("# Setting up environment...\n", True))
virtualenv.init()
virtualenv.update_requirements()
print(green("\n# DONE.", True))
print(green("Type ") + green("activate", True) + green(" to enable your vir... | Execute init tasks for all components (virtualenv, pip). |
def _safe_str_cmp(a, b):
"""
Internal function to efficiently iterate over the hashes
Regular string compare will bail at the earliest opportunity
which allows timing attacks
"""
if len(a) != len(b):
return False
rv = 0
for x, y in zip(a, b):
rv |= ord(x) ^ ord(y)
... | Internal function to efficiently iterate over the hashes
Regular string compare will bail at the earliest opportunity
which allows timing attacks |
def get_webhook(self, id, **data):
"""
GET /webhooks/:id/
Returns a :format:`webhook` for the specified webhook as ``webhook``.
"""
return self.get("/webhooks/{0}/".format(id), data=data) | GET /webhooks/:id/
Returns a :format:`webhook` for the specified webhook as ``webhook``. |
def get_models(self, columns=None):
"""
Get the hydrated models without eager loading.
:param columns: The columns to get
:type columns: list
:return: A list of models
:rtype: orator.orm.collection.Collection
"""
results = self.apply_scopes().get_query()... | Get the hydrated models without eager loading.
:param columns: The columns to get
:type columns: list
:return: A list of models
:rtype: orator.orm.collection.Collection |
def report_server_init_errors(address=None, port=None, **kwargs):
''' A context manager to help print more informative error messages when a
``Server`` cannot be started due to a network problem.
Args:
address (str) : network address that the server will be listening on
port (int) : networ... | A context manager to help print more informative error messages when a
``Server`` cannot be started due to a network problem.
Args:
address (str) : network address that the server will be listening on
port (int) : network address that the server will be listening on
Example:
.. c... |
def commit(self, index_update=True, label_guesser_update=True):
"""
Apply the changes to the index
"""
logger.info("Index: Commiting changes")
self.docsearch.index.commit(index_update=index_update,
label_guesser_update=label_guesser_update) | Apply the changes to the index |
def eval_image(image, height, width, scope=None):
"""Prepare one image for evaluation.
Args:
image: 3-D float Tensor
height: integer
width: integer
scope: Optional scope for name_scope.
Returns:
3-D float Tensor of prepared image.
"""
with tf.name_scope(values=[image, height, width], name... | Prepare one image for evaluation.
Args:
image: 3-D float Tensor
height: integer
width: integer
scope: Optional scope for name_scope.
Returns:
3-D float Tensor of prepared image. |
def size(self, type=None, failed=False):
"""How many nodes in a network.
type specifies the class of node, failed
can be True/False/all.
"""
return len(self.nodes(type=type, failed=failed)) | How many nodes in a network.
type specifies the class of node, failed
can be True/False/all. |
def getParamFromEnv(self, var, default=''):
""" Function getParamFromEnv
Search a parameter in the host environment
@param var: the var name
@param hostgroup: the hostgroup item linked to this host
@param default: default value
@return RETURN: the value
"""
... | Function getParamFromEnv
Search a parameter in the host environment
@param var: the var name
@param hostgroup: the hostgroup item linked to this host
@param default: default value
@return RETURN: the value |
def get_imported_modules(cells, nb_module_name=''):
"Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority"
module_names = get_top_level_modules()
nb_imports = [match.group(1) for cell in cells for match in IMPORT_RE.finditer(cell[... | Finds all submodules of notebook - sorted by submodules > top level modules > manual imports. This gives notebook imports priority |
def plot_centres(array, centres, units, kpc_per_arcsec, zoom_offset_arcsec):
"""Plot the (y,x) centres (e.g. of a mass profile) on the array as an 'x'.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
centres : [[tuple]]
The l... | Plot the (y,x) centres (e.g. of a mass profile) on the array as an 'x'.
Parameters
-----------
array : data.array.scaled_array.ScaledArray
The 2D array of data which is plotted.
centres : [[tuple]]
The list of centres; centres in the same list entry are colored the same.
units : str... |
def _filters_pb(self):
"""Convert all the filters into a single generic Filter protobuf.
This may be a lone field filter or unary filter, may be a composite
filter or may be :data:`None`.
Returns:
google.cloud.firestore_v1beta1.types.\
StructuredQuery.Filter: A ... | Convert all the filters into a single generic Filter protobuf.
This may be a lone field filter or unary filter, may be a composite
filter or may be :data:`None`.
Returns:
google.cloud.firestore_v1beta1.types.\
StructuredQuery.Filter: A "generic" filter representing the
... |
def export(self):
"""return the object in a file"""
with open(self.export_url, 'w', encoding='utf-8') as file:
file.write(self.build())
if self.open_browser:
webbrowser.open_new_tab(self.export_url) | return the object in a file |
def polar_histogram(xdata, ydata, radial_bins="numpy", phi_bins=16,
transformed=False, *args, **kwargs):
"""Facade construction function for the PolarHistogram.
Parameters
----------
transformed : bool
phi_range : Optional[tuple]
range
"""
dropna = kwargs.pop("dropna... | Facade construction function for the PolarHistogram.
Parameters
----------
transformed : bool
phi_range : Optional[tuple]
range |
def initialize_plot(self, data=None, ax=None, make_plot=True, clear=False,
draw=False, remove=False, priority=None):
"""
Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that ... | Initialize the plot for a data array
Parameters
----------
data: InteractiveArray or ArrayList, optional
Data object that shall be visualized.
- If not None and `plot` is True, the given data is visualized.
- If None and the :attr:`data` attribute is not Non... |
def done(self):
"""Return True the future is done, False otherwise.
This still returns True in failure cases; checking :meth:`result` or
:meth:`exception` is the canonical way to assess success or failure.
"""
return self._exception != self._SENTINEL or self._result != self._SEN... | Return True the future is done, False otherwise.
This still returns True in failure cases; checking :meth:`result` or
:meth:`exception` is the canonical way to assess success or failure. |
def hide_virtual_ip_holder_chassis_virtual_ip(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_virtual_ip_holder = ET.SubElement(config, "hide-virtual-ip-holder", xmlns="urn:brocade.com:mgmt:brocade-chassis")
chassis = ET.SubElement(hide_virtual_ip_h... | Auto Generated Code |
def _get_content(self, response):
"""Checks for errors in the response. Returns response content, in bytes.
:param response: response object
:raise:
:UnexpectedResponse: if the server responded with an unexpected response
:return:
- ServiceNow response content
... | Checks for errors in the response. Returns response content, in bytes.
:param response: response object
:raise:
:UnexpectedResponse: if the server responded with an unexpected response
:return:
- ServiceNow response content |
def addPriority(self, objectName):
"""
添加聊天室消息优先级方法 方法
@param objectName:低优先级的消息类型,每次最多提交 5 个,设置的消息类型最多不超过 20 个。(必传)
@return code:返回码,200 为正常。
@return errorMessage:错误信息。
"""
desc = {
"name": "CodeSuccessReslut",
"desc": " http 成功返回结果",
... | 添加聊天室消息优先级方法 方法
@param objectName:低优先级的消息类型,每次最多提交 5 个,设置的消息类型最多不超过 20 个。(必传)
@return code:返回码,200 为正常。
@return errorMessage:错误信息。 |
def loader_cls(self):
"""Loader class used in `JsonRef.replace_refs`."""
cls = self.app.config['JSONSCHEMAS_LOADER_CLS']
if isinstance(cls, six.string_types):
return import_string(cls)
return cls | Loader class used in `JsonRef.replace_refs`. |
def gather_callbacks(self, optimizer) -> list:
""" Gather all the callbacks to be used in this training run """
callbacks = [FrameTracker(self.total_frames), TimeTracker()]
if self.scheduler_factory is not None:
callbacks.append(self.scheduler_factory.instantiate(optimizer))
... | Gather all the callbacks to be used in this training run |
def clear(self, job_id=None, force=False):
"""
Clear the queue and the job data. If job_id is not given, clear out all
jobs marked COMPLETED. If job_id is given, clear out the given job's
data. This function won't do anything if the job's state is not COMPLETED or FAILED.
:type j... | Clear the queue and the job data. If job_id is not given, clear out all
jobs marked COMPLETED. If job_id is given, clear out the given job's
data. This function won't do anything if the job's state is not COMPLETED or FAILED.
:type job_id: NoneType or str
:param job_id: the job_id to cle... |
def step3(expnums, ccd, version, rate_min,
rate_max, angle, width, field=None, prefix=None, dry_run=False,
maximum_flux_ratio=3, minimum_area=5, minimum_median_flux=1000.0):
"""run the actual step3 on the given exp/ccd combo"""
jmp_args = ['step3jmp']
matt_args = ['step3jjk']
idx ... | run the actual step3 on the given exp/ccd combo |
def plotly_app(context, name=None, slug=None, da=None, ratio=0.1, use_frameborder=False, initial_arguments=None):
'Insert a dash application using a html iframe'
fbs = '1' if use_frameborder else '0'
dstyle = """
position: relative;
padding-bottom: %s%%;
height: 0;
overflow:hidden;
"""... | Insert a dash application using a html iframe |
def process_pair(self, key, value):
""" Process a (key, value) pair """
old_key = key
old_value = value
# Create key intelligently
keyparts = self.bspacere.split(key)
# print keyparts
strippable = False
lastpart = keyparts[-1]
if lastpart.find(... | Process a (key, value) pair |
async def create_lease_if_not_exists_async(self, partition_id):
"""
Create in the store the lease info for the given partition, if it does not exist.
Do nothing if it does exist in the store already.
:param partition_id: The ID of a given parition.
:type partition_id: str
... | Create in the store the lease info for the given partition, if it does not exist.
Do nothing if it does exist in the store already.
:param partition_id: The ID of a given parition.
:type partition_id: str
:return: the existing or newly-created lease info for the partition.
:rtyp... |
def GWP(CASRN, AvailableMethods=False, Method=None):
r'''This function handles the retrieval of a chemical's Global Warming
Potential, relative to CO2. Lookup is based on CASRNs. Will automatically
select a data source to use if no Method is provided; returns None if the
data is not available.
Retu... | r'''This function handles the retrieval of a chemical's Global Warming
Potential, relative to CO2. Lookup is based on CASRNs. Will automatically
select a data source to use if no Method is provided; returns None if the
data is not available.
Returns the GWP for the 100yr outlook by default.
Parame... |
def give(self, terrain, num=1):
"""
Add a certain number of resources to the trade from giver->getter
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None
"""
for _ in range(num):
logging.debug('terrain={}'.format(... | Add a certain number of resources to the trade from giver->getter
:param terrain: resource type, models.Terrain
:param num: number to add, int
:return: None |
def run(self, graminit_h, graminit_c):
"""Load the grammar tables from the text files written by pgen."""
self.parse_graminit_h(graminit_h)
self.parse_graminit_c(graminit_c)
self.finish_off() | Load the grammar tables from the text files written by pgen. |
def _from_jwt(cls, headers, payload, key=None):
"""
Class specific implementation of from_jwt which should take jwt components and return
and instance of this Class with jwt information loaded.
:return: Jwt object containing the headers, payload and key
"""
jwt = Jwt(
... | Class specific implementation of from_jwt which should take jwt components and return
and instance of this Class with jwt information loaded.
:return: Jwt object containing the headers, payload and key |
def exportData(self, datfile):
"""
Create a .dat file with the data that has been loaded.
Args:
datfile: Path to the file (Relative to the current working
directory or absolute).
"""
def ampl_set(name, values):
def format_entry(e):
... | Create a .dat file with the data that has been loaded.
Args:
datfile: Path to the file (Relative to the current working
directory or absolute). |
def _get_intra_event_phi(self, C, mag, rjb, vs30, num_sites):
"""
Returns the intra-event standard deviation (phi), dependent on
magnitude, distance and vs30
"""
base_vals = np.zeros(num_sites)
# Magnitude Dependent phi (Equation 17)
if mag <= 4.5:
bas... | Returns the intra-event standard deviation (phi), dependent on
magnitude, distance and vs30 |
def convert_args_to_dict(call, with_lambda=False):
"""Convert all args to a dict such that every key and value in the dict is the same as the value of the arg.
Return the AST Call node with only one arg that is the dictionary
"""
keys, values = list(), list()
for arg in call.args:
if type(ar... | Convert all args to a dict such that every key and value in the dict is the same as the value of the arg.
Return the AST Call node with only one arg that is the dictionary |
def fit_proba(clf, X, y_proba, expand_factor=10, sample_weight=None,
shuffle=True, random_state=None,
**fit_params):
"""
Fit classifier ``clf`` to return probabilities close to ``y_proba``.
scikit-learn can't optimize cross-entropy directly if target
probability values are n... | Fit classifier ``clf`` to return probabilities close to ``y_proba``.
scikit-learn can't optimize cross-entropy directly if target
probability values are not indicator vectors. As a workaround this function
expands the dataset according to target probabilities.
Use expand_factor=None to turn it off
... |
def login_handler(self, config=None, prefix=None, **args):
"""OAuth starts here, redirect user to Google."""
params = {
'response_type': 'code',
'client_id': self.google_api_client_id,
'redirect_uri': self.scheme_host_port_prefix(
'http', config.host, ... | OAuth starts here, redirect user to Google. |
def read_image(filename):
"""!
@brief Returns image as N-dimension (depends on the input image) matrix, where one element of list describes pixel.
@param[in] filename (string): Path to image.
@return (list) Pixels where each pixel described by list of RGB-values.
"""
... | !
@brief Returns image as N-dimension (depends on the input image) matrix, where one element of list describes pixel.
@param[in] filename (string): Path to image.
@return (list) Pixels where each pixel described by list of RGB-values. |
def pages(self):
"""Get pages, reloading the site if needed."""
rev = self.db.get('site:rev')
if int(rev) != self.revision:
self.reload_site()
return self._pages | Get pages, reloading the site if needed. |
def get_metadata(self):
"""
Fetch repository repomd.xml file
"""
metadata_path = "{}/{}/{}".format(self.url,
self.metadata_dir,
self.metadata_file)
metadata_sig_path = "{}/{}/{}.sig".format(self.u... | Fetch repository repomd.xml file |
def get_initial(self, form, name):
"""
Get the initial data that got passed into the superform for this
composite field. It should return ``None`` if no initial values where
given.
"""
if hasattr(form, 'initial'):
return form.initial.get(name, None)
r... | Get the initial data that got passed into the superform for this
composite field. It should return ``None`` if no initial values where
given. |
def register(self, name, function, plugin, description=None):
"""
Registers a new document.
.. warning: You can not use any relative links inside a given document.
For instance, sphinx's toctree, image, figure or include statements do not work.
:param function: Func... | Registers a new document.
.. warning: You can not use any relative links inside a given document.
For instance, sphinx's toctree, image, figure or include statements do not work.
:param function: Function, which gets called for the new thread
:type function: function
... |
def rst(filename):
'''
Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive
'''
content = open(filename).read()
return re.sub(r'\.\.\s? code-block::\s*(\w|\+)+', '::', content) | Load rst file and sanitize it for PyPI.
Remove unsupported github tags:
- code-block directive |
def unpack_apply_message(bufs, g=None, copy=True):
"""Unpack f,args,kwargs from buffers packed by pack_apply_message().
Returns: original f,args,kwargs
"""
bufs = list(bufs) # allow us to pop
assert len(bufs) >= 2, "not enough buffers!"
pf = buffer_to_bytes_py2(bufs.pop(0))
f = uncan(pickl... | Unpack f,args,kwargs from buffers packed by pack_apply_message().
Returns: original f,args,kwargs |
def process_input(self, encoded_stream, value):
"""Process or drop a graph input.
This method asynchronously queued an item to be processed by the
sensorgraph worker task in _reset_vector. It must be called from
inside the emulation loop and returns immediately before the input is
... | Process or drop a graph input.
This method asynchronously queued an item to be processed by the
sensorgraph worker task in _reset_vector. It must be called from
inside the emulation loop and returns immediately before the input is
processed. |
def __Autostart_TCP_Server_checkBox_set_ui(self):
"""
Sets the **Autostart_TCP_Server_checkBox** Widget.
"""
# Adding settings key if it doesn't exists.
self.__settings.get_key(self.__settings_section, "autostart_tcp_server").isNull() and \
self.__settings.set_key(self._... | Sets the **Autostart_TCP_Server_checkBox** Widget. |
def run_cmd_if_file_missing(cmd, fname, out=os.path.devnull, err=os.path.devnull):
"""Runs an external command if file is absent.
:param list cmd: Command to run.
:param str fname: Path to the file, which existence is being checked.
:param str out: Output file
:param str err: Error file
:return... | Runs an external command if file is absent.
:param list cmd: Command to run.
:param str fname: Path to the file, which existence is being checked.
:param str out: Output file
:param str err: Error file
:return: True if cmd was executed, False otherwise
:rtype: boolean |
def _ReadFileHeader(self, file_object):
"""Reads the file header.
Args:
file_object (file): file-like object.
Returns:
keychain_file_header: file header.
Raises:
ParseError: if the file header cannot be read.
"""
data_type_map = self._GetDataTypeMap('keychain_file_header')
... | Reads the file header.
Args:
file_object (file): file-like object.
Returns:
keychain_file_header: file header.
Raises:
ParseError: if the file header cannot be read. |
def analytical(src, rec, res, freqtime, solution='fs', signal=None, ab=11,
aniso=None, epermH=None, epermV=None, mpermH=None, mpermV=None,
verb=2):
r"""Return the analytical full- or half-space solution.
Calculate the electromagnetic frequency- or time-domain field due to
infi... | r"""Return the analytical full- or half-space solution.
Calculate the electromagnetic frequency- or time-domain field due to
infinitesimal small electric or magnetic dipole source(s), measured by
infinitesimal small electric or magnetic dipole receiver(s); sources and
receivers are directed along the p... |
def extract(self, destdir, decompress='auto'):
"""Extract the entire MAR file into a directory.
Args:
destdir (str): A local directory on disk into which the contents of
this MAR file will be extracted. Required parent directories
will be created as necessary... | Extract the entire MAR file into a directory.
Args:
destdir (str): A local directory on disk into which the contents of
this MAR file will be extracted. Required parent directories
will be created as necessary.
decompress (obj, optional): Controls whether... |
def Q_srk(self, k):
"""
function (k). Returns the square root of noise matrix of dynamic model
on iteration k.
k (iteration number). starts at 0
This function is implemented to use SVD prediction step.
"""
ind = self.index[self.Q_time_var_index,... | function (k). Returns the square root of noise matrix of dynamic model
on iteration k.
k (iteration number). starts at 0
This function is implemented to use SVD prediction step. |
def robust_partition_all(n, iterable):
"""
replaces partition_all with a more robust version.
Workaround for a segfault in pybedtools when using a BedTool as an iterator:
https://github.com/daler/pybedtools/issues/88 for the discussion
"""
it = iter(iterable)
while True:
x = []
... | replaces partition_all with a more robust version.
Workaround for a segfault in pybedtools when using a BedTool as an iterator:
https://github.com/daler/pybedtools/issues/88 for the discussion |
def last(self, node):
# TODO: check docstring
"""Returns True if node is the last node in the route
Parameters
----------
nodes : type
Desc
Returns
-------
bool
True if node is the last node in the route
... | Returns True if node is the last node in the route
Parameters
----------
nodes : type
Desc
Returns
-------
bool
True if node is the last node in the route |
def _required_args(fn):
"""Returns arguments of fn with default=REQUIRED_ARG."""
spec = getargspec(fn)
if not spec.defaults:
return []
arg_names = spec.args[-len(spec.defaults):]
return [name for name, val in zip(arg_names, spec.defaults)
if val is REQUIRED_ARG] | Returns arguments of fn with default=REQUIRED_ARG. |
def send_message(source_jid, password, target_jid, body, subject = None,
message_type = "chat", message_thread = None, settings = None):
"""Star an XMPP session and send a message, then exit.
:Parameters:
- `source_jid`: sender JID
- `password`: sender password
- `target... | Star an XMPP session and send a message, then exit.
:Parameters:
- `source_jid`: sender JID
- `password`: sender password
- `target_jid`: recipient JID
- `body`: message body
- `subject`: message subject
- `message_type`: message type
- `message_thread`: mess... |
def lag(expr, offset, default=None, sort=None, ascending=True):
"""
Get value in the row ``offset`` rows prior to the current row.
:param offset: the offset value
:param default: default value for the function, when there are no rows satisfying the offset
:param expr: expression for calculation
... | Get value in the row ``offset`` rows prior to the current row.
:param offset: the offset value
:param default: default value for the function, when there are no rows satisfying the offset
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort ... |
def annotate(self, out, filename=None, commandline=None, relative_path=False):
"""
Dump annotated source code with current profiling statistics to "out"
file.
Time unit: second.
out (file-ish opened for writing)
Destination of annotated sources.
filename (str,... | Dump annotated source code with current profiling statistics to "out"
file.
Time unit: second.
out (file-ish opened for writing)
Destination of annotated sources.
filename (str, collection of str)
If provided, dump stats for given source file(s) only.
... |
def _generate_report_all(self):
'''Generate report for all subfolders contained by self.folder_id.'''
assert self.workbook is not None
count = 0
# Do all subfolders
for sid in self.folders.subfolders(self.folder_id, self.user):
count += 1
self._generate_f... | Generate report for all subfolders contained by self.folder_id. |
async def query_pathing(
self, start: Union[Unit, Point2, Point3], end: Union[Point2, Point3]
) -> Optional[Union[int, float]]:
""" Caution: returns 0 when path not found """
assert isinstance(start, (Point2, Unit))
assert isinstance(end, Point2)
if isinstance(start, Point2):... | Caution: returns 0 when path not found |
def build_tree_parser(patterns):
""" This parser_type simply outputs an array of [(tree, regex)]
for use in another language.
"""
def output():
for pattern in patterns:
yield (pattern.build_full_tree(), pattern.regex)
return list(output()) | This parser_type simply outputs an array of [(tree, regex)]
for use in another language. |
def create_dataset(self,
name,
x_img_size,
y_img_size,
z_img_size,
x_vox_res,
y_vox_res,
z_vox_res,
x_offset=0,
y... | Creates a dataset.
Arguments:
name (str): Name of dataset
x_img_size (int): max x coordinate of image size
y_img_size (int): max y coordinate of image size
z_img_size (int): max z coordinate of image size
x_vox_res (float): x voxel resolution
... |
def plot(self, normed=False, scale_errors_by=1.0, scale_histogram_by=1.0, plt=plt, errors=False, **kwargs):
"""Plots the histogram with Poisson (sqrt(n)) error bars
- scale_errors_by multiplies the error bars by its argument
- scale_histogram_by multiplies the histogram AND the error bars by... | Plots the histogram with Poisson (sqrt(n)) error bars
- scale_errors_by multiplies the error bars by its argument
- scale_histogram_by multiplies the histogram AND the error bars by its argument
- plt thing to call .errorbar on (pylab, figure, axes, whatever the matplotlib guys come up wit... |
def find_near_matches_substitutions_ngrams(subsequence, sequence,
max_substitutions):
"""search for near-matches of subsequence in sequence
This searches for near-matches, where the nearly-matching parts of the
sequence must meet the following limitations (relativ... | search for near-matches of subsequence in sequence
This searches for near-matches, where the nearly-matching parts of the
sequence must meet the following limitations (relative to the subsequence):
* the number of character substitutions must be less than max_substitutions
* no deletions or insertions... |
def current_version(self, object, relations_as_of=None, check_db=False):
"""
Return the current version of the given object.
The current version is the one having its version_end_date set to NULL.
If there is not such a version then it means the object has been
'deleted' and so ... | Return the current version of the given object.
The current version is the one having its version_end_date set to NULL.
If there is not such a version then it means the object has been
'deleted' and so there is no current version available. In this case
the function returns None.
... |
def get_pos(self, sector):
"""Get index (into the raw data of the disk image) of start of sector
This base class method assumes the sectors are one after another, in
order starting from the beginning of the raw data.
"""
if not self.sector_is_valid(sector):
raise Byt... | Get index (into the raw data of the disk image) of start of sector
This base class method assumes the sectors are one after another, in
order starting from the beginning of the raw data. |
def close(self):
"""Close underlying stream"""
if self.tabix_file and not self.tabix_file.closed:
self.tabix_file.close()
if self.stream:
self.stream.close() | Close underlying stream |
def __create_matcher(self, match_class, **keywds):
"""implementation details"""
matcher_args = keywds.copy()
del matcher_args['function']
del matcher_args['recursive']
if 'allow_empty' in matcher_args:
del matcher_args['allow_empty']
decl_matcher = decl_match... | implementation details |
def focus_widget(self, checked=None, w=None):
"""Focus the given widget. Checked is ignored and only used as a slot for QAbstractButton.clicked.
:param checked: The checked state of the button that was clicked
:type checked: bool
:param w: the widget to focus
:type w: QtGui.QWid... | Focus the given widget. Checked is ignored and only used as a slot for QAbstractButton.clicked.
:param checked: The checked state of the button that was clicked
:type checked: bool
:param w: the widget to focus
:type w: QtGui.QWidget
:returns: None
:raises: None |
def getElementsByTagName(start_node: ParentNode, tag: str) -> NodeList:
"""Get child nodes which tag name is ``tag``."""
_tag = tag.upper()
return getElementsBy(start_node, lambda node: node.tagName == _tag) | Get child nodes which tag name is ``tag``. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.