Search is not available for this dataset
text stringlengths 75 104k |
|---|
def confidence_interval_arr(data, conf=0.95):
r""" Computes element-wise confidence intervals from a sample of ndarrays
Given a sample of arbitrarily shaped ndarrays, computes element-wise confidence intervals
Parameters
----------
data : ndarray (K, (shape))
ndarray of ndarrays, the first... |
def status(self, remote=False):
"""
Return the connection status, both locally and remotely.
The local connection status is a dictionary that gives:
* the count of multiple queries sent to the server.
* the count of single queries sent to the server.
* the count of actio... |
def query_single(self, object_type, url_params, query_params=None):
# type: (str, list, dict) -> dict
"""
Query for a single object.
:param object_type: string query type (e.g., "users" or "groups")
:param url_params: required list of strings to provide as additional URL componen... |
def query_multiple(self, object_type, page=0, url_params=None, query_params=None):
# type: (str, int, list, dict) -> tuple
"""
Query for a page of objects. Defaults to the (0-based) first page.
Sadly, the sort order is undetermined.
:param object_type: string constant query type... |
def execute_single(self, action, immediate=False):
"""
Execute a single action (containing commands on a single object).
Normally, since actions are batched so as to be most efficient about execution,
but if you want this command sent immediately (and all prior queued commands
se... |
def execute_multiple(self, actions, immediate=True):
"""
Execute multiple Actions (each containing commands on a single object).
Normally, the actions are sent for execution immediately (possibly preceded
by earlier queued commands), but if you are going for maximum efficiency
yo... |
def _execute_batch(self, actions):
"""
Execute a single batch of Actions.
For each action that has a problem, we annotate the action with the
error information for that action, and we return the number of
successful actions in the batch.
:param actions: the list of Action... |
def make_call(self, path, body=None, delete=False):
"""
Make a single UMAPI call with error handling and retry on temporary failure.
:param path: the string endpoint path for the call
:param body: (optional) list of dictionaries to be serialized into the request body
:return: the... |
def paginate(query, org_id, max_pages=maxsize, max_records=maxsize):
"""
Paginate through all results of a UMAPI query
:param query: a query method from a UMAPI instance (callable as a function)
:param org_id: the organization being queried
:param max_pages: the max number of pages to collect before... |
def make_call(query, org_id, page):
"""
Make a single UMAPI call with error handling and server-controlled throttling.
(Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry)
:param query: a query method from a UMAPI instance (callable as a function)
:param org_... |
def do(self, **kwargs):
"""
Here for compatibility with legacy clients only - DO NOT USE!!!
This is sort of mix of "append" and "insert": it puts commands in the list,
with some half smarts about which commands go at the front or back.
If you add multiple commands to the back in ... |
def split(self, max_commands):
"""
Split this action into an equivalent list of actions, each of which have at most max_commands commands.
:param max_commands: max number of commands allowed in any action
:return: the list of commands created from this one
"""
a_prior = A... |
def append(self, **kwargs):
"""
Add commands at the end of the sequence.
Be careful: because this runs in Python 2.x, the order of the kwargs dict may not match
the order in which the args were specified. Thus, if you care about specific ordering,
you must make multiple calls t... |
def insert(self, **kwargs):
"""
Insert commands at the beginning of the sequence.
This is provided because certain commands
have to come first (such as user creation), but may be need to beadded
after other commands have already been specified.
Later calls to insert put ... |
def report_command_error(self, error_dict):
"""
Report a server error executing a command.
We keep track of the command's position in the command list,
and we add annotation of what the command was, to the error.
:param error_dict: The server's error dict for the error encounter... |
def execution_errors(self):
"""
Return a list of commands that encountered execution errors, with the error.
Each dictionary entry gives the command dictionary and the error dictionary
:return: list of commands that gave errors, with their error information
"""
if self.s... |
def maybe_split_groups(self, max_groups):
"""
Check if group lists in add/remove directives should be split and split them if needed
:param max_groups: Max group list size
:return: True if at least one command was split, False if none were split
"""
split_commands = []
... |
def reload(self):
"""
Rerun the query (lazily).
The results will contain any values on the server side that have changed since the last run.
:return: None
"""
self._results = []
self._next_item_index = 0
self._next_page_index = 0
self._last_page_se... |
def _next_page(self):
"""
Fetch the next page of the query.
"""
if self._last_page_seen:
raise StopIteration
new, self._last_page_seen = self.conn.query_multiple(self.object_type, self._next_page_index,
self... |
def all_results(self):
"""
Eagerly fetch all the results.
This can be called after already doing some amount of iteration, and it will return
all the previously-iterated results as well as any results that weren't yet iterated.
:return: a list of all the results.
"""
... |
def _fetch_result(self):
"""
Fetch the queried object.
"""
self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params) |
def create(self, first_name=None, last_name=None, country=None, email=None,
on_conflict=IfAlreadyExistsOptions.ignoreIfAlreadyExists):
"""
Create the user on the Adobe back end.
See [Issue 32](https://github.com/adobe-apiplatform/umapi-client.py/issues/32): because
we retr... |
def update(self, email=None, username=None, first_name=None, last_name=None, country=None):
"""
Update values on an existing user. See the API docs for what kinds of update are possible.
:param email: new email for this user
:param username: new username for this user
:param fir... |
def add_to_groups(self, groups=None, all_groups=False, group_type=None):
"""
Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect
is simply to do an "add to organization Everybody group", so we let that be done.
:param groups: list of group names the u... |
def remove_from_groups(self, groups=None, all_groups=False, group_type=None):
"""
Remove user from some PLC groups, or all of them.
:param groups: list of group names the user should be removed from
:param all_groups: a boolean meaning remove from all (don't specify groups or group_type ... |
def add_role(self, groups=None, role_type=RoleTypes.admin):
"""
Make user have a role (typically PLC admin) with respect to some PLC groups.
:param groups: list of group names the user should have this role for
:param role_type: the role (defaults to "admin")
:return: the User, s... |
def remove_role(self, groups=None, role_type=RoleTypes.admin):
"""
Remove user from a role (typically admin) of some groups.
:param groups: list of group names the user should NOT have this role for
:param role_type: the type of role (defaults to "admin")
:return: the User, so yo... |
def remove_from_organization(self, delete_account=False):
"""
Remove a user from the organization's list of visible users. Optionally also delete the account.
Deleting the account can only be done if the organization owns the account's domain.
:param delete_account: Whether to delete th... |
def delete_account(self):
"""
Delete a user's account.
Deleting the user's account can only be done if the user's domain is controlled by the authorized organization,
and removing the account will also remove the user from all organizations with access to that domain.
:return: No... |
def _validate(cls, group_name):
"""
Validates the group name
Input values must be strings (standard or unicode). Throws ArgumentError if any input is invalid
:param group_name: name of group
"""
if group_name and not cls._group_name_regex.match(group_name):
r... |
def add_to_products(self, products=None, all_products=False):
"""
Add user group to some product license configuration groups (PLCs), or all of them.
:param products: list of product names the user should be added to
:param all_products: a boolean meaning add to all (don't specify produc... |
def remove_from_products(self, products=None, all_products=False):
"""
Remove user group from some product license configuration groups (PLCs), or all of them.
:param products: list of product names the user group should be removed from
:param all_products: a boolean meaning remove from ... |
def add_users(self, users=None):
"""
Add users (specified by email address) to this user group.
In case of ambiguity (two users with same email address), the non-AdobeID user is preferred.
:param users: list of emails for users to add to the group.
:return: the Group, so you can ... |
def remove_users(self, users=None):
"""
Remove users (specified by email address) from this user group.
In case of ambiguity (two users with same email address), the non-AdobeID user is preferred.
:param users: list of emails for users to remove from the group.
:return: the Group... |
def scale2x(self, surface):
"""
Scales using the AdvanceMAME Scale2X algorithm which does a
'jaggie-less' scale of bitmap graphics.
"""
assert(self._scale == 2)
return self._pygame.transform.scale2x(surface) |
def smoothscale(self, surface):
"""
Smooth scaling using MMX or SSE extensions if available
"""
return self._pygame.transform.smoothscale(surface, self._output_size) |
def identity(self, surface):
"""
Fast scale operation that does not sample the results
"""
return self._pygame.transform.scale(surface, self._output_size) |
def led_matrix(self, surface):
"""
Transforms the input surface into an LED matrix (1 pixel = 1 LED)
"""
scale = self._led_on.get_width()
w, h = self._input_size
pix = self._pygame.PixelArray(surface)
img = self._pygame.Surface((w * scale, h * scale))
for... |
def rgb2short(r, g, b):
"""
Converts RGB values to the nearest equivalent xterm-256 color.
"""
# Using list of snap points, convert RGB value to cube indexes
r, g, b = [len(tuple(s for s in snaps if s < x)) for x in (r, g, b)]
# Simple colorcube transform
return (r * 36) + (g * 6) + b + 16 |
def to_surface(self, image, alpha=1.0):
"""
Converts a :py:mod:`PIL.Image` into a :class:`pygame.Surface`,
transforming it according to the ``transform`` and ``scale``
constructor arguments.
"""
assert(0.0 <= alpha <= 1.0)
if alpha < 1.0:
im = image.co... |
def display(self, image):
"""
Takes a :py:mod:`PIL.Image` and dumps it to a numbered PNG file.
"""
assert(image.size == self.size)
self._last_image = image
self._count += 1
filename = self._file_template.format(self._count)
image = self.preprocess(image)
... |
def display(self, image):
"""
Takes an image, scales it according to the nominated transform, and
stores it for later building into an animated GIF.
"""
assert(image.size == self.size)
self._last_image = image
image = self.preprocess(image)
surface = self... |
def display(self, image):
"""
Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface.
"""
assert(image.size == self.size)
self._last_image = image
image = self.preprocess(image)
self._clock.tick(self._fps)
self._pygame.event.pump()
... |
def _char_density(self, c, font=ImageFont.load_default()):
"""
Count the number of black pixels in a rendered character.
"""
image = Image.new('1', font.getsize(c), color=255)
draw = ImageDraw.Draw(image)
draw.text((0, 0), c, fill="white", font=font)
return collec... |
def _generate_art(self, image, width, height):
"""
Return an iterator that produces the ascii art.
"""
# Characters aren't square, so scale the output by the aspect ratio of a charater
height = int(height * self._char_width / float(self._char_height))
image = image.resize... |
def display(self, image):
"""
Takes a :py:mod:`PIL.Image` and renders it to the current terminal as
ASCII-art.
"""
assert(image.size == self.size)
self._last_image = image
surface = self.to_surface(self.preprocess(image), alpha=self._contrast)
rawbytes = ... |
def _generate_art(self, image, width, height):
"""
Return an iterator that produces the ascii art.
"""
image = image.resize((width, height), Image.ANTIALIAS).convert("RGB")
pixels = list(image.getdata())
for y in range(0, height - 1, 2):
for x in range(width)... |
def _CSI(self, cmd):
"""
Control sequence introducer
"""
sys.stdout.write('\x1b[')
sys.stdout.write(cmd) |
def display(self, image):
"""
Takes a :py:mod:`PIL.Image` and renders it to the current terminal as
ASCII-blocks.
"""
assert(image.size == self.size)
self._last_image = image
surface = self.to_surface(self.preprocess(image), alpha=self._contrast)
rawbytes... |
def chunk_sequence(sequence, chunk_length):
"""Yield successive n-sized chunks from l."""
for index in range(0, len(sequence), chunk_length):
yield sequence[index:index + chunk_length] |
def _filter_invalid_routes(routes, board, railroad):
"""
Given a collection of routes, returns a new set containing only valid routes. Invalid routes removed:
- contain less than 2 cities, or
- go through Chicago using an impassable exit
- only contain Chicago as a station, but don't use the correct... |
def find(path,
level=None,
message=None,
time_lower=None, time_upper=None,
case_sensitive=False): # pragma: no cover
"""
Filter log message.
**中文文档**
根据level名称, message中的关键字, 和log的时间的区间, 筛选出相关的日志
"""
if level:
level = level.upper() # level name has... |
def get_logger_by_name(name=None, rand_name=False, charset=Charset.HEX):
"""
Get a logger by name.
:param name: None / str, logger name.
:param rand_name: if True, ``name`` will be ignored, a random name will be used.
"""
if rand_name:
name = rand_str(charset)
logger = logging.getLo... |
def debug(self, msg, indent=0, **kwargs):
"""invoke ``self.logger.debug``"""
return self.logger.debug(self._indent(msg, indent), **kwargs) |
def info(self, msg, indent=0, **kwargs):
"""invoke ``self.info.debug``"""
return self.logger.info(self._indent(msg, indent), **kwargs) |
def warning(self, msg, indent=0, **kwargs):
"""invoke ``self.logger.warning``"""
return self.logger.warning(self._indent(msg, indent), **kwargs) |
def error(self, msg, indent=0, **kwargs):
"""invoke ``self.logger.error``"""
return self.logger.error(self._indent(msg, indent), **kwargs) |
def critical(self, msg, indent=0, **kwargs):
"""invoke ``self.logger.critical``"""
return self.logger.critical(self._indent(msg, indent), **kwargs) |
def show(self, msg, indent=0, style="", **kwargs):
"""
Print message to console, indent format may apply.
"""
if self.enable_verbose:
new_msg = self.MessageTemplate.with_style.format(
indent=self.tab * indent,
style=style,
msg=m... |
def remove_all_handler(self):
"""
Unlink the file handler association.
"""
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
self._handler_cache.append(handler) |
def recover_all_handler(self):
"""
Relink the file handler association you just removed.
"""
for handler in self._handler_cache:
self.logger.addHandler(handler)
self._handler_cache = list() |
def from_protobuf(cls, proto: LinkItemProto) -> LinkItem:
"""
Constructor from protobuf.
:param proto: protobuf structure
:type proto: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto
:return: the LinkItem
:rtype: ~unidown.plugin.link_item.LinkItem
:raises Va... |
def to_protobuf(self) -> LinkItemProto:
"""
Create protobuf item.
:return: protobuf structure
:rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto
"""
result = LinkItemProto()
result.name = self._name
result.time.CopyFrom(datetime_to_timestamp(sel... |
def update(self, fname):
"""
Adds a handler to save to a file. Includes debug stuff.
"""
ltfh = FileHandler(fname)
self._log.addHandler(ltfh) |
def delete_dir_rec(path: Path):
"""
Delete a folder recursive.
:param path: folder to deleted
:type path: ~pathlib.Path
"""
if not path.exists() or not path.is_dir():
return
for sub in path.iterdir():
if sub.is_dir():
delete_dir_rec(sub)
else:
... |
def create_dir_rec(path: Path):
"""
Create a folder recursive.
:param path: path
:type path: ~pathlib.Path
"""
if not path.exists():
Path.mkdir(path, parents=True, exist_ok=True) |
def datetime_to_timestamp(time: datetime) -> Timestamp:
"""
Convert datetime to protobuf.timestamp.
:param time: time
:type time: ~datetime.datetime
:return: protobuf.timestamp
:rtype: ~google.protobuf.timestamp_pb2.Timestamp
"""
protime = Timestamp()
protime.FromDatetime(time)
... |
def print_plugin_list(plugins: Dict[str, pkg_resources.EntryPoint]):
"""
Prints all registered plugins and checks if they can be loaded or not.
:param plugins: plugins
:type plugins: Dict[str, ~pkg_resources.EntryPoint]
"""
for trigger, entry_point in plugins.items():
try:
p... |
def overlap(xl1, yl1, nx1, ny1, xl2, yl2, nx2, ny2):
"""
Determines whether two windows overlap
"""
return (xl2 < xl1+nx1 and xl2+nx2 > xl1 and
yl2 < yl1+ny1 and yl2+ny2 > yl1) |
def saveJSON(g, data, backup=False):
"""
Saves the current setup to disk.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
backup : bool
If we are saving a backup on close, don't prompt for filename
"""
... |
def postJSON(g, data):
"""
Posts the current setup to the camera and data servers.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
"""
g.clog.debug('Entering postJSON')
# encode data as json
json_dat... |
def createJSON(g, full=True):
"""
Create JSON compatible dictionary from current settings
Parameters
----------
g : hcam_drivers.globals.Container
Container with globals
"""
data = dict()
if 'gps_attached' not in g.cpars:
data['gps_attached'] = 1
else:
data['gps... |
def insertFITSHDU(g):
"""
Uploads a table of TCS data to the servers, which is appended onto a run.
Arguments
---------
g : hcam_drivers.globals.Container
the Container object of application globals
"""
if not g.cpars['hcam_server_on']:
g.clog.warn('insertFITSHDU: servers ar... |
def execCommand(g, command, timeout=10):
"""
Executes a command by sending it to the rack server
Arguments:
g : hcam_drivers.globals.Container
the Container object of application globals
command : (string)
the command (see below)
Possible commands are:
start : s... |
def isRunActive(g):
"""
Polls the data server to see if a run is active
"""
if g.cpars['hcam_server_on']:
url = g.cpars['hipercam_server'] + 'summary'
response = urllib.request.urlopen(url, timeout=2)
rs = ReadServer(response.read(), status_msg=True)
if not rs.ok:
... |
def getFrameNumber(g):
"""
Polls the data server to find the current frame number.
Throws an exceotion if it cannot determine it.
"""
if not g.cpars['hcam_server_on']:
raise DriverError('getRunNumber error: servers are not active')
url = g.cpars['hipercam_server'] + 'status/DET.FRAM2.NO... |
def getRunNumber(g):
"""
Polls the data server to find the current run number. Throws
exceptions if it can't determine it.
"""
if not g.cpars['hcam_server_on']:
raise DriverError('getRunNumber error: servers are not active')
url = g.cpars['hipercam_server'] + 'summary'
response = url... |
def checkSimbad(g, target, maxobj=5, timeout=5):
"""
Sends off a request to Simbad to check whether a target is recognised.
Returns with a list of results, or raises an exception if it times out
"""
url = 'http://simbad.u-strasbg.fr/simbad/sim-script'
q = 'set limit ' + str(maxobj) + \
'... |
def run(self):
"""
Version of run that traps Exceptions and stores
them in the fifo
"""
try:
threading.Thread.run(self)
except Exception:
t, v, tb = sys.exc_info()
error = traceback.format_exception_only(t, v)[0][:-1]
tback ... |
def rand_str(charset, length=32):
"""
Generate random string.
"""
return "".join([random.choice(charset) for _ in range(length)]) |
def get_root(w):
"""
Simple method to access root for a widget
"""
next_level = w
while next_level.master:
next_level = next_level.master
return next_level |
def addStyle(w):
"""
Styles the GUI: global fonts and colours.
Parameters
----------
w : tkinter.tk
widget element to style
"""
# access global container in root widget
root = get_root(w)
g = root.globals
fsize = g.cpars['font_size']
family = g.cpars['font_family']
... |
def init(main_dir: Path, logfile_path: Path, log_level: str):
"""
Initialize the _downloader. TODO.
:param main_dir: main directory
:type main_dir: ~pathlib.Path
:param logfile_path: logfile path
:type logfile_path: ~pathlib.Path
:param log_level: logging level
:type log_level: str
... |
def download_from_plugin(plugin: APlugin):
"""
Download routine.
1. get newest update time
2. load savestate
3. compare last update time with savestate time
4. get download links
5. compare with savestate
6. download new/updated data
7. check downloads
8. update savestate
9.... |
def run(plugin_name: str, options: List[str] = None) -> PluginState:
"""
Run a plugin so use the download routine and clean up after.
:param plugin_name: name of plugin
:type plugin_name: str
:param options: parameters which will be send to the plugin initialization
:type options: List[str]
... |
def check_update():
"""
Check for app updates and print/log them.
"""
logging.info('Check for app updates.')
try:
update = updater.check_for_app_updates()
except Exception:
logging.exception('Check for updates failed.')
return
if update:
print("!!! UPDATE AVAI... |
def get_newest_app_version() -> Version:
"""
Download the version tag from remote.
:return: version from remote
:rtype: ~packaging.version.Version
"""
with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man:
pypi_json = p_man.urlopen('GET', static_data.PYP... |
def setupNodding(self):
"""
Setup Nodding for GTC
"""
g = get_root(self).globals
if not self.nod():
# re-enable clear mode box if not drift
if not self.isDrift():
self.clear.enable()
# clear existing nod pattern
se... |
def dumpJSON(self):
"""
Encodes current parameters to JSON compatible dictionary
"""
numexp = self.number.get()
expTime, _, _, _, _ = self.timing()
if numexp == 0:
numexp = -1
data = dict(
numexp=self.number.value(),
app=self.a... |
def loadJSON(self, json_string):
"""
Loads in an application saved in JSON format.
"""
g = get_root(self).globals
data = json.loads(json_string)['appdata']
# first set the parameters which change regardless of mode
# number of exposures
numexp = data.get('... |
def check(self, *args):
"""
Callback to check validity of instrument parameters.
Performs the following tasks:
- spots and flags overlapping windows or null window parameters
- flags windows with invalid dimensions given the binning parameter
- sets the corre... |
def freeze(self):
"""
Freeze all settings so they cannot be altered
"""
self.app.disable()
self.clear.disable()
self.nod.disable()
self.led.disable()
self.dummy.disable()
self.readSpeed.disable()
self.expose.disable()
self.number.di... |
def unfreeze(self):
"""
Reverse of freeze
"""
self.app.enable()
self.clear.enable()
self.nod.enable()
self.led.enable()
self.dummy.enable()
self.readSpeed.enable()
self.expose.enable()
self.number.enable()
self.wframe.enable... |
def getRtplotWins(self):
""""
Returns a string suitable to sending off to rtplot when
it asks for window parameters. Returns null string '' if
the windows are not OK. This operates on the basis of
trying to send something back, even if it might not be
OK as a window setup... |
def timing(self):
"""
Estimates timing information for the current setup. You should
run a check on the instrument parameters before calling this.
Returns: (expTime, deadTime, cycleTime, dutyCycle)
expTime : exposure time per frame (seconds)
deadTime : dead time per ... |
def loadJSON(self, json_string):
"""
Sets the values of the run parameters given an JSON string
"""
g = get_root(self).globals
user = json.loads(json_string)['user']
def setField(widget, field):
val = user.get(field)
if val is not None:
... |
def dumpJSON(self):
"""
Encodes current parameters to JSON compatible dictionary
"""
g = get_root(self).globals
dtype = g.observe.rtype()
if dtype == 'bias':
target = 'BIAS'
elif dtype == 'flat':
target = 'FLAT'
elif dtype == 'dark'... |
def check(self, *args):
"""
Checks the validity of the run parameters. Returns
flag (True = OK), and a message which indicates the
nature of the problem if the flag is False.
"""
ok = True
msg = ''
g = get_root(self).globals
dtype = g.observe.rtyp... |
def freeze(self):
"""
Freeze all settings so that they can't be altered
"""
self.target.disable()
self.filter.configure(state='disable')
self.prog_ob.configure(state='disable')
self.pi.configure(state='disable')
self.observers.configure(state='disable')
... |
def unfreeze(self):
"""
Unfreeze all settings so that they can be altered
"""
g = get_root(self).globals
self.filter.configure(state='normal')
dtype = g.observe.rtype()
if dtype == 'data caution' or dtype == 'data' or dtype == 'technical':
self.prog_ob... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.