code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def safe_print(ustring, errors='replace', **kwargs):
""" Safely print a unicode string """
encoding = sys.stdout.encoding or 'utf-8'
if sys.version_info[0] == 3:
print(ustring, **kwargs)
else:
bytestr = ustring.encode(encoding, errors=errors)
print(bytestr, **kwargs) | Safely print a unicode string |
def summarize(self, **kwargs):
"""
Return pandas DataFrame with the most important results stored in the timers.
"""
import pandas as pd
colnames = ["fname", "wall_time", "cpu_time", "mpi_nprocs", "omp_nthreads", "mpi_rank"]
frame = pd.DataFrame(columns=colnames)
... | Return pandas DataFrame with the most important results stored in the timers. |
def cholesky(A, sparse=True, verbose=True):
"""
Choose the best possible cholesky factorizor.
if possible, import the Scikit-Sparse sparse Cholesky method.
Permutes the output L to ensure A = L.H . L
otherwise defaults to numpy's non-sparse version
Parameters
----------
A : array-like... | Choose the best possible cholesky factorizor.
if possible, import the Scikit-Sparse sparse Cholesky method.
Permutes the output L to ensure A = L.H . L
otherwise defaults to numpy's non-sparse version
Parameters
----------
A : array-like
array to decompose
sparse : boolean, defaul... |
def invalidate_cache(self, obj=None, queryset=None,
extra=None, force_all=False):
"""
Method that should be called by all tiggers to invalidate the
cache for an item(s).
Should be overriden by inheriting classes to customize behavior.
"""
if sel... | Method that should be called by all tiggers to invalidate the
cache for an item(s).
Should be overriden by inheriting classes to customize behavior. |
def solveConsRepAgent(solution_next,DiscFac,CRRA,IncomeDstn,CapShare,DeprFac,PermGroFac,aXtraGrid):
'''
Solve one period of the simple representative agent consumption-saving model.
Parameters
----------
solution_next : ConsumerSolution
Solution to the next period's problem (i.e. previous i... | Solve one period of the simple representative agent consumption-saving model.
Parameters
----------
solution_next : ConsumerSolution
Solution to the next period's problem (i.e. previous iteration).
DiscFac : float
Intertemporal discount factor for future utility.
CRRA : float
... |
def get_by(self, field, value):
"""
Gets the list of firmware baseline resources managed by the appliance. Optional parameters can be used to
filter the list of resources returned.
The search is case-insensitive.
Args:
field: Field name to filter.
value:... | Gets the list of firmware baseline resources managed by the appliance. Optional parameters can be used to
filter the list of resources returned.
The search is case-insensitive.
Args:
field: Field name to filter.
value: Value to filter.
Returns:
list... |
def _buildTraitCovar(self, trait_covar_type='freeform', rank=1, fixed_trait_covar=None, jitter=1e-4):
"""
Internal functions that builds the trait covariance matrix using the LIMIX framework
Args:
trait_covar_type: type of covaraince to use. Default 'freeform'. possible values are
... | Internal functions that builds the trait covariance matrix using the LIMIX framework
Args:
trait_covar_type: type of covaraince to use. Default 'freeform'. possible values are
rank: rank of a possible lowrank component (default 1)
fixed_trait_covar: PxP matr... |
def normalize_val(val):
"""Normalize JSON/YAML derived values as they pertain
to Vault resources and comparison operations """
if is_unicode(val) and val.isdigit():
return int(val)
elif isinstance(val, list):
return ','.join(val)
elif val is None:
return ''
return val | Normalize JSON/YAML derived values as they pertain
to Vault resources and comparison operations |
def message_user(self, username, domain, subject, message):
"""Currently use send_message_chat and discard subject, because headline messages are not
stored by mod_offline."""
kwargs = {
'body': message,
'from': domain,
'to': '%s@%s' % (username, domain),
... | Currently use send_message_chat and discard subject, because headline messages are not
stored by mod_offline. |
def text_list_to_colors(names):
'''
Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors.
'''
# STEP A: compute strings distance between all combnations of strings
Dnames = np.zeros( (len(names), len(names)) )
for i in range(len(names)):
... | Generates a list of colors based on a list of names (strings). Similar strings correspond to similar colors. |
def remove_task_db(self, fs_id):
'''ๅฐไปปๅกไปๆฐๆฎๅบไธญๅ ้ค'''
sql = 'DELETE FROM tasks WHERE fsid=?'
self.cursor.execute(sql, [fs_id, ])
self.check_commit() | ๅฐไปปๅกไปๆฐๆฎๅบไธญๅ ้ค |
def eqy(ql, qs, ns=None,):
"""
*New in pywbem 0.12*
This function is a wrapper for :meth:`~pywbem.WBEMConnection.ExecQuery`.
Execute a query in a namespace.
Parameters:
ql (:term:`string`):
Name of the query language used in the `qs` parameter, e.g.
"DMTF:CQL" for CIM Q... | *New in pywbem 0.12*
This function is a wrapper for :meth:`~pywbem.WBEMConnection.ExecQuery`.
Execute a query in a namespace.
Parameters:
ql (:term:`string`):
Name of the query language used in the `qs` parameter, e.g.
"DMTF:CQL" for CIM Query Language, and "WQL" for WBEM Query... |
def dpsi2_dtheta(self, dL_dpsi2, Z, mu, S, target):
"""Shape N,num_inducing,num_inducing,Ntheta"""
self._psi_computations(Z, mu, S)
d_var = 2.*self._psi2 / self.variance
# d_length = 2.*self._psi2[:, :, :, None] * (self._psi2_Zdist_sq * self._psi2_denom + self._psi2_mudist_sq + S[:, None... | Shape N,num_inducing,num_inducing,Ntheta |
def set_pixel_spacing(hdr, spacing):
r"""Depreciated synonym of `~medpy.io.header.set_voxel_spacing`."""
warnings.warn('get_pixel_spacing() is depreciated, use set_voxel_spacing() instead', category=DeprecationWarning)
set_voxel_spacing(hdr, spacing) | r"""Depreciated synonym of `~medpy.io.header.set_voxel_spacing`. |
def function(self):
"""
The function passed to the `fit_function` specified in `scipy_data_fitting.Fit.options`,
and used by `scipy_data_fitting.Fit.pointspace` to generate plots, etc.
Its number of arguments and their order is determined by items 1, 2, and 3
as listed in `scipy... | The function passed to the `fit_function` specified in `scipy_data_fitting.Fit.options`,
and used by `scipy_data_fitting.Fit.pointspace` to generate plots, etc.
Its number of arguments and their order is determined by items 1, 2, and 3
as listed in `scipy_data_fitting.Fit.all_variables`.
... |
def _remove_hlink(self):
"""
Remove the a:hlinkClick or a:hlinkHover element, including dropping
any relationship it might have.
"""
hlink = self._hlink
if hlink is None:
return
rId = hlink.rId
if rId:
self.part.drop_rel(rId)
... | Remove the a:hlinkClick or a:hlinkHover element, including dropping
any relationship it might have. |
def is_none(entity, prop, name):
"bool: True if the value of a property is None."
return is_not_empty(entity, prop, name) and getattr(entity, name) is None | bool: True if the value of a property is None. |
def compute_column_width_and_height(self):
'''
compute and set the column width for all colls in the table
'''
# skip tables with no row
if not self.rows:
return
# determine row height
for row in self.rows:
max_row_height = max((len(cell.g... | compute and set the column width for all colls in the table |
def justify(clr, argd):
""" Justify str/Colr based on user args. """
methodmap = {
'--ljust': clr.ljust,
'--rjust': clr.rjust,
'--center': clr.center,
}
for flag in methodmap:
if argd[flag]:
if argd[flag] in ('0', '-'):
val = get_terminal_size(... | Justify str/Colr based on user args. |
def build_html():
"""Build the html, to be served by IndexHandler"""
source = AjaxDataSource(data_url='./data',
polling_interval=INTERVAL,
method='GET')
# OHLC plot
p = figure(plot_height=400,
title='OHLC',
sizing_mod... | Build the html, to be served by IndexHandler |
def main(self, function):
"""
Decorator to define the main function of the experiment.
The main function of an experiment is the default command that is being
run when no command is specified, or when calling the run() method.
Usually it is more convenient to use ``automain`` i... | Decorator to define the main function of the experiment.
The main function of an experiment is the default command that is being
run when no command is specified, or when calling the run() method.
Usually it is more convenient to use ``automain`` instead. |
def retrieve_import_alias_mapping(names_list):
"""Creates a dictionary mapping aliases to their respective name.
import_alias_names is used in module_definitions.py and visit_Call"""
import_alias_names = dict()
for alias in names_list:
if alias.asname:
import_alias_names[alias.asnam... | Creates a dictionary mapping aliases to their respective name.
import_alias_names is used in module_definitions.py and visit_Call |
def primary_keys_full(cls):
"""Get primary key properties for a SQLAlchemy cls.
Taken from marshmallow_sqlalchemy
"""
mapper = cls.__mapper__
return [
mapper.get_property_by_column(column)
for column in mapper.primary_key
] | Get primary key properties for a SQLAlchemy cls.
Taken from marshmallow_sqlalchemy |
def extract_all(zipfile, dest_folder):
"""
reads the zip file, determines compression
and unzips recursively until source files
are extracted
"""
z = ZipFile(zipfile)
print(z)
z.extract(dest_folder) | reads the zip file, determines compression
and unzips recursively until source files
are extracted |
def rename_tier(self, id_from, id_to):
"""Rename a tier. Note that this renames also the child tiers that have
the tier as a parent.
:param str id_from: Original name of the tier.
:param str id_to: Target name of the tier.
:throws KeyError: If the tier doesnt' exist.
"""... | Rename a tier. Note that this renames also the child tiers that have
the tier as a parent.
:param str id_from: Original name of the tier.
:param str id_to: Target name of the tier.
:throws KeyError: If the tier doesnt' exist. |
def update_iscsi_settings(self, iscsi_data):
"""Update iscsi data
:param data: default iscsi config data
"""
self._conn.patch(self.path, data=iscsi_data) | Update iscsi data
:param data: default iscsi config data |
def groups_kick(self, room_id, user_id, **kwargs):
"""Removes a user from the private group."""
return self.__call_api_post('groups.kick', roomId=room_id, userId=user_id, kwargs=kwargs) | Removes a user from the private group. |
def mac_address_table_aging_time_conversational_time_out(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
mac_address_table = ET.SubElement(config, "mac-address-table", xmlns="urn:brocade.com:mgmt:brocade-mac-address-table")
aging_time = ET.SubElement(mac... | Auto Generated Code |
def get(self, request, *args, **kwargs):
"""Handler for HTTP GET requests."""
try:
context = self.get_context_data(**kwargs)
except exceptions.NotAvailable:
exceptions.handle(request)
self.set_workflow_step_errors(context)
return self.render_to_response(co... | Handler for HTTP GET requests. |
def instruction_list_to_easm(instruction_list: list) -> str:
"""Convert a list of instructions into an easm op code string.
:param instruction_list:
:return:
"""
result = ""
for instruction in instruction_list:
result += "{} {}".format(instruction["address"], instruction["opcode"])
... | Convert a list of instructions into an easm op code string.
:param instruction_list:
:return: |
def schedule_to_array(schedule, events, slots):
"""Convert a schedule from schedule to array form
Parameters
----------
schedule : list or tuple
of instances of :py:class:`resources.ScheduledItem`
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tu... | Convert a schedule from schedule to array form
Parameters
----------
schedule : list or tuple
of instances of :py:class:`resources.ScheduledItem`
events : list or tuple
of :py:class:`resources.Event` instances
slots : list or tuple
of :py:class:`resources.Slot` instances
... |
def calculate_integral(self, T1, T2):
r'''Method to compute the enthalpy integral of heat capacity from
`T1` to `T2`. Analytically integrates across the piecewise spline
as necessary.
Parameters
----------
T1 : float
Initial temperature, [K]
... | r'''Method to compute the enthalpy integral of heat capacity from
`T1` to `T2`. Analytically integrates across the piecewise spline
as necessary.
Parameters
----------
T1 : float
Initial temperature, [K]
T2 : float
Final temperature, ... |
def file_data(self):
"""Return Group file (only supported for Document and Report)."""
return {
'fileContent': self._file_content,
'fileName': self._group_data.get('fileName'),
'type': self._group_data.get('type'),
} | Return Group file (only supported for Document and Report). |
def bool(cls, must=None, should=None, must_not=None, minimum_number_should_match=None, boost=None):
'''
http://www.elasticsearch.org/guide/reference/query-dsl/bool-query.html
A query that matches documents matching boolean combinations of other queris. The bool query maps to Lucene BooleanQuery.... | http://www.elasticsearch.org/guide/reference/query-dsl/bool-query.html
A query that matches documents matching boolean combinations of other queris. The bool query maps to Lucene BooleanQuery. It is built using one of more boolean clauses, each clause with a typed occurrence. The occurrence types are:
'... |
def configure_profile(msg_type, profile_name, data, auth):
"""
Create the profile entry.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters
... | Create the profile entry.
Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:data: (dict) dict values for the 'settings'
:auth: (dict) auth parameters |
def base64url_decode(input):
"""Helper method to base64url_decode a string.
Args:
input (str): A base64url_encoded string to decode.
"""
rem = len(input) % 4
if rem > 0:
input += b'=' * (4 - rem)
return base64.urlsafe_b64decode(input) | Helper method to base64url_decode a string.
Args:
input (str): A base64url_encoded string to decode. |
def delete(self, uid):
"""Example DELETE method.
"""
try:
record = resource_db[uid].copy()
except KeyError:
return self.response_factory.not_found(errors=['Resource with UID {} does not exist!'])
del resource_db[uid]
return self.response_factory... | Example DELETE method. |
def load(controller=None, filename="", name=None, rsrc=None):
"Create the GUI objects defined in the resource (filename or python struct)"
# if no filename is given, search for the rsrc.py with the same module name:
if not filename and not rsrc:
if isinstance(controller, types.ClassType):
... | Create the GUI objects defined in the resource (filename or python struct) |
def _save_namepaths_bids_derivatives(self, f, tag, save_directory, suffix=None):
"""
Creates output directory and output name
Paramters
---------
f : str
input files, includes the file bids_suffix
tag : str
what should be added to f in the output ... | Creates output directory and output name
Paramters
---------
f : str
input files, includes the file bids_suffix
tag : str
what should be added to f in the output file.
save_directory : str
additional directory that the output file should go in... |
def _get_config_type(cla55: type) -> Optional[str]:
"""
Find the name (if any) that a subclass was registered under.
We do this simply by iterating through the registry until we
find it.
"""
# Special handling for pytorch RNN types:
if cla55 == torch.nn.RNN:
return "rnn"
elif cla... | Find the name (if any) that a subclass was registered under.
We do this simply by iterating through the registry until we
find it. |
def _set_policy(self, v, load=False):
"""
Setter method for policy, mapped from YANG variable /rbridge_id/maps/policy (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_policy is considered as a private
method. Backends looking to populate this variable should
... | Setter method for policy, mapped from YANG variable /rbridge_id/maps/policy (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_policy is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_policy() directly... |
def _get_benchmark_handler(self, last_trade, freq='minutely'):
'''
Setup a custom benchmark handler or let zipline manage it
'''
return LiveBenchmark(
last_trade, frequency=freq).surcharge_market_data \
if utils.is_live(last_trade) else None | Setup a custom benchmark handler or let zipline manage it |
def browseprofile(profilelog):
'''
Browse interactively a profile log in console
'''
print('Starting the pstats profile browser...\n')
try:
browser = ProfileBrowser(profilelog)
print >> browser.stream, "Welcome to the profile statistics browser. Type help to get started."
... | Browse interactively a profile log in console |
def _init_metadata(self):
"""stub"""
self._choices_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'choices'),
'element_label': 'Choices',
'instructions':... | stub |
def fmt_text(text, bg = None, fg = None, attr = None, plain = False):
"""
Apply given console formating around given text.
"""
if not plain:
if fg is not None:
text = TEXT_FORMATING['fg'][fg] + text
if bg is not None:
text = TEXT_FO... | Apply given console formating around given text. |
def find_root(self):
"""Finds the outermost context."""
node = self
while node.parent is not None:
node = node.parent
return node | Finds the outermost context. |
async def get(self, request):
"""Gets the user_id for the request.
Gets the ticket for the request using the get_ticket() function, and
authenticates the ticket.
Args:
request: aiohttp Request object.
Returns:
The userid for the request, or None if the ... | Gets the user_id for the request.
Gets the ticket for the request using the get_ticket() function, and
authenticates the ticket.
Args:
request: aiohttp Request object.
Returns:
The userid for the request, or None if the ticket is not
authenticated. |
def spare_disk(self, disk_xml=None):
""" Number of spare disk per type.
For example: storage.ontap.filer201.disk.SATA
"""
spare_disk = {}
disk_types = set()
for filer_disk in disk_xml:
disk_types.add(filer_disk.find('effective-disk-type').text)
... | Number of spare disk per type.
For example: storage.ontap.filer201.disk.SATA |
def get_resource(self, path):
"""Getting the required information from the API."""
response = self._http_request(path)
try:
return response.json()
except ValueError:
raise exception.ServiceException("Invalid service response.") | Getting the required information from the API. |
def scan_full(self, regex, return_string=True, advance_pointer=True):
"""
Match from the current position.
If `return_string` is false and a match is found, returns the number of
characters matched.
>>> s = Scanner("test string")
>>> s.scan_full(r' ')
... | Match from the current position.
If `return_string` is false and a match is found, returns the number of
characters matched.
>>> s = Scanner("test string")
>>> s.scan_full(r' ')
>>> s.scan_full(r'test ')
'test '
>>> s.pos
5
... |
def _lambert_ticks(ax, ticks, tick_location, line_constructor, tick_extractor):
"""Get the tick locations and labels for an axis of a Lambert Conformal projection."""
outline_patch = sgeom.LineString(ax.outline_patch.get_path().vertices.tolist())
axis = find_side(outline_patch, tick_location)
n_steps = ... | Get the tick locations and labels for an axis of a Lambert Conformal projection. |
def rpc_reply(id: Union[str, int], result: Optional[object],
warnings: Optional[List[Warning]] = None) -> rpcq.messages.RPCReply:
"""
Create RPC reply
:param str|int id: Request ID
:param result: Result
:param warnings: List of warnings to attach to the message
:return: JSON RPC f... | Create RPC reply
:param str|int id: Request ID
:param result: Result
:param warnings: List of warnings to attach to the message
:return: JSON RPC formatted dict |
def _combine_qc_samples(samples):
"""Combine split QC analyses into single samples based on BAM files.
"""
by_bam = collections.defaultdict(list)
for data in [utils.to_single_data(x) for x in samples]:
batch = dd.get_batch(data) or dd.get_sample_name(data)
if not isinstance(batch, (list,... | Combine split QC analyses into single samples based on BAM files. |
def fetch_from(self, year: int, month: int):
"""Fetch data from year, month to current year month data"""
self.raw_data = []
self.data = []
today = datetime.datetime.today()
for year, month in self._month_year_iter(month, year, today.month, today.year):
self.raw_data.... | Fetch data from year, month to current year month data |
def read_until_eof(self) -> bool:
"""Consume all the stream. Same as EOF in BNF."""
if self.read_eof():
return True
# TODO: read ALL
self._stream.save_context()
while not self.read_eof():
self._stream.incpos()
return self._stream.validate_context() | Consume all the stream. Same as EOF in BNF. |
def _get_9q_square_qvm(name: str, noisy: bool,
connection: ForestConnection = None,
qvm_type: str = 'qvm') -> QuantumComputer:
"""
A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do... | A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do vaguely interesting algorithms and small enough to simulate quickly.
:param name: The name of this QVM
:param connection: The connection to use to talk to external services
... |
def add_atoms_linearly(self, start_atom, end_atom, new_atoms, jitterbug = 0.2):
'''A low-level function which adds new_atoms between start_atom and end_atom. This function does not validate the
input i.e. the calling functions are responsible for ensuring that the insertion makes sense.
R... | A low-level function which adds new_atoms between start_atom and end_atom. This function does not validate the
input i.e. the calling functions are responsible for ensuring that the insertion makes sense.
Returns the PDB file content with the new atoms added. These atoms are given fresh serial nu... |
def _inplace_subset_var(self, index):
"""Inplace subsetting along variables dimension.
Same as ``adata = adata[:, index]``, but inplace.
"""
adata_subset = self[:, index].copy()
self._init_as_actual(adata_subset, dtype=self._X.dtype) | Inplace subsetting along variables dimension.
Same as ``adata = adata[:, index]``, but inplace. |
def add_result(self, result):
"""
Adds the result of a completed job to the result list, then decrements
the active job count. If the job set is already complete, the result is
simply discarded instead.
"""
if self._active_jobs == 0:
return
self._res... | Adds the result of a completed job to the result list, then decrements
the active job count. If the job set is already complete, the result is
simply discarded instead. |
def get_gene_modification_language(identifier_qualified: ParserElement) -> ParserElement:
"""Build a gene modification parser."""
gmod_identifier = MatchFirst([
identifier_qualified,
gmod_default_ns,
])
return gmod_tag + nest(
Group(gmod_identifier)(IDENTIFIER)
) | Build a gene modification parser. |
def add_ordered_combo_item(
combo, text, data=None, count_selected_features=None, icon=None):
"""Add a combo item ensuring that all items are listed alphabetically.
Although QComboBox allows you to set an InsertAlphabetically enum
this only has effect when a user interactively adds combo items to
... | Add a combo item ensuring that all items are listed alphabetically.
Although QComboBox allows you to set an InsertAlphabetically enum
this only has effect when a user interactively adds combo items to
an editable combo. This we have this little function to ensure that
combos are always sorted alphabeti... |
def parse_eprocess(self, eprocess_data):
"""Parse the EProcess object we get from some rekall output"""
Name = eprocess_data['_EPROCESS']['Cybox']['Name']
PID = eprocess_data['_EPROCESS']['Cybox']['PID']
PPID = eprocess_data['_EPROCESS']['Cybox']['Parent_PID']
return {'Name': Nam... | Parse the EProcess object we get from some rekall output |
def multilingual(request):
"""
Returns context variables containing information about available languages.
"""
codes = sorted(get_language_code_list())
return {'LANGUAGE_CODES': codes,
'LANGUAGE_CODES_AND_NAMES': [(c, LANG_DICT.get(c, c)) for c in codes],
'DEFAULT_LANGUAGE_C... | Returns context variables containing information about available languages. |
def config(data_folder=settings.data_folder,
logs_folder=settings.logs_folder,
imgs_folder=settings.imgs_folder,
cache_folder=settings.cache_folder,
use_cache=settings.use_cache,
log_file=settings.log_file,
log_console=settings.log_console,
lo... | Configure osmnx by setting the default global vars to desired values.
Parameters
---------
data_folder : string
where to save and load data files
logs_folder : string
where to write the log files
imgs_folder : string
where to save figures
cache_folder : string
wh... |
def _create_user(
self, username, email, short_name, full_name,
institute, password, is_admin, **extra_fields):
"""Creates a new active person. """
# Create Person
person = self.model(
username=username, email=email,
short_name=short_name, full_na... | Creates a new active person. |
def _iterparse(xmlfile):
"""
Avoid bug in python 3.{2,3}. See http://bugs.python.org/issue9257.
:param xmlfile: XML file or file-like object
"""
try:
return ET.iterparse(xmlfile, events=("start-ns", ))
except TypeError:
return ET.iterparse(xmlfile, events=(b"start-ns", )) | Avoid bug in python 3.{2,3}. See http://bugs.python.org/issue9257.
:param xmlfile: XML file or file-like object |
def graph_to_laplacian(G, normalized=True):
"""
Converts a graph from popular Python packages to Laplacian representation.
Currently support NetworkX, graph_tool and igraph.
Parameters
----------
G : obj
Input graph
normalized : bool
Whether to use normalized Laplacian.... | Converts a graph from popular Python packages to Laplacian representation.
Currently support NetworkX, graph_tool and igraph.
Parameters
----------
G : obj
Input graph
normalized : bool
Whether to use normalized Laplacian.
Normalized and unnormalized Laplacians capture ... |
def _state_invalid(self):
"""
If the state is invalid for the transition, return details on what didn't match
:return: Tuple of (state manager, current state, label for current state)
"""
for statemanager, conditions in self.statetransition.transitions.items():
curre... | If the state is invalid for the transition, return details on what didn't match
:return: Tuple of (state manager, current state, label for current state) |
def _find_scc(self):
"""
Set ``self._num_scc`` and ``self._scc_proj``
by calling ``scipy.sparse.csgraph.connected_components``:
* docs.scipy.org/doc/scipy/reference/sparse.csgraph.html
* github.com/scipy/scipy/blob/master/scipy/sparse/csgraph/_traversal.pyx
``self._scc_p... | Set ``self._num_scc`` and ``self._scc_proj``
by calling ``scipy.sparse.csgraph.connected_components``:
* docs.scipy.org/doc/scipy/reference/sparse.csgraph.html
* github.com/scipy/scipy/blob/master/scipy/sparse/csgraph/_traversal.pyx
``self._scc_proj`` is a list of length `n` that assign... |
def reset(cls):
"""Resets the static state. Should only be called by tests."""
cls.stats = StatContainer()
cls.parentMap = {}
cls.containerMap = {}
cls.subId = 0
for stat in gc.get_objects():
if isinstance(stat, Stat):
stat._aggregators = {} | Resets the static state. Should only be called by tests. |
def off_datastream(self, datastream):
"""
To turn off datastream
:param datastream: string
"""
url = '/datastream/' + str(datastream) + '/off'
response = self.http.post(url,"")
return response | To turn off datastream
:param datastream: string |
def drop_indexes(self):
"""Drops all indexes on this collection.
Can be used on non-existant collections or collections with no indexes.
Raises OperationFailure on an error.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automaticall... | Drops all indexes on this collection.
Can be used on non-existant collections or collections with no indexes.
Raises OperationFailure on an error.
.. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
this collection is automatically applied to this operation when us... |
def load(text, match=None):
"""This function reads a string that contains the XML of an Atom Feed, then
returns the
data in a native Python structure (a ``dict`` or ``list``). If you also
provide a tag name or path to match, only the matching sub-elements are
loaded.
:param text: The XML te... | This function reads a string that contains the XML of an Atom Feed, then
returns the
data in a native Python structure (a ``dict`` or ``list``). If you also
provide a tag name or path to match, only the matching sub-elements are
loaded.
:param text: The XML text to load.
:type text: ``strin... |
def add_attribute(self, ont_id: str, ctrl_acct: Account, attributes: Attribute, payer: Account, gas_limit: int,
gas_price: int) -> str:
"""
This interface is used to send a Transaction object which is used to add attribute.
:param ont_id: OntId.
:param ctrl_acct: a... | This interface is used to send a Transaction object which is used to add attribute.
:param ont_id: OntId.
:param ctrl_acct: an Account object which indicate who will sign for the transaction.
:param attributes: a list of attributes we want to add.
:param payer: an Account object which i... |
def simplify_basic(drawing, process=False, **kwargs):
"""
Merge colinear segments and fit circles.
Parameters
-----------
drawing: Path2D object, will not be modified.
Returns
-----------
simplified: Path2D with circles.
"""
if any(i.__class__.__name__ != 'Line'
for... | Merge colinear segments and fit circles.
Parameters
-----------
drawing: Path2D object, will not be modified.
Returns
-----------
simplified: Path2D with circles. |
def genotypesPhenotypesGenerator(self, request):
"""
Returns a generator over the (phenotypes, nextPageToken) pairs
defined by the (JSON string) request
"""
# TODO make paging work using SPARQL?
compoundId = datamodel.PhenotypeAssociationSetCompoundId.parse(
r... | Returns a generator over the (phenotypes, nextPageToken) pairs
defined by the (JSON string) request |
def compare(s1, s2, **kwargs):
"""Compares two strings and returns their similarity.
:param s1: first string
:param s2: second string
:param kwargs: additional keyword arguments passed to __init__.
:return: similarity between 0.0 and 1.0.
>>> from ngram import NGram
... | Compares two strings and returns their similarity.
:param s1: first string
:param s2: second string
:param kwargs: additional keyword arguments passed to __init__.
:return: similarity between 0.0 and 1.0.
>>> from ngram import NGram
>>> NGram.compare('spa', 'spam')
... |
def main( gpu:Param("GPU to run on", str)=None ):
"""Distrubuted training of CIFAR-10.
Fastest speed is if you run as follows:
python -m fastai.launch train_cifar.py"""
gpu = setup_distrib(gpu)
n_gpus = num_distrib()
path = url2path(URLs.CIFAR)
ds_tfms = ([*rand_pad(4, 32), flip_lr(p=0.5... | Distrubuted training of CIFAR-10.
Fastest speed is if you run as follows:
python -m fastai.launch train_cifar.py |
def __getListMetaInfo(self, inferenceElement):
""" Get field metadata information for inferences that are of list type
TODO: Right now we assume list inferences are associated with the input field
metadata
"""
fieldMetaInfo = []
inferenceLabel = InferenceElement.getLabel(inferenceElement)
f... | Get field metadata information for inferences that are of list type
TODO: Right now we assume list inferences are associated with the input field
metadata |
def refetch_fields(self, missing_fields):
""" Refetches a list of fields from the DB """
db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields})
self._fetched_fields += tuple(missing_fields)
if not db_fields:
return
... | Refetches a list of fields from the DB |
def loads(s, cls=BinaryQuadraticModel, vartype=None):
"""Load a COOrdinate formatted binary quadratic model from a string."""
return load(s.split('\n'), cls=cls, vartype=vartype) | Load a COOrdinate formatted binary quadratic model from a string. |
def underscores_to_camelcase(argument):
''' Converts a camelcase param like the_new_attribute to the equivalent
camelcase version like theNewAttribute. Note that the first letter is
NOT capitalized by this function '''
result = ''
previous_was_underscore = False
for char in argument:
if ... | Converts a camelcase param like the_new_attribute to the equivalent
camelcase version like theNewAttribute. Note that the first letter is
NOT capitalized by this function |
def get_fn(elev, name=None):
"""
Determines the standard filename for a given GeoTIFF Layer.
Parameters
-----------
elev : GdalReader.raster_layer
A raster layer from the GdalReader object.
name : str (optional)
An optional suffix to the filename.
Returns
-------
fn ... | Determines the standard filename for a given GeoTIFF Layer.
Parameters
-----------
elev : GdalReader.raster_layer
A raster layer from the GdalReader object.
name : str (optional)
An optional suffix to the filename.
Returns
-------
fn : str
The standard <filename>_<na... |
async def _verkey_for(self, target: str) -> str:
"""
Given a DID, retrieve its verification key, looking in wallet, then pool.
Given a verification key or None, return input.
Raise WalletState if the wallet is closed. Given a recipient DID not in the wallet,
raise AbsentPool if ... | Given a DID, retrieve its verification key, looking in wallet, then pool.
Given a verification key or None, return input.
Raise WalletState if the wallet is closed. Given a recipient DID not in the wallet,
raise AbsentPool if the instance has no pool or ClosedPool if its pool is closed.
... |
def parse(content, *args, **kwargs):
''' Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed '''
global MECAB_PYTHON3
if 'mecab_loc' not in kwargs and MECAB_PYTHON3 and 'MeCab' in globals():
return MeCab.Tagger(*args).parse(content)
else:
return r... | Use mecab-python3 by default to parse JP text. Fall back to mecab binary app if needed |
def get_posix(self, i):
"""Get POSIX."""
index = i.index
value = ['[']
try:
c = next(i)
if c != ':':
raise ValueError('Not a valid property!')
else:
value.append(c)
c = next(i)
if c == '^... | Get POSIX. |
def repeat(self, count=2):
""" Repeat the last control code a number of times.
Returns a new Control with this one's data and the repeated code.
"""
# Subtracting one from the count means the code mentioned is
# truly repeated exactly `count` times.
# Control().move_u... | Repeat the last control code a number of times.
Returns a new Control with this one's data and the repeated code. |
def shell():
"Open a shell"
from gui.tools.debug import Shell
shell = Shell()
shell.show()
return shell | Open a shell |
def filter(self, table, cg_snapshots, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [cg_snapshot for cg_snapshot in cg_snapshots
if query in cg_snapshot.name.lower()] | Naive case-insensitive search. |
def put (self, ch):
'''This puts a characters at the current cursor position.
'''
if isinstance(ch, bytes):
ch = self._decode(ch)
self.put_abs (self.cur_r, self.cur_c, ch) | This puts a characters at the current cursor position. |
def print_summary(graph, tails, node_id_map):
"""Print out summary and per-node comparison data."""
# Get comparison data
heads = get_heads(tails)
heights = get_heights(tails)
max_height = max(heights)
common_height, block_ids_at_common_height = get_common_height(tails)
lags = get_lags(heigh... | Print out summary and per-node comparison data. |
def sendSMS_multi(self, CorpNum, Sender, Contents, Messages, reserveDT, adsYN=False, UserID=None, RequestNum=None):
""" ๋จ๋ฌธ ๋ฌธ์๋ฉ์์ง ๋ค๋์ ์ก
args
CorpNum : ํ๋นํ์ ์ฌ์
์๋ฒํธ
Sender : ๋ฐ์ ์๋ฒํธ (๋๋ณด์ ์ก์ฉ)
Contents : ๋ฌธ์ ๋ด์ฉ (๋๋ณด์ ์ก์ฉ)
Messages : ๊ฐ๋ณ์ ์ก์ ๋ณด ๋ฐฐ์ด
... | ๋จ๋ฌธ ๋ฌธ์๋ฉ์์ง ๋ค๋์ ์ก
args
CorpNum : ํ๋นํ์ ์ฌ์
์๋ฒํธ
Sender : ๋ฐ์ ์๋ฒํธ (๋๋ณด์ ์ก์ฉ)
Contents : ๋ฌธ์ ๋ด์ฉ (๋๋ณด์ ์ก์ฉ)
Messages : ๊ฐ๋ณ์ ์ก์ ๋ณด ๋ฐฐ์ด
reserveDT : ์์ฝ์ ์ก์๊ฐ (ํ์. yyyyMMddHHmmss)
UserID : ํ๋นํ์ ์์ด๋
RequestNum : ์ ์ก์์ฒญ๋ฒํธ
... |
def get_bounce_dump(bounce_id, api_key=None, secure=None, test=None,
**request_args):
'''Get the raw email dump for a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:par... | Get the raw email dump for a single bounce.
:param bounce_id: The bounce's id. Get the id with :func:`get_bounces`.
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postmar... |
def enable_events(self):
"""enable slow wave and spindle detection if both
annotations and channels are active.
"""
if self.annot is not None and self.parent.channels.groups:
self.action['spindle'].setEnabled(True)
self.action['slow_wave'].setEnabled(True)
... | enable slow wave and spindle detection if both
annotations and channels are active. |
def tie_weights(self):
""" Run this to be sure output and input (adaptive) softmax weights are tied """
# sampled softmax
if self.sample_softmax > 0:
if self.config.tie_weight:
self.out_layer.weight = self.transformer.word_emb.weight
# adaptive softmax (includ... | Run this to be sure output and input (adaptive) softmax weights are tied |
def get_status(self):
""" Query the device status. Returns JSON of the device internal state """
url = self.base_url + '/status'
try:
r = requests.get(url, timeout=10)
return r.json()
except RequestException as err:
raise Client.ClientError(err) | Query the device status. Returns JSON of the device internal state |
def decode_body(cls, header, f):
"""Generates a `MqttUnsuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsuback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Rais... | Generates a `MqttUnsuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsuback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def get_bucket_lifecycle(self, bucket):
"""
Get the lifecycle configuration of a bucket.
@param bucket: The name of the bucket.
@return: A C{Deferred} that will fire with the bucket's lifecycle
configuration.
"""
details = self._details(
method=b"GET"... | Get the lifecycle configuration of a bucket.
@param bucket: The name of the bucket.
@return: A C{Deferred} that will fire with the bucket's lifecycle
configuration. |
def open(self, path, mode='r'):
"""Open stream, returning ``Stream`` object"""
entry = self.find(path)
if entry is None:
if mode == 'r':
raise ValueError("stream does not exists: %s" % path)
entry = self.create_dir_entry(path, 'stream', None)
els... | Open stream, returning ``Stream`` object |
def value_to_string(self, obj):
"""Convert a field value to a string.
Returns the state name.
"""
statefield = self.to_python(self.value_from_object(obj))
return statefield.state.name | Convert a field value to a string.
Returns the state name. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.