code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def create_refund(self, refund_deets): request = self._post('transactions/refunds', refund_deets) return self.responder(request)
Creates a new refund transaction.
def process_request(self, request, response): self.logger.info('Requested: {0} {1} {2}'.format(request.method, request.relative_uri, request.content_type))
Logs the basic endpoint requested
def ListFlows(self): args = flow_pb2.ApiListFlowsArgs(client_id=self.client_id) items = self._context.SendIteratorRequest("ListFlows", args) return utils.MapItemsIterator( lambda data: flow.Flow(data=data, context=self._context), items)
List flows that ran on this client.
def encap(self, pkt): if pkt.name != Ether().name: raise TypeError('cannot encapsulate packet in MACsec, must be Ethernet') hdr = copy.deepcopy(pkt) payload = hdr.payload del hdr.payload tag = MACsec(sci=self.sci, an=self.an, SC=self.send_sci, ...
encapsulate a frame using this Secure Association
def i(msg, *args, **kwargs): return logging.log(INFO, msg, *args, **kwargs)
log a message at info level;
def kick(self, channel, target, reason=None): if reason: target += ' :' + reason self.send_line('KICK %s %s' % (channel, target), nowait=True)
kick target from channel
def go_to_next_cell(self): cursor = self.textCursor() cursor.movePosition(QTextCursor.NextBlock) cur_pos = prev_pos = cursor.position() while not self.is_cell_separator(cursor): cursor.movePosition(QTextCursor.NextBlock) prev_pos = cur_pos cur_p...
Go to the next cell of lines
def _create(self, cache_file): conn = sqlite3.connect(cache_file) cur = conn.cursor() cur.execute("PRAGMA foreign_keys = ON") cur.execute( ) cur.execute( ) conn.commit() conn.close()
Create the tables needed to store the information.
def _anova(self, dv=None, between=None, detailed=False, export_filename=None): aov = anova(data=self, dv=dv, between=between, detailed=detailed, export_filename=export_filename) return aov
Return one-way and two-way ANOVA.
def OnCardRightClick(self, event): item = event.GetItem() if item: itemdata = self.readertreepanel.cardtreectrl.GetItemPyData(item) if isinstance(itemdata, smartcard.Card.Card): self.selectedcard = itemdata if not hasattr(self, "connectID"): ...
Called when user right-clicks a node in the card tree control.
def parser(cls, v): return geoid.census.State.parse(str(v).zfill(2))
Ensure that the upstream parser gets two digits.
def debug(level=logging.DEBUG): from jcvi.apps.console import magenta, yellow format = yellow("%(asctime)s [%(module)s]") format += magenta(" %(message)s") logging.basicConfig(level=level, format=format, datefmt="%H:%M:%S")
Turn on the debugging
def index(self, child_pid): if not isinstance(child_pid, PersistentIdentifier): child_pid = resolve_pid(child_pid) relation = PIDRelation.query.filter_by( parent=self._resolved_pid, child=child_pid, relation_type=self.relation_type.id).one() return...
Index of the child in the relation.
def _get_module(self, line): for sline in self._source: if len(sline) > 0 and sline[0] != "!": rmatch = self.RE_MODULE.match(sline) if rmatch is not None: self.modulename = rmatch.group("name") break else: re...
Finds the name of the module and retrieves it from the parser cache.
def show_scan_report(audio_filepaths, album_dir, r128_data): for audio_filepath in audio_filepaths: try: loudness, peak = r128_data[audio_filepath] except KeyError: loudness, peak = "SKIPPED", "SKIPPED" else: loudness = "%.1f LUFS" % (loudness) if peak is None: peak = "-" ...
Display loudness scan results.
def register_halfmaxes(self, telescope, band, lower, upper): if (telescope, band) in self._halfmaxes: raise AlreadyDefinedError('half-max points for %s/%s already ' 'defined', telescope, band) self._note(telescope, band) self._halfmaxes[telescope...
Register precomputed half-max points.
def discard_incoming_messages(self): self.inbox.clear() previous = self._discard_incoming_messages self._discard_incoming_messages = True try: yield finally: self._discard_incoming_messages = previous
Discard all incoming messages for the time of the context manager.
def create_distant_reference(self, ref_data): self.validate_reference_data(ref_data) creation_status = self._zotero_lib.create_items([ref_data]) try: created_item = creation_status["successful"]["0"] return created_item except KeyError as e: print(crea...
Validate and create the reference in Zotero and return the created item.
def from_bs_date(cls, year, month, day): return NepDate(year, month, day).update()
Create and update an NepDate object for bikram sambat date
def parse(self): errors_tested = 0 for error in self.error_definitions: errors_tested += 1 result = self.parse_single(self.error_definitions[error]) if result[0]: self.errors.append(error(result[1], result[2])) if len(self.errors) > 0: ...
Parse for the occurens of all errors defined in ERRORS
def getData(file_id,ra,dec): DATA="www.cadc-ccda.hia-iha.nrc-cnrc.gc.ca" BASE="http://"+DATA+"/authProxy/getData" archive="CFHT" wcs="corrected" import re groups=re.match('^(?P<file_id>\d{6}).*',file_id) if not groups: return None file_id=groups.group('file_id') file_id+="p" ...
Create a link that connects to a getData URL
def copy_file(self, infile, outfile, check=True): self.ensure_dir(os.path.dirname(outfile)) logger.info('Copying %s to %s', infile, outfile) if not self.dry_run: msg = None if check: if os.path.islink(outfile): msg = '%s is a symlink' %...
Copy a file respecting dry-run and force flags.
def _get_directory_path(context): path = os.path.join(settings.BASE_PATH, 'store') path = context.params.get('path', path) path = os.path.join(path, context.crawler.name) path = os.path.abspath(os.path.expandvars(path)) try: os.makedirs(path) except Exception: pass return pat...
Get the storage path fro the output.
def convert(self, argument): if _is_integer_type(argument): return argument elif isinstance(argument, six.string_types): base = 10 if len(argument) > 2 and argument[0] == '0': if argument[1] == 'o': base = 8 elif argument[1] == 'x': base = 16 return in...
Returns the int value of argument.
def sparse_arrays(self, value): if not isinstance(value, bool): raise TypeError('sparse_arrays attribute must be a logical type.') self._sparse_arrays = value
Validate and enable spare arrays.
def make_event_data(self, flavor, data): if not flavor.startswith('_'): raise ValueError('Event flavor must start with _underscore') d = {'source': {'space': self._event_space, 'id': self._source_id}} d.update(data) return {flavor: d}
Marshall ``flavor`` and ``data`` into a standard event.
def _apply_uncertainty_to_geometry(self, source, value): if self.uncertainty_type == 'simpleFaultDipRelative': source.modify('adjust_dip', dict(increment=value)) elif self.uncertainty_type == 'simpleFaultDipAbsolute': source.modify('set_dip', dict(dip=value)) elif self.un...
Modify ``source`` geometry with the uncertainty value ``value``
def instance_provisioned(device_id): session = db.get_reader_session() with session.begin(): port_model = models_v2.Port res = bool(session.query(port_model) .filter(port_model.device_id == device_id).count()) return res
Returns true if any ports exist for an instance.
def validate(key, val): if val and val.startswith("~/"): return os.path.expanduser(val) if key == "output_header_frequency": return int(val, 10) if key.endswith("_ecma48"): return eval("'%s'" % val.replace("'", r"\'")) return val
Validate a configuration value.
def setOverlayInputMethod(self, ulOverlayHandle, eInputMethod): fn = self.function_table.setOverlayInputMethod result = fn(ulOverlayHandle, eInputMethod) return result
Sets the input settings for the specified overlay.
def syncParamList(self, firstTime, preserve_order=True): new_list = self._getParamsFromConfigDict(self, initialPass=firstTime) if self._forUseWithEpar: new_list.append(basicpar.IrafParS(['$nargs','s','h','N'])) if len(self.__paramList) > 0 and preserve_order: namesInOrder...
Set or reset the internal param list from the dict's contents.
def turn_left(): motors.left_motor(150) motors.right_motor(150) board.sleep(0.5) motors.brake(); board.sleep(0.1)
turns RedBot to the Left
def make_subgraph(graph, vertices, edges): local_graph = copy.deepcopy(graph) edges_to_delete = [x for x in local_graph.get_all_edge_ids() if x not in edges] for e in edges_to_delete: local_graph.delete_edge_by_id(e) nodes_to_delete = [x for x in local_graph.get_all_node_ids() if x not in vertic...
Converts a subgraph given by a list of vertices and edges into a graph object.
def _get_hanging_wall_term(self, C, rup, dists): return (C["c10"] * self._get_hanging_wall_coeffs_rx(C, rup, dists.rx) * self._get_hanging_wall_coeffs_rrup(dists) * self._get_hanging_wall_coeffs_mag(C, rup.mag) * self._get_hanging_wall_coeffs_ztor(...
Returns the hanging wall scaling term defined in equations 7 to 16
def trim(self): now_time = time.time() while self._seq and self._seq[0].expire_time < now_time: item = self._seq.popleft() del self._map[item.key] if self._max_items: while self._seq and len(self._seq) > self._max_items: item = self._seq.poplef...
Remove items that are expired or exceed the max size.
def visit_name(self, node, parent): context = self._get_context(node) if context == astroid.Del: newnode = nodes.DelName(node.id, node.lineno, node.col_offset, parent) elif context == astroid.Store: newnode = nodes.AssignName(node.id, node.lineno, node.col_offset, parent)...
visit a Name node by returning a fresh instance of it
def install(self): packages = self.packages() if packages: print("") for pkg in packages: ver = SBoGrep(pkg).version() prgnam = "{0}-{1}".format(pkg, ver) if find_package(prgnam, self.meta.output): binary = slack...
Install packages from queue
def custom_popen(cmd): creationflags = 0 if sys.platform == 'win32': creationflags = 0x08000000 try: p = Popen(cmd, bufsize=0, stdout=PIPE, stdin=PIPE, stderr=STDOUT, creationflags=creationflags) except OSError as ex: if ex.errno == errno.ENOENT: rai...
Disconnect cmd from parent fds, read only from stdout.
def create_user_profile(sender, instance, created, **kwargs): if created: profile = UserProfile.objects.get_or_create(user=instance)[0] profile.hash_pass = create_htpasswd(instance.hash_pass) profile.save() else: try: up = UserProfile.objects.get(user=instance.id) ...
Create the UserProfile when a new User is saved
def list_wallet_names(api_key, is_hd_wallet=False, coin_symbol='btc'): assert is_valid_coin_symbol(coin_symbol), coin_symbol assert api_key params = {'token': api_key} kwargs = dict(wallets='hd' if is_hd_wallet else '') url = make_url(coin_symbol, **kwargs) r = requests.get(url, params=params, v...
Get all the wallets belonging to an API key
def combine_xml_points(l, units, handle_units): ret = {} for item in l: for key, value in item.items(): ret.setdefault(key, []).append(value) for key, value in ret.items(): if key != 'date': ret[key] = handle_units(value, units.get(key, None)) return ret
Combine multiple Point tags into an array.
def date_to_um_date(date): assert date.hour == 0 and date.minute == 0 and date.second == 0 return [date.year, date.month, date.day, 0, 0, 0]
Convert a date object to 'year, month, day, hour, minute, second.'
def analyze(self, scratch, **kwargs): changes = dict((x.name, self.sprite_changes(x)) for x in scratch.sprites) changes['stage'] = { 'background': self.attribute_state(scratch.stage.scripts, 'costume')} return {'in...
Run and return the results of the AttributeInitialization plugin.
def serialize_dict(self, msg_dict): serialized = json.dumps(msg_dict, namedtuple_as_object=False) if PY2: serialized = serialized.decode("utf-8") serialized = "{}\nend\n".format(serialized) return serialized
Serialize to JSON a message dictionary.
def _badlink(info, base): tip = _resolved(os.path.join(base, os.path.dirname(info.name))) return _badpath(info.linkname, base=tip)
Links are interpreted relative to the directory containing the link
def new_from_memory(cls, data): size = len(data) copy = g_memdup(data, size) ptr = cast(copy, POINTER(guint8)) try: with gerror(GIError) as error: return GITypelib._new_from_memory(ptr, size, error) except GIError: free(copy) ra...
Takes bytes and returns a GITypelib, or raises GIError
def engine_data(engine): views = ("default", "main", "started", "stopped", "complete", "incomplete", "seeding", "leeching", "active", "messages") methods = [ "throttle.global_up.rate", "throttle.global_up.max_rate", "throttle.global_down.rate", "throttle.global_down.max_rate", ]...
Get important performance data and metadata from rTorrent.
def random_population(dna_size, pop_size, tune_params): population = [] for _ in range(pop_size): dna = [] for i in range(dna_size): dna.append(random_val(i, tune_params)) population.append(dna) return population
create a random population
def force_invalidate(self, cache_key): try: if self.cacheable(cache_key): os.unlink(self._sha_file(cache_key)) except OSError as e: if e.errno != errno.ENOENT: raise
Force-invalidate the cached item.
def properties_changed(self, sender, changed_properties, invalidated_properties): if 'Connected' in changed_properties: if changed_properties['Connected']: self.connect_succeeded() else: self.disconnect_succeeded() if ('ServicesResolved' in changed...
Called when a device property has changed or got invalidated.
def background_reader(stream, loop: asyncio.AbstractEventLoop, callback): for line in iter(stream.readline, b''): loop.call_soon_threadsafe(loop.create_task, callback(line))
Reads a stream and forwards each line to an async callback.
def include_block(self, x): last_pos = self._chr_last_blocks.get(x.chrom, 0) if last_pos <= self._end_buffer and x.stop >= self._ref_sizes.get(x.chrom, 0) - self._end_buffer: return True elif self._ref_sizes.get(x.chrom, 0) <= self._target_size: return False elif ...
Check for inclusion of block based on distance from previous.
def dispatch(self, request, *args, **kwargs): self.request = request self.args = args self.kwargs = kwargs response = self.check_permissions(request) if response: return response return super().dispatch(request, *args, **kwargs)
Dispatches an incoming request.
def subsystem_dependencies_iter(cls): for dep in cls.subsystem_dependencies(): if isinstance(dep, SubsystemDependency): yield dep else: yield SubsystemDependency(dep, GLOBAL_SCOPE, removal_version=None, removal_hint=None)
Iterate over the direct subsystem dependencies of this Optionable.
def import_spydercustomize(): here = osp.dirname(__file__) parent = osp.dirname(here) customize_dir = osp.join(parent, 'customize') while '' in sys.path: sys.path.remove('') site.addsitedir(customize_dir) import spydercustomize try: sys.path.remove(customize_dir) except V...
Import our customizations into the kernel.
def _generate_throw_error(self, name, reason): throw_exc = '@throw([NSException exceptionWithName:@"{}" reason:{} userInfo:nil]);' self.emit(throw_exc.format(name, reason))
Emits a generic error throwing line.
def create_product(name, abbreviation, **kwargs): data = create_product_raw(name, abbreviation, **kwargs) if data: return utils.format_json(data)
Create a new Product
def _convertNonZeroToFailure(self, res): "utility method to handle the result of getProcessOutputAndValue" (stdout, stderr, code) = res if code != 0: raise EnvironmentError( 'command failed with exit code %d: %s' % (code, stderr)) return (stdout, stderr, code)
utility method to handle the result of getProcessOutputAndValue
def add_permalink_methods(content_inst): for permalink_method in PERMALINK_METHODS: setattr( content_inst, permalink_method.__name__, permalink_method.__get__(content_inst, content_inst.__class__))
Add permalink methods to object
def amended_commits(commits): amended_sha1s = [] for message in commits.values(): amended_sha1s.extend(re.findall(r'AMENDS\s([0-f]+)', message)) return amended_sha1s
Return those git commit sha1s that have been amended later.
def drunk_value(grid): "Return the expected value to the player if both players play at random." if is_won(grid): return -1 succs = successors(grid) return -average(map(drunk_value, succs)) if succs else 0
Return the expected value to the player if both players play at random.
def _init_dbus(self): _bus = SessionBus() if self.device_id is None: self.device_id = self._get_device_id(_bus) if self.device_id is None: return False try: self._dev = _bus.get(SERVICE_BUS, DEVICE_PATH + "/%s" % self.device_id) except ...
Get the device id
def privateparts(self, domain): s = self.privatesuffix(domain) if s is None: return None else: pre = domain[0:-(len(s)+1)] if pre == "": return (s,) else: return tuple(pre.split(".") + [s])
Return tuple of labels and the private suffix.
def _process_token(cls, token): assert type(token) is _TokenType or callable(token), \ 'token type must be simple type or callable, not %r' % (token,) return token
Preprocess the token component of a token definition.
def draw_header(canvas): canvas.setStrokeColorRGB(0.9, 0.5, 0.2) canvas.setFillColorRGB(0.2, 0.2, 0.2) canvas.setFont('Helvetica', 16) canvas.drawString(18 * cm, -1 * cm, 'Invoice') canvas.drawInlineImage(settings.INV_LOGO, 1 * cm, -1 * cm, 250, 16) canvas.setLineWidth(4) canvas.line(0, -1.2...
Draws the invoice header
def _init_matrix(self, data, index, columns, dtype=None): data = prep_ndarray(data, copy=False) index, columns = self._prep_index(data, index, columns) data = {idx: data[:, i] for i, idx in enumerate(columns)} return self._init_dict(data, index, columns, dtype)
Init self from ndarray or list of lists.
def close(self): if self._protocol is not None: self._protocol.processor.close() del self._protocol
Closes connection to the server.
def setPoint(self, targetTemp): self.targetTemp = targetTemp self.Integrator = 0 self.Derivator = 0
Initilize the setpoint of PID.
def _closure_parent_pk(self): if hasattr(self, "%s_id" % self._closure_parent_attr): return getattr(self, "%s_id" % self._closure_parent_attr) else: parent = getattr(self, self._closure_parent_attr) return parent.pk if parent else None
What our parent pk is in the closure tree.
def generate_query(self): query = Q() ORed = [] for form in self._non_deleted_forms: if not hasattr(form, 'cleaned_data'): continue if form.cleaned_data['field'] == "_OR": ORed.append(query) query = Q() else: ...
Reduces multiple queries into a single usable query
def update(self): if "tag_groups" not in self._device_dict: return for group in self.tag_groups: group.update() for i in range(len(self._device_dict["tag_groups"])): tag_group_dict = self._device_dict["tag_groups"][i] for group in self.tag_groups: ...
Updates the dictionary of the device
def send_registered_email(self, user, user_email, request_email_confirmation): if not self.user_manager.USER_ENABLE_EMAIL: return if not self.user_manager.USER_SEND_REGISTERED_EMAIL: return email = user_email.email if user_email else user.email if request_email_confirmation: ...
Send the 'user has registered' notification email.
def browse(ctx): page_html = Path(ctx.config.sphinx.destdir)/"html"/"index.html" if not page_html.exists(): build(ctx, builder="html") assert page_html.exists() open_cmd = "open" if sys.platform.startswith("win"): open_cmd = "start" ctx.run("{open} {page_html}".format(open=open_c...
Open documentation in web browser.
def process(self, request, item): warn_untested() from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) params = model_to_dict(self, exclude=self.ADMIN_FIELDS) params['acct'] = self.acct params['creditcardtype'] = self.creditcardtype params['expdate'] ...
Do a direct payment.
def quit(self): try: self._client.write(sc_pb.Request(quit=sc_pb.RequestQuit())) except protocol.ConnectionError: pass finally: self.close()
Shut down the SC2 process.
def to_json(self, extras=None): extras = extras or {} to_dict = model_to_dict(self) to_dict.update(extras) return json.dumps(to_dict, cls=sel.serializers.JsonEncoder)
Convert a model into a json using the playhouse shortcut.
def _parse_config(config_file_path): config_file = open(config_file_path, 'r') config = yaml.load(config_file) config_file.close() return config
Parse Config File from yaml file.
def log_url (self, url_data, priority=None): self.xml_starttag(u'url') self.xml_tag(u'loc', url_data.url) if url_data.modified: self.xml_tag(u'lastmod', self.format_modified(url_data.modified, sep="T")) self.xml_tag(u'changefreq', self.frequency) self.xml_tag(u'priori...
Log URL data in sitemap format.
def create_permissions(): current_app.appbuilder.add_permissions(update_perms=True) click.echo(click.style("Created all permissions", fg="green"))
Creates all permissions and add them to the ADMIN Role.
def from_group(cls, group): if not group: return tag_items = group.split(";") return list(map(cls.parse, tag_items))
Construct tags from the regex group
def to_unit(value, unit='B'): byte_array = ['B', 'KB', 'MB', 'GB', 'TB'] if not isinstance(value, (int, float)): value = float(value) if unit in byte_array: result = value / 1024**byte_array.index(unit) return round(result, PRECISION), unit return value
Convert bytes to give unit.
def _SetupBotoConfig(self): project_id = self._GetNumericProjectId() try: boto_config.BotoConfig(project_id, debug=self.debug) except (IOError, OSError) as e: self.logger.warning(str(e))
Set the boto config so GSUtil works with provisioned service accounts.
def openEmbedded(self, name): ndx = self.toc.find(name) if ndx == -1: raise KeyError, "Member '%s' not found in %s" % (name, self.path) (dpos, dlen, ulen, flag, typcd, nm) = self.toc.get(ndx) if flag: raise ValueError, "Cannot open compressed archive %s in place" ...
Open a CArchive of name NAME embedded within this CArchive.
def _xorterm(lexer): prodterm = _prodterm(lexer) xorterm_prime = _xorterm_prime(lexer) if xorterm_prime is None: return prodterm else: return ('xor', prodterm, xorterm_prime)
Return an xor term expresssion.
def _symmetric_warp(c, magnitude:partial(uniform,size=4)=0, invert=False): "Apply symmetric warp of `magnitude` to `c`." m = listify(magnitude, 4) targ_pts = [[-1-m[3],-1-m[1]], [-1-m[2],1+m[1]], [1+m[3],-1-m[0]], [1+m[2],1+m[0]]] return _do_perspective_warp(c, targ_pts, invert)
Apply symmetric warp of `magnitude` to `c`.
def model_changed(self, model, prop_name, info): if self.parent is not None: self.parent.model_changed(model, prop_name, info)
This method notifies the parent state about changes made to the state element
def contract(self): if self.is_root(): return for c in self.children: if self.edge_length is not None and c.edge_length is not None: c.edge_length += self.edge_length self.parent.add_child(c) self.parent.remove_child(self)
Contract this ``Node`` by directly connecting its children to its parent
def iiif_image_key(obj): if isinstance(obj, ObjectVersion): bucket_id = obj.bucket_id version_id = obj.version_id key = obj.key else: bucket_id = obj.get('bucket') version_id = obj.get('version_id') key = obj.get('key') return u'{}:{}:{}'.format( bucke...
Generate the IIIF image key.
def int_to_base36(i): if six.PY2: char_set = '0123456789abcdefghijklmnopqrstuvwxyz' if i < 0: raise ValueError("Negative base36 conversion input.") if not isinstance(i, six.integer_types): raise TypeError("Non-integer base36 conversion input.") if i < 36: ...
Django on py2 raises ValueError on large values.
def remove_empty_dirs(path=None): if not path: path = settings.MEDIA_ROOT if not os.path.isdir(path): return False listdir = [os.path.join(path, filename) for filename in os.listdir(path)] if all(list(map(remove_empty_dirs, listdir))): os.rmdir(path) return True else:...
Recursively delete empty directories; return True if everything was deleted.
def broadcast_url(self, broadcast_id=None, stop=False, layout=False): url = self.api_url + '/v2/project/' + self.api_key + '/broadcast' if broadcast_id: url = url + '/' + broadcast_id if stop: url = url + '/stop' if layout: url = url + '/layout' ...
this method returns urls for working with broadcast
def with_decode(self, decode=True): return Nvim(self._session, self.channel_id, self.metadata, self.types, decode, self._err_cb)
Initialize a new Nvim instance.
def main(self) -> None: path = ask_path("where should the config be stored?", ".snekrc") conf = configobj.ConfigObj() tools = self.get_tools() for tool in tools: conf[tool] = getattr(self, tool)() conf.filename = path conf.write() print("Written config...
The main function for generating the config file
def create_handler(target: str): if target == 'stderr': return logging.StreamHandler(sys.stderr) elif target == 'stdout': return logging.StreamHandler(sys.stdout) else: return logging.handlers.WatchedFileHandler(filename=target)
Create a handler for logging to ``target``
def insert_system_path(opts, paths): if isinstance(paths, six.string_types): paths = [paths] for path in paths: path_options = {'path': path, 'root_dir': opts['root_dir']} prepend_root_dir(path_options, path_options) if (os.path.isdir(path_options['path']) and pat...
Inserts path into python path taking into consideration 'root_dir' option.
def jsonp(data, **json_kwargs): from uliweb import request if 'jsonp' in json_kwargs: cb = json_kwargs.pop('jsonp') else: cb = 'callback' begin = str(request.GET.get(cb)) if not begin: raise BadRequest("Can't found %s parameter in request's query_string" % cb) if not r_ca...
jsonp is callback key name
def param_fetch_all(self): if time.time() - getattr(self, 'param_fetch_start', 0) < 2.0: return self.param_fetch_start = time.time() self.param_fetch_in_progress = True self.mav.param_request_list_send(self.target_system, self.target_component)
initiate fetch of all parameters
def put_file(self, filename, index, doc_type, id=None, name=None): if id is None: request_method = 'POST' else: request_method = 'PUT' path = make_path(index, doc_type, id) doc = file_to_attachment(filename) if name: doc["_name"] = name ...
Store a file in a index
def color_text(text, color="none", bcolor="none", effect="none"): istty = False try: istty = sys.stdout.isatty() except: pass if not istty or not COLOR_ON: return text else: if not effect in COLOR_EFFET.keys(): effect = "none" if not color in COLOR...
Return a formated text with bash color
def remove_provenance_project_variables(): project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) existing_variable_names = project_context_scope.variableNames() existing_variables = {} for existing_variable_name in existing_variable_names: existing_variab...
Removing variables from provenance data.