code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def async_from_options(options): _type = options.pop('_type', 'furious.async.Async') _type = path_to_reference(_type) return _type.from_dict(options)
Deserialize an Async or Async subclass from an options dict.
def sign(self, msg: Dict) -> Dict: ser = serialize_msg_for_signing(msg, topLevelKeysToIgnore=[f.SIG.nm]) bsig = self.naclSigner.signature(ser) sig = base58.b58encode(bsig).decode("utf-8") return sig
Return a signature for the given message.
def on_step_end(self, step, logs={}): self.total_steps += 1 if self.total_steps % self.interval != 0: return filepath = self.filepath.format(step=self.total_steps, **logs) if self.verbose > 0: print('Step {}: saving model to {}'.format(self.total_steps, filepath))...
Save weights at interval steps during training
def mul(a, b): if a is None: if b is None: return None else: return b elif b is None: return a return a * b
Multiply two values, ignoring None
def dump(self, **kwargs): f = io.StringIO() w = Writer(f, self.keys, **kwargs) w.write(self) text = f.getvalue().lstrip() f.close() return text
CSV representation of a item.
def changed(self): if not self.parents: return [] return ChangedFileNodesGenerator([n for n in self._get_paths_for_status('modified')], self)
Returns list of modified ``FileNode`` objects.
def _make_examples(bam_file, data, ref_file, region_bed, out_file, work_dir): log_dir = utils.safe_makedir(os.path.join(work_dir, "log")) example_dir = utils.safe_makedir(os.path.join(work_dir, "examples")) if len(glob.glob(os.path.join(example_dir, "%s.tfrecord*.gz" % dd.get_sample_name(data)))) == 0: ...
Create example pileup images to feed into variant calling.
def read(sensor): import time import RPi.GPIO as GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) if sensor.gpio_in is 0: raise RuntimeError('gpio_in, gpio_out attribute of Sensor object must be assigned before calling read') else: gpio_in = sensor.gpio_in gpio_out = s...
distance of object in front of sensor in CM.
def Read(self, expected_ids, read_data=True): if self.send_idx: self._Flush() header_data = self._ReadBuffered(self.recv_header_len) header = struct.unpack(self.recv_header_format, header_data) command_id = self.wire_to_id[header[0]] if command_id not in expected_ids:...
Read ADB messages and return FileSync packets.
def title(self, title, show=False): self._write("title:%d:%s\n" % (int(show), title)) return self
writes a title tag to the Purr pipe
def xml_entity_escape(data): data = data.replace("&", "&amp;") data = data.replace(">", "&gt;") data = data.replace("<", "&lt;") return data
replace special characters with their XML entity versions
def tick(self): for npc in self.npcs: self.move_entity(npc, *npc.towards(self.player)) for entity1, entity2 in itertools.combinations(self.entities, 2): if (entity1.x, entity1.y) == (entity2.x, entity2.y): if self.player in (entity1, entity2): ...
Returns a message to be displayed if game is over, else None
def cleanup(output_root): if os.path.exists(output_root): if os.path.isdir(output_root): rmtree(output_root) else: os.remove(output_root)
Remove any reST files which were generated by this extension
def json_decode(s: str) -> Any: try: return json.JSONDecoder(object_hook=json_class_decoder_hook).decode(s) except json.JSONDecodeError: log.warning("Failed to decode JSON (returning None): {!r}", s) return None
Decodes an object from JSON using our custom decoder.
def _cellChunk(self, lines): KEYWORDS = ('CELLIJ', 'NUMPIPES', 'SPIPE') result = {'i': None, 'j': None, 'numPipes': None, 'spipes': []} chunks = pt.chunk(KEYWORDS, lines) for card, chunkList in ...
Parse CELLIJ Chunk Method
def _get_geometry(self): return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list])
Creates a multipolygon of bounding box polygons
def _map_in_out(self, inside_var_name): for out_name, in_name in self.outside_name_map.items(): if inside_var_name == in_name: return out_name return None
Return the external name of a variable mapped from inside.
def _get_xtool(): for xtool in ['xl', 'xm']: path = salt.utils.path.which(xtool) if path is not None: return path
Internal, returns xl or xm command line path
def label_empty(self, **kwargs): "Label every item with an `EmptyLabel`." kwargs['label_cls'] = EmptyLabelList return self.label_from_func(func=lambda o: 0., **kwargs)
Label every item with an `EmptyLabel`.
def disable_key(self): print("This command will disable a enabled key.") apiKeyID = input("API Key ID: ") try: key = self._curl_bitmex("/apiKey/disable", postdict={"apiKeyID": apiKeyID}) print("Key with ID %s disabled." % key["id"]) ...
Disable an existing API Key.
def load_img(name): fullname = name try: image = pygame.image.load(fullname) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() except pygame.error, message: print "Error: couldn't load image: ", fullname ...
Load image and return an image object
def make(directory): if os.path.exists(directory): if os.path.isdir(directory): click.echo('Directory already exists') else: click.echo('Path exists and is not a directory') sys.exit() os.makedirs(directory) os.mkdir(os.path.join(directory, 'jsons')) copy_...
Makes a RAS Machine directory
async def _recover_jobs(self, agent_addr): for (client_addr, job_id), (agent, job_msg, _) in reversed(list(self._job_running.items())): if agent == agent_addr: await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendJobDone...
Recover the jobs sent to a crashed agent
def normalize(self): self.routes.sort(key=lambda route: route.name) self.data_types.sort(key=lambda data_type: data_type.name) self.aliases.sort(key=lambda alias: alias.name) self.annotations.sort(key=lambda annotation: annotation.name)
Alphabetizes routes to make route declaration order irrelevant.
def flattened(self, order=None, include_smaller=True): if order is None: order = self.order else: order = self._validate_order(order) flat = set(self[order]) for order_i in range(0, order): shift = 2 * (order - order_i) for cell in self[ord...
Return a flattened pixel collection at a single order.
def keep_season(show, keep): deleted = 0 print('%s Cleaning %s to latest season.' % (datestr(), show.title)) for season in show.seasons()[:-1]: for episode in season.episodes(): delete_episode(episode) deleted += 1 return deleted
Keep only the latest season.
def dropout_mask(x:Tensor, sz:Collection[int], p:float): "Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element." return x.new(*sz).bernoulli_(1-p).div_(1-p)
Return a dropout mask of the same type as `x`, size `sz`, with probability `p` to cancel an element.
def _get_scope_with_mangled(self, name): scope = self while True: parent = scope.get_enclosing_scope() if parent is None: return if name in parent.rev_mangled: return parent scope = parent
Return a scope containing passed mangled name.
def compressedpubkey(self): secret = unhexlify(repr(self._wif)) order = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1).curve.generator.order() p = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1).verifying_key.pubkey.point x_str = ecdsa.u...
Derive uncompressed public key
def clean_total_refund_amount(self): initial = self.cleaned_data.get('initial_refund_amount', 0) total = self.cleaned_data['total_refund_amount'] summed_refunds = sum([v for k,v in self.cleaned_data.items() if k.startswith('item_refundamount_')]) if not self.cleaned_data.get('id'): ...
The Javascript should ensure that the hidden input is updated, but double check it here.
def clicked(self, px, py): if self.hidden: return None if (abs(px - self.posx) > self.width/2 or abs(py - self.posy) > self.height/2): return None return math.sqrt((px-self.posx)**2 + (py-self.posy)**2)
see if the image has been clicked on
def litecoin_withdrawal(self, amount, address): data = {'amount': amount, 'address': address} return self._post("ltc_withdrawal/", data=data, return_json=True, version=2)
Send litecoins to another litecoin wallet specified by address.
def read_d1_letter(fin_txt): go2letter = {} re_goid = re.compile(r"(GO:\d{7})") with open(fin_txt) as ifstrm: for line in ifstrm: mtch = re_goid.search(line) if mtch and line[:1] != ' ': go2letter[mtch.group(1)] = line[:1] return go2letter
Reads letter aliases from a text file created by GoDepth1LettersWr.
def list_names(cls): response = subwrap.run(['lxc-ls']) output = response.std_out return map(str.strip, output.splitlines())
Lists all known LXC names
def update(self, other: 'Language') -> 'Language': return Language.make( language=other.language or self.language, extlangs=other.extlangs or self.extlangs, script=other.script or self.script, region=other.region or self.region, variants=other.variants...
Update this Language with the fields of another Language.
def execute(self, parents=None): results = OrderedDict() for row in self.query(parents=parents).execute(self.context.graph): data = {k: v.toPython() for (k, v) in row.asdict().items()} id = data.get(self.id) if id not in results: results[id] = self.bas...
Run the data query and construct entities from it's results.
def generate(env): path, cxx, shcxx, version = get_cppc(env) if path: cxx = os.path.join(path, cxx) shcxx = os.path.join(path, shcxx) cplusplus.generate(env) env['CXX'] = cxx env['SHCXX'] = shcxx env['CXXVERSION'] = version env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS -K...
Add Builders and construction variables for SunPRO C++.
def discounted_return(reward, length, discount): timestep = tf.range(reward.shape[1].value) mask = tf.cast(timestep[None, :] < length[:, None], tf.float32) return_ = tf.reverse(tf.transpose(tf.scan( lambda agg, cur: cur + discount * agg, tf.transpose(tf.reverse(mask * reward, [1]), [1, 0]), tf.z...
Discounted Monte-Carlo returns.
def next_frame_sv2p_cutoff(): hparams = next_frame_sv2p() hparams.video_modality_loss_cutoff = 0.4 hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 1 return hparams
SV2P model with additional cutoff in L2 loss for environments like pong.
def import_job(db, calc_id, calc_mode, description, user_name, status, hc_id, datadir): job = dict(id=calc_id, calculation_mode=calc_mode, description=description, user_name=user_name, hazard_calculation_id=hc_id, is_running=0...
Insert a calculation inside the database, if calc_id is not taken
def key_sign(rsakey, message, digest): padding = _asymmetric.padding.PKCS1v15() signature = rsakey.sign(message, padding, digest) return signature
Sign the given message with the RSA key.
def _recurse_find_trace(self, structure, item, trace=[]): try: i = structure.index(item) except ValueError: for j,substructure in enumerate(structure): if isinstance(substructure, list): return self._recurse_find_trace(substructure, item, trace...
given a nested structure from _parse_repr and find the trace route to get to item
def _filter_classes(cls_list, cls_type): for cls in cls_list: if isinstance(cls, type) and issubclass(cls, cls_type): if cls_type == TempyPlace and cls._base_place: pass else: yield cls
Filters a list of classes and yields TempyREPR subclasses
def ModelDir(self): model_dir = self.Parameters['model_output_dir'].Value absolute_model_dir = os.path.abspath(model_dir) return FilePath(absolute_model_dir)
Absolute FilePath to the training output directory.
def process(self, metric): self.queue.append(metric) if len(self.queue) >= self.queue_size: logging.debug("Queue is full, sending logs to Logentries") self._send()
Process metric by sending it to datadog api
def _path_pair(self, s): if s.startswith(b'"'): parts = s[1:].split(b'" ', 1) else: parts = s.split(b' ', 1) if len(parts) != 2: self.abort(errors.BadFormat, '?', '?', s) elif parts[1].startswith(b'"') and parts[1].endswith(b'"'): parts[1] ...
Parse two paths separated by a space.
def __protocolize(base_url): if not base_url.startswith("http://") and not base_url.startswith("https://"): base_url = "https://" + base_url base_url = base_url.rstrip("/") return base_url
Internal add-protocol-to-url helper
def readkmz(self, filename): filename.strip('"') if filename[-4:] == '.kml': fo = open(filename, "r") fstring = fo.read() fo.close() elif filename[-4:] == '.kmz': zip=ZipFile(filename) for z in zip.filelist: if z.filenam...
reads in a kmz file and returns xml nodes
def parse_rdp_assignment(line): toks = line.strip().split('\t') seq_id = toks.pop(0) direction = toks.pop(0) if ((len(toks) % 3) != 0): raise ValueError( "Expected assignments in a repeating series of (rank, name, " "confidence), received %s" % toks) assignments = [] ...
Returns a list of assigned taxa from an RDP classification line
def wait_for_ribcl_firmware_update_to_complete(ribcl_object): def is_ilo_reset_initiated(): try: LOG.debug(ribcl_object._('Checking for iLO reset...')) ribcl_object.get_product_name() return False except exception.IloError: LOG.debug(ribcl_object._('iL...
Continuously checks for iLO firmware update to complete.
def update_room(room): if room.custom_server: return def _update_room(xmpp): muc = xmpp.plugin['xep_0045'] muc.joinMUC(room.jid, xmpp.requested_jid.user) muc.configureRoom(room.jid, _set_form_values(xmpp, room, muc.getRoomConfig(room.jid))) current_plugin.logger.info('Updatin...
Updates a MUC room on the XMPP server.
def _effectupdate_enlarge_font_on_focus(self, time_passed): data = self._effects['enlarge-font-on-focus'] fps = data['raise_font_ps'] final_size = data['size'] * data['enlarge_factor'] for i, option in enumerate(self.options): if i == self.option: if option['f...
Gradually enlarge the font size of the focused line.
def do_console(self) -> None: if not self._console_enabled: self._sout.write('Python console disabled for this sessiong\n') self._sout.flush() return h, p = self._host, self._console_port log.info('Starting console at %s:%d', h, p) fut = init_console_s...
Switch to async Python REPL
def serveMiniMonth(self, request, year=None, month=None): if not request.is_ajax(): raise Http404("/mini/ is for ajax requests only") today = timezone.localdate() if year is None: year = today.year if month is None: month = today.month year = int(year) month =...
Serve data for the MiniMonth template tag.
def send_notification(self, title, message, typ=1, url=None, sender=None): self.user.send_notification(title=title, message=message, typ=typ, url=url, sender=sender)
sends a message to user of this role's private mq exchange
def _ensure_arraylike(values): if not is_array_like(values): inferred = lib.infer_dtype(values, skipna=False) if inferred in ['mixed', 'string', 'unicode']: if isinstance(values, tuple): values = list(values) values = construct_1d_object_array_from_listlike(va...
ensure that we are arraylike if not already
def add_to_history(self, command): command = to_text_string(command) if command in ['', '\n'] or command.startswith('Traceback'): return if command.endswith('\n'): command = command[:-1] self.histidx = None if len(self.history) > 0 and self.history[...
Add command to history
def extract_audio(filename, channels=1, rate=16000): temp = tempfile.NamedTemporaryFile(suffix='.wav', delete=False) if not os.path.isfile(filename): print("The given file does not exist: {}".format(filename)) raise Exception("Invalid filepath: {}".format(filename)) if not which("ffmpeg"): ...
Extract audio from an input file to a temporary WAV file.
def _get_iris_args(attrs): import cf_units args = {'attributes': _filter_attrs(attrs, iris_forbidden_keys)} args.update(_pick_attrs(attrs, ('standard_name', 'long_name',))) unit_args = _pick_attrs(attrs, ('calendar',)) if 'units' in attrs: args['units'] = cf_units.Unit(attrs['units'], **unit...
Converts the xarray attrs into args that can be passed into Iris
def reject_recursive_repeats(to_wrap): to_wrap.__already_called = {} @functools.wraps(to_wrap) def wrapped(*args): arg_instances = tuple(map(id, args)) thread_id = threading.get_ident() thread_local_args = (thread_id,) + arg_instances if thread_local_args in to_wrap.__already...
Prevent simple cycles by returning None when called recursively with same instance
def printdata(self) -> None: np.set_printoptions(threshold=np.nan) print(self.data) np.set_printoptions(threshold=1000)
Prints data to stdout
async def get_content_count(self, source: str): params = {"uri": source, "type": None, "target": "all", "view": "flat"} return ContentInfo.make( **await self.services["avContent"]["getContentCount"](params) )
Return file listing for source.
def _create_mappings(self, spec): ret = dict(zip(set(spec.fields), set(spec.fields))) ret.update(dict([(n, s.alias) for n, s in spec.fields.items() if s.alias])) return ret
Create property name map based on aliases.
def post(self): self.reqparse.add_argument('namespacePrefix', type=str, required=True) self.reqparse.add_argument('description', type=str, required=True) self.reqparse.add_argument('key', type=str, required=True) self.reqparse.add_argument('value', required=True) self.reqparse.ad...
Create a new config item
def xray_requests_send(wrapped, instance, args, kwargs): return generic_xray_wrapper( wrapped, instance, args, kwargs, name='requests', namespace='remote', metadata_extractor=extract_http_metadata, )
Wrapper around the requests library's low-level send method.
def _check_buffer(self, data, ctype): assert ctype in _ffi_types.values() if not isinstance(data, bytes): data = _ffi.from_buffer(data) frames, remainder = divmod(len(data), self.channels * _ffi.sizeof(ctype)) if remainder: raise...
Convert buffer to cdata and check for valid size.
def peekiter(iterable): it = iter(iterable) one = next(it) def gen(): yield one while True: yield next(it) return (one, gen())
Return first row and also iterable with same items as original
def Wm(self): centroids = self.get_element_centroids() Wm = scipy.sparse.csr_matrix( (self.nr_of_elements, self.nr_of_elements)) for i, nb in enumerate(self.element_neighbors): for j, edges in zip(nb, self.element_neighbors_edges[i]): edge_coords = self.no...
Return the smoothing regularization matrix Wm of the grid
def replace_fields(meta, patterns): for pattern in patterns: try: field, regex, subst, _ = pattern.split(pattern[-1]) namespace = meta keypath = [i.replace('\0', '.') for i in field.replace('..', '\0').split('.')] for key in keypath[:-1]: names...
Replace patterns in fields.
def _enter_plotting(self, fontsize=9): self.original_fontsize = pyplot.rcParams['font.size'] pyplot.rcParams['font.size'] = fontsize pyplot.hold(False) pyplot.ioff()
assumes that a figure is open
def process_source(self): if isinstance(self.source, str): self.source = self.source.replace("'", "\'").replace('"', "\'") return "\"{source}\"".format(source=self.source) return self.source
Return source with transformations, if any
def new_run(self): self.current_run += 1 self.runs.append(RunData(self.current_run + 1))
Creates a new RunData object and increments pointers
async def guessImageMetadataFromHttpData(response): metadata = None img_data = bytearray() while len(img_data) < CoverSourceResult.MAX_FILE_METADATA_PEEK_SIZE: new_img_data = await response.content.read(__class__.METADATA_PEEK_SIZE_INCREMENT) if not new_img_data: break img_data.ext...
Identify an image format and size from the beginning of its HTTP data.
def _load(self): if os.path.exists(self.path): root = ET.parse(self.path).getroot() if (root.tag == "fortpy" and "mode" in root.attrib and root.attrib["mode"] == "template" and "direction" in root.attrib and root.attrib["direction"] == self.direction): ...
Extracts the XML template data from the file.
def rescale_gradients(self, scale: float): for exe in self.executors: for arr in exe.grad_arrays: if arr is None: continue arr *= scale
Rescales gradient arrays of executors by scale.
def sort(self): beams = [v for (_, v) in self.entries.items()] sortedBeams = sorted(beams, reverse=True, key=lambda x: x.prTotal*x.prText) return [x.labeling for x in sortedBeams]
return beam-labelings, sorted by probability
def probe(cls, resource, enable, disable, test, host, interval, http_method, http_response, threshold, timeout, url, window): params = { 'host': host, 'interval': interval, 'method': http_method, 'response': http_response, 'threshold': th...
Set a probe for a webaccelerator
def render_obs(self, obs): start_time = time.time() self._obs = obs self.check_valid_queued_action() self._update_camera(point.Point.build( self._obs.observation.raw_data.player.camera)) for surf in self._surfaces: surf.draw(surf) mouse_pos = self.get_mouse_pos() if mouse_pos: ...
Render a frame given an observation.
def node_updated(self, node): if self._capture_node and node == self._capture_node["node"] and node.status != "started": yield from self.stop_capture()
Called when a node member of the link is updated
def startswith_field(field, prefix): if prefix.startswith("."): return True if field.startswith(prefix): if len(field) == len(prefix) or field[len(prefix)] == ".": return True return False
RETURN True IF field PATH STRING STARTS WITH prefix PATH STRING
def share_settings(self, other, keylist=None, include_callbacks=True, callback=True): if keylist is None: keylist = self.group.keys() if include_callbacks: for key in keylist: oset, mset = other.group[key], self.group[key] ot...
Sharing settings with `other`
def from_frame(klass, frame, connection): event = frame.headers['new'] data = json.loads(frame.body) info = data['info'] build = Build.fromDict(info) build.connection = connection return klass(build, event)
Create a new BuildStateChange event from a Stompest Frame.
def _create_context_manager(self, mode): " Create a context manager that sends 'mode' commands to the client. " class mode_context_manager(object): def __enter__(*a): self.send_packet({'cmd': 'mode', 'data': mode}) def __exit__(*a): self.send_packe...
Create a context manager that sends 'mode' commands to the client.
def _names(lexer): first = _expect_token(lexer, {NameToken}).value rest = _zom_name(lexer) rnames = (first, ) + rest return rnames[::-1]
Return a tuple of names.
def prepare_axes(wave, flux, fig=None, ax_lower=(0.1, 0.1), ax_dim=(0.85, 0.65)): if not fig: fig = plt.figure() ax = fig.add_axes([ax_lower[0], ax_lower[1], ax_dim[0], ax_dim[1]]) ax.plot(wave, flux) return fig, ax
Create fig and axes if needed and layout axes in fig.
def load_sources(self, sources): self.clear() for s in sources: if isinstance(s, dict): s = Model.create_from_dict(s) self.load_source(s, build_index=False) self._build_src_index()
Delete all sources in the ROI and load the input source list.
def to_rec_single(samples, default_keys=None): out = [] for data in samples: recs = samples_to_records([normalize_missing(utils.to_single_data(data))], default_keys) assert len(recs) == 1 out.append(recs[0]) return out
Convert output into a list of single CWL records.
def headers_for_url(cls, url): response = cls.http_request(url, method='HEAD') if response.status != 200: cls.raise_http_error(response) return Resource.headers_as_dict(response)
Return the headers only for the given URL as a dict
def _make_fits(self): a = self.tests[self.active] args = self.curargs if len(args["fits"]) > 0: for fit in list(args["fits"].keys()): a.fit(args["independent"], fit, args["fits"][fit], args["threshold"], args["functions"])
Generates the data fits for any variables set for fitting in the shell.
def fire_failed_msisdn_lookup(self, to_identity): payload = {"to_identity": to_identity} hooks = Hook.objects.filter(event="identity.no_address") for hook in hooks: hook.deliver_hook( None, payload_override={"hook": hook.dict(), "data": payload} )
Fires a webhook in the event of a None to_addr.
def extract_tar (archive, compression, cmd, verbosity, interactive, outdir): cmdlist = [cmd, '--extract'] add_tar_opts(cmdlist, compression, verbosity) cmdlist.extend(["--file", archive, '--directory', outdir]) return cmdlist
Extract a TAR archive.
def write_bytes(self, data): if not isinstance(data, six.binary_type): raise TypeError( 'data must be %s, not %s' % (six.binary_type.__class__.__name__, data.__class__.__name__)) with self.open(mode='wb') as f: return f.write(data)
Open the file in bytes mode, write to it, and close the file.
def launch_in_notebook(self, port=9095, width=900, height=600): from IPython.lib import backgroundjobs as bg from IPython.display import HTML jobs = bg.BackgroundJobManager() jobs.new(self.launch, kw=dict(port=port)) frame = HTML( '<iframe src=http://localhost:{} widt...
launch the app within an iframe in ipython notebook
def getoptlist(self, p): optlist = [] for k, v in self.pairs: if k == p: optlist.append(v) return optlist
Returns all option values stored that match p as a list.
def _ref_key(self, key): queue = self.queue refcount = self.refcount queue.append(key) refcount[key] = refcount[key] + 1 if len(queue) > self.max_queue: refcount.clear() queue_appendleft = queue.appendleft queue_appendleft(self.sentinel) ...
Record a reference to the argument key.
def load_currency(self, mnemonic: str): if self.rate and self.rate.currency == mnemonic: return app = PriceDbApplication() symbol = SecuritySymbol("CURRENCY", mnemonic) self.rate = app.get_latest_price(symbol) if not self.rate: raise ValueError(f"No rate f...
load the latest rate for the given mnemonic; expressed in the base currency
def OnSearchDirectionButton(self, event): if "DOWN" in self.search_options: flag_index = self.search_options.index("DOWN") self.search_options[flag_index] = "UP" elif "UP" in self.search_options: flag_index = self.search_options.index("UP") self.search_opt...
Event handler for search direction toggle button
def _setProperty(self, _type, data, win=None, mask=None): if not win: win = self.root if type(data) is str: dataSize = 8 else: data = (data+[0]*(5-len(data)))[:5] dataSize = 32 ev = protocol.event.ClientMessage( window=win, ...
Send a ClientMessage event to the root window
def configure(self, ns, mappings=None, **kwargs): if mappings is None: mappings = dict() mappings.update(kwargs) for operation, definition in mappings.items(): try: configure_func = self._find_func(operation) except AttributeError: ...
Apply mappings to a namespace.
def segments (self): for n in xrange(len(self.vertices) - 1): yield Line(self.vertices[n], self.vertices[n + 1]) yield Line(self.vertices[-1], self.vertices[0])
Return the Line segments that comprise this Polygon.