positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def on_select(self, item, action):
"""
Add an action to make when an object is selected.
Only one action can be stored this way.
"""
if not isinstance(item, int):
item = self.items.index(item)
self._on_select[item] = action | Add an action to make when an object is selected.
Only one action can be stored this way. |
def Remove(self, row):
"""Removes a row from the table.
Args:
row: int, the row number to delete. Must be >= 1, as the header
cannot be removed.
Raises:
TableError: Attempt to remove nonexistent or header row.
"""
if row == 0 or row > self.size:
raise TableE... | Removes a row from the table.
Args:
row: int, the row number to delete. Must be >= 1, as the header
cannot be removed.
Raises:
TableError: Attempt to remove nonexistent or header row. |
def _TypecheckFunction(function, parent_type_check_dict, stack_location,
self_name):
"""Decorator function to collect and execute type checks."""
type_check_dict = _CollectTypeChecks(function, parent_type_check_dict,
stack_location + 1, self_name)
if not... | Decorator function to collect and execute type checks. |
def close(self):
"""Closes the record file."""
if not self.is_open:
return
if self.writable:
check_call(_LIB.MXRecordIOWriterFree(self.handle))
else:
check_call(_LIB.MXRecordIOReaderFree(self.handle))
self.is_open = False
self.pid = Non... | Closes the record file. |
def _str_member_list(self, name):
"""
Generate a member listing, autosummary:: table where possible,
and a table where not.
"""
out = []
if self[name]:
out += ['.. rubric:: %s' % name, '']
prefix = getattr(self, '_name', '')
if prefix... | Generate a member listing, autosummary:: table where possible,
and a table where not. |
def managed_sans(self):
"""
Gets the Managed SANs API client.
Returns:
ManagedSANs:
"""
if not self.__managed_sans:
self.__managed_sans = ManagedSANs(self.__connection)
return self.__managed_sans | Gets the Managed SANs API client.
Returns:
ManagedSANs: |
def set_snapshots(self,snapshots):
"""
Set the snapshots and reindex all time-dependent data.
This will reindex all pandas.Panels of time-dependent data; NaNs are filled
with the default value for that quantity.
Parameters
----------
snapshots : list or pandas.I... | Set the snapshots and reindex all time-dependent data.
This will reindex all pandas.Panels of time-dependent data; NaNs are filled
with the default value for that quantity.
Parameters
----------
snapshots : list or pandas.Index
All time steps.
Returns
... |
def update(self, event_or_list):
"""Update the text and position of cursor according to the event passed."""
event_or_list = super().update(event_or_list)
for e in event_or_list:
if e.type == KEYDOWN:
if e.key == K_RIGHT:
if e.mod * KMOD_CTRL:
... | Update the text and position of cursor according to the event passed. |
def plot_temp_diagrams(config, results, temp_dir):
"""Plot temporary diagrams"""
display_name = {
'time': 'Compilation time (s)',
'memory': 'Compiler memory usage (MB)',
}
files = config['files']
img_files = []
if any('slt' in result for result in results) and 'bmp' in files.va... | Plot temporary diagrams |
def terminate(self):
'''Stop the server process and change our state to TERMINATING. Only valid if state=READY.'''
logger.debug('client.terminate() called (state=%s)', self.strstate)
if self.state == ClientState.WAITING_FOR_RESULT:
raise ClientStateError('terimate() called while stat... | Stop the server process and change our state to TERMINATING. Only valid if state=READY. |
def get_default_physical_units(interface_mode=None):
"""Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au,... | Return physical units used for calculators
Physical units: energy, distance, atomic mass, force
vasp : eV, Angstrom, AMU, eV/Angstrom
wien2k : Ry, au(=borh), AMU, mRy/au
abinit : hartree, au, AMU, eV/Angstrom
elk : hartree... |
def store(self):
'''
Record the current value of each variable X named in track_vars in an
attribute named X_hist.
Parameters
----------
none
Returns
-------
none
'''
for var_name in self.track_vars:
value_now = getatt... | Record the current value of each variable X named in track_vars in an
attribute named X_hist.
Parameters
----------
none
Returns
-------
none |
def data(item=None, show_doc=False):
"""loads a datasaet (from in-modules datasets) in a dataframe data structure.
Args:
item (str) : name of the dataset to load.
show_doc (bool) : to show the dataset's documentation.
Examples:
>>> iris = data('iris')
>>> data('titanic', sh... | loads a datasaet (from in-modules datasets) in a dataframe data structure.
Args:
item (str) : name of the dataset to load.
show_doc (bool) : to show the dataset's documentation.
Examples:
>>> iris = data('iris')
>>> data('titanic', show_doc=True)
: returns the dataset's... |
def previous(self, rows: List[Row]) -> List[Row]:
"""
Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list.
"""
if not... | Takes an expression that evaluates to a single row, and returns the row that occurs before
the input row in the original set of rows. If the input row happens to be the top row, we
will return an empty list. |
def expand_user(path, user=None):
"""Roughly the same as os.path.expanduser, but you can pass a default user."""
def _replace(m):
m_user = m.group(1) or user
return pwd.getpwnam(m_user).pw_dir if m_user else pwd.getpwuid(os.getuid()).pw_dir
return re.sub(r'~(\w*)', _replace, path) | Roughly the same as os.path.expanduser, but you can pass a default user. |
def read_content(self):
"""Return data and data size for this URL.
Can be overridden in subclasses."""
maxbytes = self.aggregate.config["maxfilesizedownload"]
buf = StringIO()
for data in self.url_connection.iter_content(chunk_size=self.ReadChunkBytes):
if buf.tell() ... | Return data and data size for this URL.
Can be overridden in subclasses. |
def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):
"""
internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly.
"""
fmt = u("{%s}")
pairs = []
pfmt = u("%s: %s")
if max_seq_items is False:
nitems = len(seq)
els... | internal. pprinter for iterables. you should probably use pprint_thing()
rather then calling this directly. |
def _end_apply_index(self, dtindex):
"""
Add self to the given DatetimeIndex, specialized for case where
self.weekday is non-null.
Parameters
----------
dtindex : DatetimeIndex
Returns
-------
result : DatetimeIndex
"""
off = dtin... | Add self to the given DatetimeIndex, specialized for case where
self.weekday is non-null.
Parameters
----------
dtindex : DatetimeIndex
Returns
-------
result : DatetimeIndex |
def save(self, *args, **kwargs):
"""
This save method protects against two processesses concurrently modifying
the same object. Normally the second save would silently overwrite the
changes from the first. Instead we raise a ConcurrentModificationError.
"""
cls = self.__c... | This save method protects against two processesses concurrently modifying
the same object. Normally the second save would silently overwrite the
changes from the first. Instead we raise a ConcurrentModificationError. |
def load_toml_validator_config(filename):
"""Returns a ValidatorConfig created by loading a TOML file from the
filesystem.
"""
if not os.path.exists(filename):
LOGGER.info(
"Skipping validator config loading from non-existent config file:"
" %s", filename)
return ... | Returns a ValidatorConfig created by loading a TOML file from the
filesystem. |
def decode(cls, auth_header: str, encoding: str='latin1') -> 'BasicAuth':
"""Create a BasicAuth object from an Authorization HTTP header."""
try:
auth_type, encoded_credentials = auth_header.split(' ', 1)
except ValueError:
raise ValueError('Could not parse authorization ... | Create a BasicAuth object from an Authorization HTTP header. |
def get_ioos_def(self, ident, elem_type, ont):
"""Gets a definition given an identifier and where to search for it"""
if elem_type == "identifier":
getter_fn = self.system.get_identifiers_by_name
elif elem_type == "classifier":
getter_fn = self.system.get_classifiers_by_n... | Gets a definition given an identifier and where to search for it |
def drop_all(self, queue_name):
"""
Drops all the task in the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
"""
cls = self.__class__
for task_id in cls.queues.get(queue_name, []):... | Drops all the task in the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string |
def _gen_weldobj(self, arr):
'''
Generating a new weldarray from a given arr for self.
@arr: weldarray or ndarray.
- weldarray: Just update the weldobject with the context from the
weldarray.
- ndarray: Add the given array to the context of the weldobject.
... | Generating a new weldarray from a given arr for self.
@arr: weldarray or ndarray.
- weldarray: Just update the weldobject with the context from the
weldarray.
- ndarray: Add the given array to the context of the weldobject.
Sets self.name and self.weldobj. |
def clean_dir(root):
'''remove .* and _* files and directories under root'''
for x in root.walkdirs('.*', errors='ignore'):
x.rmtree()
for x in root.walkdirs('_*', errors='ignore'):
x.rmtree()
for x in root.walkfiles('.*', errors='ignore'):
x.remove()
for x in root.walkfiles... | remove .* and _* files and directories under root |
def _handle_getconfig(self,cfg_file,*args,**options):
"""Command 'supervisor getconfig' prints merged config to stdout."""
if args:
raise CommandError("supervisor getconfig takes no arguments")
print cfg_file.read()
return 0 | Command 'supervisor getconfig' prints merged config to stdout. |
def add_to_fileswitcher(self, plugin, tabs, data, icon):
"""Add a plugin to the File Switcher."""
if self.fileswitcher is None:
from spyder.widgets.fileswitcher import FileSwitcher
self.fileswitcher = FileSwitcher(self, plugin, tabs, data, icon)
else:
se... | Add a plugin to the File Switcher. |
def read_wavefront(fname_obj):
"""Returns mesh dictionary along with their material dictionary from a wavefront (.obj and/or .mtl) file."""
fname_mtl = ''
geoms = read_objfile(fname_obj)
for line in open(fname_obj):
if line:
split_line = line.strip().split(' ', 1)
if len(... | Returns mesh dictionary along with their material dictionary from a wavefront (.obj and/or .mtl) file. |
def merge(blocks):
"""Merge the given blocks into a contiguous block of compressed data.
:param blocks: the list of blocks
:rtype: a list of compressed bytes
"""
current_block = blocks[sorted(blocks.keys())[0]]
compressed_data = []
eof = False
while not eof:
data_size_to_appe... | Merge the given blocks into a contiguous block of compressed data.
:param blocks: the list of blocks
:rtype: a list of compressed bytes |
def open_array(store=None, mode='a', shape=None, chunks=True, dtype=None,
compressor='default', fill_value=0, order='C', synchronizer=None,
filters=None, cache_metadata=True, cache_attrs=True, path=None,
object_codec=None, chunk_store=None, **kwargs):
"""Open an array us... | Open an array using file-mode-like semantics.
Parameters
----------
store : MutableMapping or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
... |
def address_families_for_dir(cls, address_families_dict, spec_dir_path):
"""Implementation of `matching_address_families()` for specs matching at most one directory."""
maybe_af = address_families_dict.get(spec_dir_path, None)
if maybe_af is None:
raise cls.AddressFamilyResolutionError(
'Path ... | Implementation of `matching_address_families()` for specs matching at most one directory. |
def tokenize(self, text: str, customize=True, disable=[]) -> List[Token]:
"""
Tokenize the given text, returning a list of tokens. Type token: class spacy.tokens.Token
Args:
text (string):
Returns: [tokens]
"""
"""Tokenize text"""
if not self.keep_... | Tokenize the given text, returning a list of tokens. Type token: class spacy.tokens.Token
Args:
text (string):
Returns: [tokens] |
def check_value(
config,
section,
option,
jinja_pattern=JINJA_PATTERN,
):
"""try to figure out if value is valid or jinja2 template value
Args:
config (:obj:`configparser.ConfigParser`): config object to read key from
section (str): name of section in configparse... | try to figure out if value is valid or jinja2 template value
Args:
config (:obj:`configparser.ConfigParser`): config object to read key from
section (str): name of section in configparser
option (str): name of option in configparser
jinja_pattern (:obj:`_sre.SRE_Pattern`): a `re.com... |
def from_array(array):
"""
Deserialize a new MaskPosition from a given dictionary.
:return: new MaskPosition instance.
:rtype: MaskPosition
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_nam... | Deserialize a new MaskPosition from a given dictionary.
:return: new MaskPosition instance.
:rtype: MaskPosition |
def list(self, kind, tag_slug, cur_p=''):
'''
根据 cat_handler.py 中的 def view_cat_new(self, cat_slug, cur_p = '')
'''
# 下面用来使用关键字过滤信息,如果网站信息量不是很大不要开启
# Todo:
# if self.get_current_user():
# redisvr.sadd(config.redis_kw + self.userinfo.user_name, tag_slug)
... | 根据 cat_handler.py 中的 def view_cat_new(self, cat_slug, cur_p = '') |
def errorFunction(self, t, a):
"""
Using a hyperbolic arctan on the error slightly exaggerates
the actual error non-linearly. Return t - a to just use the difference.
t - target vector
a - activation vector
"""
def difference(v):
if not self.hyperbolic... | Using a hyperbolic arctan on the error slightly exaggerates
the actual error non-linearly. Return t - a to just use the difference.
t - target vector
a - activation vector |
def deserialize(data):
""" Deserialize `data` to an exception instance.
If the `exc_path` value matches an exception registered as
``deserializable``, return an instance of that exception type.
Otherwise, return a `RemoteError` instance describing the exception
that occurred.
"""
key = data... | Deserialize `data` to an exception instance.
If the `exc_path` value matches an exception registered as
``deserializable``, return an instance of that exception type.
Otherwise, return a `RemoteError` instance describing the exception
that occurred. |
def _populate_random_tournament_row_col(n, r, row, col):
"""
Populate ndarrays `row` and `col` with directed edge indices
determined by random numbers in `r` for a tournament graph with n
nodes, which has num_edges = n * (n-1) // 2 edges.
Parameters
----------
n : scalar(int)
Number... | Populate ndarrays `row` and `col` with directed edge indices
determined by random numbers in `r` for a tournament graph with n
nodes, which has num_edges = n * (n-1) // 2 edges.
Parameters
----------
n : scalar(int)
Number of nodes.
r : ndarray(float, ndim=1)
ndarray of length ... |
async def status(self) -> JobStatus:
"""
Status of the job.
"""
if await self._redis.exists(result_key_prefix + self.job_id):
return JobStatus.complete
elif await self._redis.exists(in_progress_key_prefix + self.job_id):
return JobStatus.in_progress
... | Status of the job. |
def vlag_commit_mode_disable(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vlag_commit_mode = ET.SubElement(config, "vlag-commit-mode", xmlns="urn:brocade.com:mgmt:brocade-lacp")
disable = ET.SubElement(vlag_commit_mode, "disable")
callback = ... | Auto Generated Code |
def del_record(self, dns_record_type, host):
"""Remove a DNS record"""
rec = self.get_record(dns_record_type, host)
if rec:
self._entries = list(set(self._entries) - set([rec]))
return True | Remove a DNS record |
def write_strings_on_files_between_markers(filenames: list, strings: list,
marker: str):
r"""Write the table of contents on multiple files.
:parameter filenames: the files that needs to be read or modified.
:parameter strings: the strings that will be written on t... | r"""Write the table of contents on multiple files.
:parameter filenames: the files that needs to be read or modified.
:parameter strings: the strings that will be written on the file. Each
string is associated with one file.
:parameter marker: a marker that will identify the start
and the... |
def lambda_handler(event, context):
'''A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics.'''
raw_kpl_records = event['records']
output = [process_kpl_record(kpl_record) for kpl_record in raw_kpl_records]
# Print number of successful and failed records.
success_coun... | A Python AWS Lambda function to process aggregated records sent to KinesisAnalytics. |
def getWindowByTitle(self, wildcard, order=0):
""" Returns a handle for the first window that matches the provided "wildcard" regex """
for w in self._get_window_list():
if "kCGWindowName" in w and re.search(wildcard, w["kCGWindowName"], flags=re.I):
# Matches - make sure we ... | Returns a handle for the first window that matches the provided "wildcard" regex |
def enable(self, trigger_ids=[]):
"""
Enable triggers.
:param trigger_ids: List of trigger definition ids to enable
"""
trigger_ids = ','.join(trigger_ids)
url = self._service_url(['triggers', 'enabled'], params={'triggerIds': trigger_ids, 'enabled': 'true'})
sel... | Enable triggers.
:param trigger_ids: List of trigger definition ids to enable |
def notify(self, data):
"""Notify this observer that data has arrived"""
LOG.debug('notify received: %s', data)
self._notify_count += 1
if self._cancelled:
LOG.debug('notify skipping due to `cancelled`')
return self
if self._once_done and self._once:
... | Notify this observer that data has arrived |
def get_value_from_environment(
section_name,
key_name,
envname_pad=ENVNAME_PAD,
logger=logging.getLogger('ProsperCommon'),
):
"""check environment for key/value pair
Args:
section_name (str): section name
key_name (str): key to look up
envname_pad (str):... | check environment for key/value pair
Args:
section_name (str): section name
key_name (str): key to look up
envname_pad (str): namespace padding
logger (:obj:`logging.logger`): logging handle
Returns:
str: value in environment |
def guess_autoescape(self, template_name):
"""Given a template Name I will gues using its
extension if we should autoscape or not.
Default autoscaped extensions: ('html', 'xhtml', 'htm', 'xml')
"""
if template_name is None or '.' not in template_name:
return False
... | Given a template Name I will gues using its
extension if we should autoscape or not.
Default autoscaped extensions: ('html', 'xhtml', 'htm', 'xml') |
def _prepare_job(request, candidates):
"""
Creates a temporary directory, move uploaded files there and
select the job file by looking at the candidate names.
:returns: full path of the job_file
"""
temp_dir = tempfile.mkdtemp()
inifiles = []
arch = request.FILES.get('archive')
if a... | Creates a temporary directory, move uploaded files there and
select the job file by looking at the candidate names.
:returns: full path of the job_file |
def start_with(self, request):
"""Start the crawler using the given request.
Args:
request (:class:`nyawc.http.Request`): The startpoint for the crawler.
"""
HTTPRequestHelper.patch_with_options(request, self.__options)
self.queue.add_request(request)
self... | Start the crawler using the given request.
Args:
request (:class:`nyawc.http.Request`): The startpoint for the crawler. |
def _do_digest(data, func):
"""Return the binary digest of `data` with the given `func`."""
func = FuncReg.get(func)
hash = FuncReg.hash_from_func(func)
if not hash:
raise ValueError("no available hash function for hash", func)
hash.update(data)
return bytes(hash.digest()) | Return the binary digest of `data` with the given `func`. |
def map_vp(self, port1, vpi1, port2, vpi2):
"""
Creates a new Virtual Path connection.
:param port1: input port
:param vpi1: input vpi
:param port2: output port
:param vpi2: output vpi
"""
if port1 not in self._nios:
return
if port2 ... | Creates a new Virtual Path connection.
:param port1: input port
:param vpi1: input vpi
:param port2: output port
:param vpi2: output vpi |
def append(self, other):
"""
Add the rows of an SFrame to the end of this SFrame.
Both SFrames must have the same set of columns with the same column
names and column types.
Parameters
----------
other : SFrame
Another SFrame whose rows are appended ... | Add the rows of an SFrame to the end of this SFrame.
Both SFrames must have the same set of columns with the same column
names and column types.
Parameters
----------
other : SFrame
Another SFrame whose rows are appended to the current SFrame.
Returns
... |
def cvxEDA(eda, sampling_rate=1000, tau0=2., tau1=0.7, delta_knot=10., alpha=8e-4, gamma=1e-2, solver=None, verbose=False, options={'reltol':1e-9}):
"""
A convex optimization approach to electrodermal activity processing (CVXEDA).
This function implements the cvxEDA algorithm described in "cvxEDA: a
Co... | A convex optimization approach to electrodermal activity processing (CVXEDA).
This function implements the cvxEDA algorithm described in "cvxEDA: a
Convex Optimization Approach to Electrodermal Activity Processing" (Greco et al., 2015).
Parameters
----------
eda : list or array
raw E... |
def halt(self):
"""Halts the CPU Core.
Args:
self (JLink): the ``JLink`` instance
Returns:
``True`` if halted, ``False`` otherwise.
"""
res = int(self._dll.JLINKARM_Halt())
if res == 0:
time.sleep(1)
return True
return... | Halts the CPU Core.
Args:
self (JLink): the ``JLink`` instance
Returns:
``True`` if halted, ``False`` otherwise. |
def _folder_item_reflex_icons(self, analysis_brain, item):
"""Adds an icon to the item dictionary if the analysis has been
automatically generated due to a reflex rule
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents ... | Adds an icon to the item dictionary if the analysis has been
automatically generated due to a reflex rule
:param analysis_brain: Brain that represents an analysis
:param item: analysis' dictionary counterpart that represents a row |
def load(cls, path):
"""Create a new MLPipeline from a JSON specification.
The JSON file format is the same as the one created by the `to_dict` method.
Args:
path (str): Path of the JSON file to load.
Returns:
MLPipeline:
A new MLPipeline instan... | Create a new MLPipeline from a JSON specification.
The JSON file format is the same as the one created by the `to_dict` method.
Args:
path (str): Path of the JSON file to load.
Returns:
MLPipeline:
A new MLPipeline instance with the specification found
... |
def version():
""" Print the current version and exit. """
from topydo.lib.Version import VERSION, LICENSE
print("topydo {}\n".format(VERSION))
print(LICENSE)
sys.exit(0) | Print the current version and exit. |
def reactions_to_files(model, dest, writer, split_subsystem):
"""Turn the reaction subsystems into their own files.
If a subsystem has a number of reactions over the threshold, it gets its
own YAML file. All other reactions, those that don't have a subsystem or
are in a subsystem that falls below the t... | Turn the reaction subsystems into their own files.
If a subsystem has a number of reactions over the threshold, it gets its
own YAML file. All other reactions, those that don't have a subsystem or
are in a subsystem that falls below the threshold, get added to a common
reaction file.
Args:
... |
def set_hs_color(self, hue: float, saturation: float):
"""
Set a fixed color and also turn off effects in order to see the color.
:param hue: Hue component (range 0-1)
:param saturation: Saturation component (range 0-1). Yields white for values near 0, other values are
inter... | Set a fixed color and also turn off effects in order to see the color.
:param hue: Hue component (range 0-1)
:param saturation: Saturation component (range 0-1). Yields white for values near 0, other values are
interpreted as 100% saturation.
The input values are the components of ... |
def decode(self, s):
"""
Decode special characters encodings found in string I{s}.
@param s: A string to decode.
@type s: str
@return: The decoded string.
@rtype: str
"""
if isinstance(s, str) and '&' in s:
for x in self.decodings:
... | Decode special characters encodings found in string I{s}.
@param s: A string to decode.
@type s: str
@return: The decoded string.
@rtype: str |
def shutdown(exiting_interpreter=False):
"""Disconnect the worker, and terminate processes started by ray.init().
This will automatically run at the end when a Python process that uses Ray
exits. It is ok to run this twice in a row. The primary use case for this
function is to cleanup state between tes... | Disconnect the worker, and terminate processes started by ray.init().
This will automatically run at the end when a Python process that uses Ray
exits. It is ok to run this twice in a row. The primary use case for this
function is to cleanup state between tests.
Note that this will clear any remote fu... |
def arg_string_from_dict(arg_dict, **kwds):
"""
This function takes a series of ditionaries and creates an argument
string for a graphql query
"""
# the filters dictionary
filters = {
**arg_dict,
**kwds,
}
# return the correctly formed string
return ", ".join(... | This function takes a series of ditionaries and creates an argument
string for a graphql query |
def _from_inferred_categories(cls, inferred_categories, inferred_codes,
dtype, true_values=None):
"""
Construct a Categorical from inferred values.
For inferred categories (`dtype` is None) the categories are sorted.
For explicit `dtype`, the `inferred_... | Construct a Categorical from inferred values.
For inferred categories (`dtype` is None) the categories are sorted.
For explicit `dtype`, the `inferred_categories` are cast to the
appropriate type.
Parameters
----------
inferred_categories : Index
inferred_codes ... |
def _add_ubridge_connection(self, nio, adapter_number):
"""
Creates a connection in uBridge.
:param nio: NIO instance or None if it's a dummy interface (if an interface is missing in ubridge you can't see it via ifconfig in the container)
:param adapter_number: adapter number
""... | Creates a connection in uBridge.
:param nio: NIO instance or None if it's a dummy interface (if an interface is missing in ubridge you can't see it via ifconfig in the container)
:param adapter_number: adapter number |
def to_execution_plan(self,
domain,
default_screen,
start_date,
end_date):
"""
Compile into an ExecutionPlan.
Parameters
----------
domain : zipline.pipeline.domain.Domain
... | Compile into an ExecutionPlan.
Parameters
----------
domain : zipline.pipeline.domain.Domain
Domain on which the pipeline will be executed.
default_screen : zipline.pipeline.term.Term
Term to use as a screen if self.screen is None.
all_dates : pd.Datetime... |
def parse_cookie(name, sign_key, kaka, enc_key=None, sign_alg='SHA256'):
"""Parses and verifies a cookie value
Parses a cookie created by `make_cookie` and verifies
it has not been tampered with.
You need to provide the same `sign_key` and `enc_key`
used when creating the cookie, otherwise the ver... | Parses and verifies a cookie value
Parses a cookie created by `make_cookie` and verifies
it has not been tampered with.
You need to provide the same `sign_key` and `enc_key`
used when creating the cookie, otherwise the verification
fails. See `make_cookie` for details about the verification.
... |
def get_decomposition_energy(self, entry, pH, V):
"""
Finds decomposition to most stable entry
Args:
entry (PourbaixEntry): PourbaixEntry corresponding to
compound to find the decomposition for
pH (float): pH at which to find the decomposition
... | Finds decomposition to most stable entry
Args:
entry (PourbaixEntry): PourbaixEntry corresponding to
compound to find the decomposition for
pH (float): pH at which to find the decomposition
V (float): voltage at which to find the decomposition
Return... |
def ReliefF_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN, headers, class_type, X, y, labels_std, data_type):
""" Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. """
scores = np.zeros(num_attributes)
for feature_nu... | Unique scoring procedure for ReliefF algorithm. Scoring based on k nearest hits and misses of current target instance. |
def send_email(self, user, subject, msg):
"""Should be overwritten in the setup"""
print('To:', user)
print('Subject:', subject)
print(msg) | Should be overwritten in the setup |
def fetch_uptodate(self, ):
"""Set and return whether the currently loaded entity is
the newest version in the department.
:returns: True, if newest version. False, if there is a newer version.
None, if there is nothing loaded yet.
:rtype: bool | None
:raises: ... | Set and return whether the currently loaded entity is
the newest version in the department.
:returns: True, if newest version. False, if there is a newer version.
None, if there is nothing loaded yet.
:rtype: bool | None
:raises: None |
def get_sunpos(self, t, true_time=False):
"""
Computes the Sun positions for the *t* time vector.
*t* have to be in absolute minutes (0 at 00:00 01 Jan). The and
in Sun positions calculated are in solar time, that is, maximun
solar zenit exactly at midday.
... | Computes the Sun positions for the *t* time vector.
*t* have to be in absolute minutes (0 at 00:00 01 Jan). The and
in Sun positions calculated are in solar time, that is, maximun
solar zenit exactly at midday.
The generated information is stored in:
... |
def quaternion_inverse(quaternion):
"""Return inverse of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_inverse(q0)
>>> numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
True
"""
q = numpy.array(quaternion, dtype=numpy.float64, copy=True)
numpy.negative(q[1:], q[1... | Return inverse of quaternion.
>>> q0 = random_quaternion()
>>> q1 = quaternion_inverse(q0)
>>> numpy.allclose(quaternion_multiply(q0, q1), [1, 0, 0, 0])
True |
def copy_file_if_modified(src_path, dest_path):
"""Only copies the file from the source path to the destination path if it doesn't exist yet or it has
been modified. Intended to provide something of an optimisation when a project has large trees of assets."""
# if the destination path is a directory, delet... | Only copies the file from the source path to the destination path if it doesn't exist yet or it has
been modified. Intended to provide something of an optimisation when a project has large trees of assets. |
def get_job_amounts(agent, project_name, spider_name=None):
"""
Get amounts that pending job amount, running job amount, finished job amount.
"""
job_list = agent.get_job_list(project_name)
pending_job_list = job_list['pending']
running_job_list = job_list['running']
finished_job_list = job_... | Get amounts that pending job amount, running job amount, finished job amount. |
def on_config_value_changed(self, config_m, prop_name, info):
"""Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config ... | Callback when a config value has been changed
:param ConfigModel config_m: The config model that has been changed
:param str prop_name: Should always be 'config'
:param dict info: Information e.g. about the changed config key |
def _to_string(self):
"""Implemented a function for __str__ and __repr__ to use, but
which prevents infinite recursion when migrating to Python 3"""
if self.sections:
start = "/" if self.bound_start else "**/"
sections = "/**/".join(str(section) for section in self.sectio... | Implemented a function for __str__ and __repr__ to use, but
which prevents infinite recursion when migrating to Python 3 |
def _dyn_loader(self, module: str, kwargs: str):
"""Dynamically load a specific module instance."""
package_directory: str = os.path.dirname(os.path.abspath(__file__))
modules: str = package_directory + "/modules"
module = module + ".py"
if module not in os.listdir(modules):
... | Dynamically load a specific module instance. |
def _extract_ips(self, data):
'''
Extract ip addressess from openstack structure
{
'pl-krk-2-int-301-c2-int-1': [
{
'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:29:f1:bb',
'version': 4,
'addr': '10.185.138.36',
'OS-EXT-IPS:type': '... | Extract ip addressess from openstack structure
{
'pl-krk-2-int-301-c2-int-1': [
{
'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:29:f1:bb',
'version': 4,
'addr': '10.185.138.36',
'OS-EXT-IPS:type': 'fixed'
}
]
}
:arg... |
def notification_message(cls, item):
'''Convert an RPCRequest item to a message.'''
assert isinstance(item, Notification)
return cls.encode_payload(cls.request_payload(item, None)) | Convert an RPCRequest item to a message. |
def K(self):
"""Normalizing constant for wishart CDF."""
K1 = np.float_power(pi, 0.5 * self.n_min * self.n_min)
K1 /= (
np.float_power(2, 0.5 * self.n_min * self._n_max)
* self._mgamma(0.5 * self._n_max, self.n_min)
* self._mgamma(0.5 * self.n_min, self.n_min)... | Normalizing constant for wishart CDF. |
def plot_samples(
ax,
sampler,
modelidx=0,
sed=True,
n_samples=100,
e_unit=u.eV,
e_range=None,
e_npoints=100,
threads=None,
label=None,
last_step=False,
):
"""Plot a number of samples from the sampler chain.
Parameters
----------
ax : `matplotlib.Axes`
... | Plot a number of samples from the sampler chain.
Parameters
----------
ax : `matplotlib.Axes`
Axes to plot on.
sampler : `emcee.EnsembleSampler`
Sampler
modelidx : int, optional
Model index. Default is 0
sed : bool, optional
Whether to plot SED or differential sp... |
def find_clashes(all_items):
"""Find schedule items which clash (common slot and venue)"""
clashes = {}
seen_venue_slots = {}
for item in all_items:
for slot in item.slots.all():
pos = (item.venue, slot)
if pos in seen_venue_slots:
if seen_venue_slots[pos]... | Find schedule items which clash (common slot and venue) |
def _save_function_final_state(self, function_key, function_address, state):
"""
Save the final state of a function, and merge it with existing ones if there are any.
:param FunctionKey function_key: The key to this function.
:param int function_address: Address of the function.
... | Save the final state of a function, and merge it with existing ones if there are any.
:param FunctionKey function_key: The key to this function.
:param int function_address: Address of the function.
:param SimState state: Initial state of the function.
:return: None |
def setMaximumSize(self, *args):
"""
Sets the maximum size value to the inputed size and emits the \
sizeConstraintChanged signal.
:param *args | <tuple>
"""
super(XView, self).setMaximumSize(*args)
if ( not self.signalsBlocked() ):
... | Sets the maximum size value to the inputed size and emits the \
sizeConstraintChanged signal.
:param *args | <tuple> |
def social_media_profile(self,
site: Optional[SocialNetwork] = None) -> str:
"""Generate profile for random social network.
:return: Profile in some network.
:Example:
http://facebook.com/some_user
"""
key = self._validate_enum(site, Soc... | Generate profile for random social network.
:return: Profile in some network.
:Example:
http://facebook.com/some_user |
def pre_check(self, data):
"""Count chars, words and sentences in the text."""
sentences = len(re.findall('[\.!?]+\W+', data)) or 1
chars = len(data) - len(re.findall('[^a-zA-Z0-9]', data))
num_words = len(re.findall('\s+', data))
data = re.split('[^a-zA-Z]+', data)
retur... | Count chars, words and sentences in the text. |
def get_ips_from_steamids(self, server_steam_ids, timeout=30):
"""Resolve IPs from SteamIDs
:param server_steam_ids: a list of steamids
:type server_steam_ids: list
:param timeout: (optional) timeout for request in seconds
:type timeout: int
:return: map of ips to stea... | Resolve IPs from SteamIDs
:param server_steam_ids: a list of steamids
:type server_steam_ids: list
:param timeout: (optional) timeout for request in seconds
:type timeout: int
:return: map of ips to steamids
:rtype: dict
:raises: :class:`.UnifiedMessageError`
... |
def _encrypt(key_data, derived_key_information):
"""
Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm.
'derived_key_information' should contain a key strengthened by PBKDF2. The
key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode).
The HMAC of the ciphert... | Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm.
'derived_key_information' should contain a key strengthened by PBKDF2. The
key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode).
The HMAC of the ciphertext is generated to ensure the ciphertext has not been
... |
def create_oqhazardlib_source(self, tom, mesh_spacing, area_discretisation,
use_defaults=False):
"""
Converts the source model into an instance of the :class:
openquake.hazardlib.source.area.AreaSource
:param tom:
Temporal Occurrence model a... | Converts the source model into an instance of the :class:
openquake.hazardlib.source.area.AreaSource
:param tom:
Temporal Occurrence model as instance of :class:
openquake.hazardlib.tom.TOM
:param float mesh_spacing:
Mesh spacing |
def enable(self):
"""Enable a NApp if not already enabled.
Raises:
FileNotFoundError: If NApp is not installed.
PermissionError: No filesystem permission to enable NApp.
"""
core_napps_manager = CoreNAppsManager(base_path=self._enabled)
core_napps_manage... | Enable a NApp if not already enabled.
Raises:
FileNotFoundError: If NApp is not installed.
PermissionError: No filesystem permission to enable NApp. |
def container(self, cls, **kwargs):
"""Container context manager."""
self.start_container(cls, **kwargs)
yield
self.end_container() | Container context manager. |
def Main():
"""The main function.
Returns:
bool: True if successful or False otherwise.
"""
tool = image_export_tool.ImageExportTool()
if not tool.ParseArguments():
return False
if tool.list_signature_identifiers:
tool.ListSignatureIdentifiers()
return True
if not tool.has_filters:
... | The main function.
Returns:
bool: True if successful or False otherwise. |
def delete_one(self, id_):
"""Delete one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#delete
:param id_: record id_
**中文文档**
删除一条记录
"""
url = "https://api.kna... | Delete one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#delete
:param id_: record id_
**中文文档**
删除一条记录 |
def list_configs():
'''
List all available configs
CLI example:
.. code-block:: bash
salt '*' snapper.list_configs
'''
try:
configs = snapper.ListConfigs()
return dict((config[0], config[2]) for config in configs)
except dbus.DBusException as exc:
raise Com... | List all available configs
CLI example:
.. code-block:: bash
salt '*' snapper.list_configs |
def parse_cmd_kwarg(text, off=0):
'''
Parse a foo:bar=<valu> kwarg into (prop,valu),off
'''
_, off = nom(text, off, whites)
prop, off = nom(text, off, varset)
_, off = nom(text, off, whites)
if not nextchar(text, off, '='):
raise s_exc.BadSyntax(expected='= for kwarg ' + prop, at=... | Parse a foo:bar=<valu> kwarg into (prop,valu),off |
def load_edgegrid_client_settings():
'''Load Akamai EdgeGrid configuration
returns a (hostname, EdgeGridAuth) tuple from the following locations:
1. Values specified directly in the Django settings::
AKAMAI_CCU_CLIENT_SECRET
AKAMAI_CCU_HOST
AKAMAI_CCU_ACCESS_TOKEN
AKAMAI_CC... | Load Akamai EdgeGrid configuration
returns a (hostname, EdgeGridAuth) tuple from the following locations:
1. Values specified directly in the Django settings::
AKAMAI_CCU_CLIENT_SECRET
AKAMAI_CCU_HOST
AKAMAI_CCU_ACCESS_TOKEN
AKAMAI_CCU_CLIENT_TOKEN
2. An edgerc file specifi... |
async def discover(ignore_list=[], max_wait=30, loop=None):
"""List STB in the network."""
stbs = []
try:
async with timeout(max_wait, loop=loop):
def responses_callback(notify):
"""Queue notify messages."""
_LOGGER.debug("Found: %s", notify.ip_address)
... | List STB in the network. |
def reverse(self):
"""
NAME:
reverse
PURPOSE:
reverse an already integrated orbit (that is, make it go from end to beginning in t=0 to tend)
INPUT:
(none)
OUTPUT:
(none)
HISTORY:
2011-04-13 - Written - Bovy (N... | NAME:
reverse
PURPOSE:
reverse an already integrated orbit (that is, make it go from end to beginning in t=0 to tend)
INPUT:
(none)
OUTPUT:
(none)
HISTORY:
2011-04-13 - Written - Bovy (NYU) |
def _truncated_normal(mean,
stddev,
seed=None,
normalize=True,
alpha=0.01):
''' Add noise with truncnorm from numpy.
Bounded (0.001,0.999)
'''
# within range ()
# provide entry to chose which adding noise way to ... | Add noise with truncnorm from numpy.
Bounded (0.001,0.999) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.