Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _normalize(mat: np.ndarray):
"""rescales a numpy array, so that min is 0 and max is 255"""
return ((mat - mat.min()) * (255 / mat.max())).astype(np.uint8) |
def to_24bit_gray(mat: np.ndarray):
"""returns a matrix that contains RGB channels, and colors scaled
from 0 to 255"""
return np.repeat(np.expand_dims(_normalize(mat), axis=2), 3, axis=2) |
def apply_color_map(name: str, mat: np.ndarray = None):
"""returns an RGB matrix scaled by a matplotlib color map"""
def apply_map(mat):
return (cm.get_cmap(name)(_normalize(mat))[:, :, :3] * 255).astype(np.uint8)
return apply_map if mat is None else apply_map(mat) |
def mat_to_surface(mat: np.ndarray, transformer=to_24bit_gray):
"""Can be used to create a pygame.Surface from a 2d numpy array.
By default a grey image with scaled colors is returned, but using the
transformer argument any transformation can be used.
:param mat: the matrix to create the surface of.
... |
def random_id(length=16, charset=alphanum_chars, first_charset=alpha_chars, sep='', group=0):
"""Creates a random id with the given length and charset.
## Parameters
* length the number of characters in the id
* charset what character set to use (a list of characters)
* first_c... |
def merge_dict(data, *args):
"""Merge any number of dictionaries
"""
results = {}
for current in (data,) + args:
results.update(current)
return results |
def make_url(url, *paths):
"""Joins individual URL strings together, and returns a single string.
"""
for path in paths:
url = re.sub(r'/?$', re.sub(r'^/?', '/', path), url)
return url |
def aggregate_result(self, return_code, output, service_description='', specific_servers=None):
'''
aggregate result
'''
if specific_servers == None:
specific_servers = self.servers
else:
specific_servers = set(self.servers).intersection(specific_servers)
... |
def send_results(self):
'''
send results
'''
for server in self.servers:
if self.servers[server]['results']:
if len(self.servers[server]['results']) == 1:
msg = MIMEText('')
msg['Subject'] = '[%(custom_fqdn)s] [%(servic... |
def main():
"""MAIN"""
config = {
"api": {
"services": [
{
"name": "my_api",
"testkey": "testval",
},
],
"calls": {
"hello_world": {
"delay": 5,
... |
def make_request(self, data):
"""Parse the outgoing schema"""
sch = MockItemSchema()
return Request(**{
"callname": self.context.get("callname"),
"payload": sch.dump(data),
}) |
def populate_data(self, data):
"""Parse the outgoing schema"""
sch = MockItemSchema()
return Result(**{
"callname": self.context.get("callname"),
"result": sch.dump(data),
}) |
def key_press(keys):
"""returns a handler that can be used with EventListener.listen()
and returns when a key in keys is pressed"""
return lambda e: e.key if e.type == pygame.KEYDOWN \
and e.key in keys else EventConsumerInfo.DONT_CARE |
def unicode_char(ignored_chars=None):
"""returns a handler that listens for unicode characters"""
return lambda e: e.unicode if e.type == pygame.KEYDOWN \
and ((ignored_chars is None)
or (e.unicode not in ignored_chars))\
else EventConsumerInfo.DONT_CARE |
def mouse_area(self, handler, group=0, ident=None):
"""Adds a new MouseProxy for the given group to the
EventListener.mouse_proxies dict if it is not in there yet, and returns
the (new) MouseProxy. In listen() all entries in the current group of
mouse_proxies are used."""
key = ... |
def listen(self, *temporary_handlers):
"""When listen() is called all queued pygame.Events will be passed to all
registered listeners. There are two ways to register a listener:
1. as a permanent listener, that is always executed for every event. These
are registered by passing the ... |
def listen_until_return(self, *temporary_handlers, timeout=0):
"""Calls listen repeatedly until listen returns something else than None.
Then returns listen's result. If timeout is not zero listen_until_return
stops after timeout seconds and returns None."""
start = time.time()
w... |
def wait_for_n_keypresses(self, key, n=1):
"""Waits till one key was pressed n times.
:param key: the key to be pressed as defined by pygame. E.g.
pygame.K_LEFT for the left arrow key
:type key: int
:param n: number of repetitions till the function returns
:type n: i... |
def wait_for_keys(self, *keys, timeout=0):
"""Waits until one of the specified keys was pressed, and returns
which key was pressed.
:param keys: iterable of integers of pygame-keycodes, or simply
multiple keys passed via multiple arguments
:type keys: iterable
:par... |
def wait_for_keys_modified(self, *keys, modifiers_to_check=_mod_keys,
timeout=0):
"""The same as wait_for_keys, but returns a frozen_set which contains
the pressed key, and the modifier keys.
:param modifiers_to_check: iterable of modifiers for which the function... |
def wait_for_unicode_char(self, ignored_chars=None, timeout=0):
"""Returns a str that contains the single character that was pressed.
This already respects modifier keys and keyboard layouts. If timeout is
not none and no key is pressed within the specified timeout, None is
returned. If ... |
def _find_all_first_files(self, item):
"""
Does not support the full range of ways rar can split
as it'd require reading the file to ensure you are using the
correct way.
"""
for listed_item in item.list():
new_style = re.findall(r'(?i)\.part(\d+)\.rar^', list... |
def find_datafile(name, search_path, codecs=get_codecs()):
"""
find all matching data files in search_path
search_path: path of directories to load from
codecs: allow to override from list of installed
returns array of tuples (codec_object, filename)
"""
return munge.find_datafile(name, sear... |
def load_datafile(name, search_path, codecs=get_codecs(), **kwargs):
"""
find datafile and load them from codec
TODO only does the first one
kwargs:
default = if passed will return that on failure instead of throwing
"""
return munge.load_datafile(name, search_path, codecs, **kwargs) |
def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str,
) -> None:
"""
Initialize what requires credentials/secret files.
:param secrets_dir: dir to expect credentials in and store logs/history in.
:param log:... |
def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send birdsite message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
"""
... |
def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[]
) -> List[OutputRecord]:
"""
Upload media to birdsite,
and send status and media,
and captions if present.
:param text: tweet text.
... |
def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
Looks up the recent messages of the target user,
a... |
def send_dm_sos(self, message: str) -> None:
"""
Send DM to owner if something happens.
:param message: message to send to owner.
:returns: None.
"""
if self.owner_handle:
try:
# twitter changed the DM API and tweepy (as of 2019-03-08)
... |
def handle_error(
self,
*,
message: str,
error: tweepy.TweepError,
) -> OutputRecord:
"""
Handle error while trying to do something.
:param message: message to send in DM regarding error.
:param e: tweepy error object.
:returns... |
def _handle_caption_upload(
self,
*,
media_ids: List[str],
captions: Optional[List[str]],
) -> None:
"""
Handle uploading all captions.
:param media_ids: media ids of uploads to attach captions to.
:param captions: captions to be attac... |
def _send_direct_message_new(self, messageobject: Dict[str, Dict]) -> Any:
"""
:reference: https://developer.twitter.com/en/docs/direct-messages/sending-and-receiving/api-reference/new-event.html
"""
headers, post_data = _buildmessageobject(messageobject)
newdm_path = "/direct_me... |
def main():
"""Takes crash data via stdin and generates a Socorro signature"""
parser = argparse.ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
args = parser.parse_args()
generator = SignatureGenera... |
def add_config(self, config):
"""
Update internel configuration dict with config and recheck
"""
for attr in self.__fixed_attrs:
if attr in config:
raise Exception("cannot set '%s' outside of init", attr)
# pre checkout
stages = config.get('s... |
def check_config(self):
"""
called after config was modified to sanity check
raises on error
"""
# sanity checks - no config access past here
if not getattr(self, 'stages', None):
raise NotImplementedError("member variable 'stages' must be defined")
#... |
def check_definition(self):
"""
called after Defintion was loaded to sanity check
raises on error
"""
if not self.write_codec:
self.__write_codec = self.defined.data_ext
# TODO need to add back a class scope target limited for subprojects with sub target sets... |
def find_datafile(self, name, search_path=None):
"""
find all matching data files in search_path
returns array of tuples (codec_object, filename)
"""
if not search_path:
search_path = self.define_dir
return codec.find_datafile(name, search_path) |
def load_datafile(self, name, search_path=None, **kwargs):
"""
find datafile and load them from codec
"""
if not search_path:
search_path = self.define_dir
self.debug_msg('loading datafile %s from %s' % (name, str(search_path)))
return codec.load_datafile(nam... |
def run(self):
""" run all configured stages """
self.sanity_check()
# TODO - check for devel
# if not self.version:
# raise Exception("no version")
# XXX check attr exist
if not self.release_environment:
raise Exception("no instance name")
time_start = t... |
def timestamp(dt):
"""
Return POSIX timestamp as float.
>>> timestamp(datetime.datetime.now()) > 1494638812
True
>>> timestamp(datetime.datetime.now()) % 1 > 0
True
"""
if dt.tzinfo is None:
return time.mktime((
dt.year, dt.month, dt.day,
dt.hour, dt.minute, dt.second,
-1, -1, -1)) + dt.microsecond... |
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
"""Rate limit a function."""
return util.rate_limited(max_per_hour, *args) |
def _repair(record: Dict[str, Any]) -> Dict[str, Any]:
"""Repair a corrupted IterationRecord with a specific known issue."""
output_records = record.get("output_records")
if record.get("_type", None) == "IterationRecord" and output_records is not None:
birdsite_record = output_records.get("birdsite"... |
def from_dict(cls, obj_dict: Dict[str, Any]) -> "IterationRecord":
"""Get object back from dict."""
obj = cls()
for key, item in obj_dict.items():
obj.__dict__[key] = item
return obj |
def send(
self,
*args: str,
text: str=None,
) -> IterationRecord:
"""
Post text-only to all outputs.
:param args: positional arguments.
expected: text to send as message in post.
keyword text argument is preferred over this.
... |
def send_with_one_media(
self,
*args: str,
text: str=None,
file: str=None,
caption: str=None,
) -> IterationRecord:
"""
Post with one media item to all outputs.
Provide filename so outputs can handle their own uploads.
:par... |
def send_with_many_media(
self,
*args: str,
text: str=None,
files: List[str]=None,
captions: List[str]=[],
) -> IterationRecord:
"""
Post with several media.
Provide filenames so outputs can handle their own uploads.
:param... |
def perform_batch_reply(
self,
*,
callback: Callable[..., str]=None,
target_handles: Dict[str, str]=None,
lookback_limit: int=20,
per_service_lookback_limit: Dict[str, int]=None,
) -> IterationRecord:
"""
Performs batch reply on... |
def nap(self) -> None:
"""
Go to sleep for the duration of self.delay.
:returns: None
"""
self.log.info(f"Sleeping for {self.delay} seconds.")
for _ in progress.bar(range(self.delay)):
time.sleep(1) |
def store_extra_info(self, key: str, value: Any) -> None:
"""
Store some extra value in the messaging storage.
:param key: key of dictionary entry to add.
:param value: value of dictionary entry to add.
:returns: None
"""
self.extra_keys[key] = value |
def store_extra_keys(self, d: Dict[str, Any]) -> None:
"""
Store several extra values in the messaging storage.
:param d: dictionary entry to merge with current self.extra_keys.
:returns: None
"""
new_dict = dict(self.extra_keys, **d)
self.extra_keys = new_dict.c... |
def update_history(self) -> None:
"""
Update messaging history on disk.
:returns: None
"""
self.log.debug(f"Saving history. History is: \n{self.history}")
jsons = []
for item in self.history:
json_item = item.__dict__
# Convert sub-entri... |
def load_history(self) -> List["IterationRecord"]:
"""
Load messaging history from disk to self.
:returns: List of iteration records comprising history.
"""
if path.isfile(self.history_filename):
with open(self.history_filename, "r") as f:
try:
... |
def _setup_all_outputs(self) -> None:
"""Set up all output methods. Provide them credentials and anything else they need."""
# The way this is gonna work is that we assume an output should be set up iff it has a
# credentials_ directory under our secrets dir.
for key in self.outputs.key... |
def _parse_output_records(self, item: IterationRecord) -> Dict[str, Any]:
"""Parse output records into dicts ready for JSON."""
output_records = {}
for key, sub_item in item.output_records.items():
if isinstance(sub_item, dict) or isinstance(sub_item, list):
output_re... |
def make_dir(fname):
"""
Create the directory of a fully qualified file name if it does not exist.
:param fname: File name
:type fname: string
Equivalent to these Bash shell commands:
.. code-block:: bash
$ fname="${HOME}/mydir/myfile.txt"
$ dir=$(dirname "${fname}")
... |
def normalize_windows_fname(fname, _force=False):
r"""
Fix potential problems with a Microsoft Windows file name.
Superfluous backslashes are removed and unintended escape sequences are
converted to their equivalent (presumably correct and intended)
representation, for example :code:`r'\\\\x07pps'`... |
def _homogenize_linesep(line):
"""Enforce line separators to be the right one depending on platform."""
token = str(uuid.uuid4())
line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "")
return line.replace(token, os.linesep) |
def _proc_token(spec, mlines):
"""Process line range tokens."""
spec = spec.strip().replace(" ", "")
regexp = re.compile(r".*[^0123456789\-,]+.*")
tokens = spec.split(",")
cond = any([not item for item in tokens])
if ("--" in spec) or ("-," in spec) or (",-" in spec) or cond or regexp.match(spec... |
def incfile(fname, fpointer, lrange=None, sdir=None):
r"""
Return a Python source file formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param fname: File name, relative to environment variable
:bash:`PKG_DOC_DIR`
:type fname: string
:param fpoint... |
def ste(command, nindent, mdir, fpointer, env=None):
"""
Print STDOUT of a shell command formatted in reStructuredText.
This is a simplified version of :py:func:`pmisc.term_echo`.
:param command: Shell command (relative to **mdir** if **env** is not given)
:type command: string
:param ninden... |
def term_echo(command, nindent=0, env=None, fpointer=None, cols=60):
"""
Print STDOUT of a shell command formatted in reStructuredText.
.. role:: bash(code)
:language: bash
:param command: Shell command
:type command: string
:param nindent: Indentation level
:type nindent: integ... |
def flo(string):
'''Return the string given by param formatted with the callers locals.'''
callers_locals = {}
frame = inspect.currentframe()
try:
outerframe = frame.f_back
callers_locals = outerframe.f_locals
finally:
del frame
return string.format(**callers_locals) |
def _wrap_with(color_code):
'''Color wrapper.
Example:
>>> blue = _wrap_with('34')
>>> print(blue('text'))
\033[34mtext\033[0m
'''
def inner(text, bold=False):
'''Inner color function.'''
code = color_code
if bold:
code = flo("1;{code}")
... |
def clean(deltox=False):
'''Delete temporary files not under version control.
Args:
deltox: If True, delete virtual environments used by tox
'''
basedir = dirname(__file__)
print(cyan('delete temp files and dirs for packaging'))
local(flo(
'rm -rf '
'{basedir}/.eggs/ ... |
def pythons():
'''Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
'''
if not _pyenv_exists():
print('\npyenv is not installed. You can install it with fabsetup '
'(https://gi... |
def tox(args=''):
'''Run tox.
Build package and run unit tests against several pythons.
Args:
args: Optional arguments passed to tox.
Example:
fab tox:'-e py36 -r'
'''
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_mino... |
def pypi():
'''Build package and upload to pypi.'''
if query_yes_no('version updated in setup.py?'):
print(cyan('\n## clean-up\n'))
execute(clean)
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_minor: '3.6'
highest_minor... |
def chk_col_numbers(line_num, num_cols, tax_id_col, id_col, symbol_col):
"""
Check that none of the input column numbers is out of range.
(Instead of defining this function, we could depend on Python's built-in
IndexError exception for this issue, but the IndexError exception wouldn't
include line n... |
def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col):
"""
Read input gene history file into the database.
Note that the arguments tax_id_col, id_col and symbol_col have been
converted into 0-based column indexes.
"""
# Make sure that tax_id is not "" or " "
if not t... |
def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str="",
) -> None:
"""Initialize what requires credentials/secret files."""
super().__init__(secrets_dir=secrets_dir, log=log, bot_name=bot_name)
self.ldebug("Retriev... |
def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send mastodon message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single post,
or an error.
"""
... |
def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[],
) -> List[OutputRecord]:
"""
Upload media to mastodon,
and send status and media,
and captions if present.
:param text: post text.
... |
def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
Looks up the recent messages of the target user,
a... |
def handle_error(self, message: str, e: mastodon.MastodonError) -> OutputRecord:
"""Handle error while trying to do something."""
self.lerror(f"Got an error! {e}")
# Handle errors if we know how.
try:
code = e[0]["code"]
if code in self.handled_errors:
... |
def _read_header(self):
'''
Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count |
'''
self._fh.seek(0)
buf = self._fh.read(4*2)
fc, dc = struct.unpack("<II", buf)
retur... |
def listen(self, you):
"""
Request a callback for value modification.
Parameters
----------
you : object
An instance having ``__call__`` attribute.
"""
self._listeners.append(you)
self.raw.talk_to(you) |
def _get_term_by_id(self, id):
'''Simple utility function to load a term.
'''
url = (self.url + '/%s.json') % id
r = self.session.get(url)
return r.json() |
def get_top_display(self, **kwargs):
'''
Returns all concepts or collections that form the top-level of a display
hierarchy.
As opposed to the :meth:`get_top_concepts`, this method can possibly
return both concepts and collections.
:rtype: Returns a list of concepts and... |
def get_children_display(self, id, **kwargs):
'''
Return a list of concepts or collections that should be displayed
under this concept or collection.
:param id: A concept or collection id.
:rtype: A list of concepts and collections. For each an
id is present and a la... |
def translate_genes(id_list=None, from_id=None, to_id=None, organism=None):
"""
Pass a list of identifiers (id_list), the name of the database ('Entrez',
'Symbol', 'Standard name', 'Systematic name' or a loaded crossreference
database) that you wish to translate from, and the name of the database
th... |
def _inner_func_anot(func):
"""must be applied to all inner functions that return contexts.
Wraps all instances of pygame.Surface in the input in Surface"""
@wraps(func)
def new_func(*args):
return func(*_lmap(_wrap_surface, args))
return new_func |
def Cross(width=3, color=0):
"""Draws a cross centered in the target area
:param width: width of the lines of the cross in pixels
:type width: int
:param color: color of the lines of the cross
:type color: pygame.Color
"""
return Overlay(Line("h", width, color), Line("v", width, color)) |
def compose(target, root=None):
"""Top level function to create a surface.
:param target: the pygame.Surface to blit on. Or a (width, height) tuple
in which case a new surface will be created
:type target: -
"""
if type(root) == Surface:
raise ValueError("A Surface may not be u... |
def Font(name=None, source="sys", italic=False, bold=False, size=20):
"""Unifies loading of fonts.
:param name: name of system-font or filepath, if None is passed the default
system-font is loaded
:type name: str
:param source: "sys" for system font, or "file" to load a file
:type source: ... |
def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"):
"""Renders a text. Supports multiline text, the background will be transparent.
:param align: text-alignment must be "center", "left", or "righ"
:type align: str
:return: the input text
:rtype: pygame.Surface
... |
def from_scale(scale_w, scale_h=None):
"""Creates a padding by the remaining space after scaling the content.
E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and
Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0)
because the content would not b... |
def radicals(self, levels=None):
"""
:param levels string: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
http://www.wanikani.com/api/v1.2#... |
def kanji(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http://ww... |
def vocabulary(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http... |
def ishex(obj):
"""
Test if the argument is a string representing a valid hexadecimal digit.
:param obj: Object
:type obj: any
:rtype: boolean
"""
return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits) |
def isnumber(obj):
"""
Test if the argument is a number (complex, float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float, complex))
) |
def isreal(obj):
"""
Test if the argument is a real number (float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float))
) |
def create_api_context(self, cls):
"""Create and return an API context"""
return self.api_context_schema().load({
"name": cls.name,
"cls": cls,
"inst": [],
"conf": self.conf.get_api_service(cls.name),
"calls": self.conf.get_api_calls(),
... |
def receive(self, data, api_context):
"""Pass an API result down the pipeline"""
self.log.debug(f"Putting data on the pipeline: {data}")
result = {
"api_contexts": self.api_contexts,
"api_context": api_context,
"strategy": dict(), # Shared strategy data
... |
def shutdown(self, signum, frame): # pylint: disable=unused-argument
"""Shut it down"""
if not self.exit:
self.exit = True
self.log.debug(f"SIGTRAP!{signum};{frame}")
self.api.shutdown()
self.strat.shutdown() |
def course(self):
"""
Course this node belongs to
"""
course = self.parent
while course.parent:
course = course.parent
return course |
def path(self):
"""
Path of this node on Studip. Looks like Coures/folder/folder/document. Respects the renaming policies defined in the namemap
"""
if self.parent is None:
return self.title
return join(self.parent.path, self.title) |
def title(self):
"""
get title of this node. If an entry for this course is found in the configuration namemap it is used, otherwise the default
value from stud.ip is used.
"""
tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title
retur... |
def deep_documents(self):
"""
list of all documents find in subtrees of this node
"""
tree = []
for entry in self.contents:
if isinstance(entry, Document):
tree.append(entry)
else:
tree += entry.deep_documents
return... |
def title(self):
"""
The title of the course. If no entry in the namemap of the configuration is found a new entry is created with name=$STUD.IP_NAME + $SEMESTER_NAME
"""
name = c.namemap_lookup(self.id)
if name is None:
name = self._title + " " + client.get_semester_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.