code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def pretty_echo(cls, message): if cls.intty(): if message: from pprint import pprint pprint(message)
Display message using pretty print formatting.
def max_id_length(self): if config().identifiers() == "text": return max_id_length(len(self._todos)) else: try: return math.ceil(math.log(len(self._todos), 10)) except ValueError: return 0
Returns the maximum length of a todo ID, used for formatting purposes.
def new(cls, settings, *args, **kwargs): logger.debug('Initializing new "%s" Instance object' % settings['CLOUD']) cloud = settings['CLOUD'] if cloud == 'bare': self = BareInstance(settings=settings, *args, **kwargs) elif cloud == 'aws': self = AWSInstance(setting...
Create a new Cloud instance based on the Settings
def connected(func): @wraps(func) def wrapper(*args, **kwargs): self = args[0] if not self.connected: self.show_output("Not connected.") else: try: return func(*args, **kwargs) except APIError: self.show_output("ZooKeepe...
check connected, fails otherwise
def could_collide_hor(self, vpos, adsb_pkt): margin = self.asterix_settings.filter_dist_xy timeout = self.asterix_settings.filter_time alat = adsb_pkt.lat * 1.0e-7 alon = adsb_pkt.lon * 1.0e-7 avel = adsb_pkt.hor_velocity * 0.01 vvel = sqrt(vpos.vx**2 + vpos.vy**2) ...
return true if vehicle could come within filter_dist_xy meters of adsb vehicle in timeout seconds
def create_dhcprelay_ipv6(self): return DHCPRelayIPv6( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of DHCPRelayIPv6 services facade.
def add_image_history(self, data): self._ef['0th'][piexif.ImageIFD.ImageHistory] = json.dumps(data)
Add arbitrary string to ImageHistory tag.
def clean_up_datetime(obj_map): clean_map = {} for key, value in obj_map.items(): if isinstance(value, datetime.datetime): clean_map[key] = { 'year': value.year, 'month': value.month, 'day': value.day, 'hour': value.hour, ...
convert datetime objects to dictionaries for storage
def exclude_samples(in_file, out_file, to_exclude, ref_file, config, filters=None): include, exclude = _get_exclude_samples(in_file, to_exclude) if len(exclude) == 0: out_file = in_file elif not utils.file_exists(out_file): with file_transaction(config, out_file) as tx_out_file: ...
Exclude specific samples from an input VCF file.
def extract_xyz_matrix_from_chain(self, chain_id, atoms_of_interest = []): chains = [l[21] for l in self.structure_lines if len(l) > 21] chain_lines = [l for l in self.structure_lines if len(l) > 21 and l[21] == chain_id] return PDB.extract_xyz_matrix_from_pdb(chain_lines, atoms_of_interest = at...
Create a pandas coordinates dataframe from the lines in the specified chain.
def init_state(self): self.in_warc_response = False self.in_http_response = False self.in_payload = False
Sets the initial state of the state machine.
def _from_any(cls, spec): if isinstance(spec, str): spec = cls.from_file(spec) elif isinstance(spec, dict): spec = cls.from_dict(spec) elif not isinstance(spec, cls): raise context.TypeError("spec must be either an ApplicationSpec, " ...
Generic creation method for all types accepted as ``spec``
def _massage_data(self): self._xdata_massaged, self._ydata_massaged, self._eydata_massaged = self.get_processed_data() return self
Processes the data and stores it.
def _get_json_response(self, resp): if resp is not None and resp.text is not None: try: text = resp.text.strip('\n') if len(text) > 0: return json.loads(text) except ValueError as e: if self.debug: pr...
Parse a JSON response
def _get_id2upper(id2upper, item_id, item_obj): if item_id in id2upper: return id2upper[item_id] upper_ids = set() for upper_obj in item_obj.get_goterms_upper(): upper_id = upper_obj.item_id upper_ids.add(upper_id) upper_ids |= _get_id2upper(id2upper, upper_id, upper_obj) ...
Add the parent item IDs for one item object and their upper.
def scroll_to_item(self, index): spacing_between_items = self.scene.verticalSpacing() height_view = self.scrollarea.viewport().height() height_item = self.scene.itemAt(index).sizeHint().height() height_view_excluding_item = max(0, height_view - height_item) height_of_top_items = ...
Scroll to the selected item of ThumbnailScrollBar.
def _send_to_destination( self, destination, header, payload, transport_kwargs, add_path_step=True ): if header: header = header.copy() header["workflows-recipe"] = True else: header = {"workflows-recipe": True} dest_kwargs = transport_kwargs.copy(...
Helper function to send a message to a specific recipe destination.
def hacked_pep257(to_lint): def ignore(*args, **kwargs): pass pep257.check_blank_before_after_class = ignore pep257.check_blank_after_last_paragraph = ignore pep257.check_blank_after_summary = ignore pep257.check_ends_with_period = ignore pep257.check_one_liners = ignore pep257.check...
Check for the presence of docstrings, but ignore some of the options
def trionyx(request): return { 'TX_APP_NAME': settings.TX_APP_NAME, 'TX_LOGO_NAME_START': settings.TX_LOGO_NAME_START, 'TX_LOGO_NAME_END': settings.TX_LOGO_NAME_END, 'TX_LOGO_NAME_SMALL_START': settings.TX_LOGO_NAME_SMALL_START, 'TX_LOGO_NAME_SMALL_END': settings.TX_LOGO_NAME...
Add trionyx context data
def invalidate_model_cache(self): logger.info('Invalidating cache for table {0}'.format(self.model._meta.db_table)) if django.VERSION >= (1, 8): related_tables = set( [f.related_model._meta.db_table for f in self.model._meta.get_fields() if ((f.one_to_many or...
Invalidate model cache by generating new key for the model.
def increment(self): self.value += self.increment_size return self.value - self.increment_size
Increment our value, return the previous value.
def bytes(self, *args): if len(args) == 1 and isinstance(args[0], BTree.Cursor): cur = args[0] else: cur = self.btree.find('eq', self.makekey(*args)) if cur: return cur.getval()
return a raw value for the given arguments
def call_operation(self, operation, **kwargs): data = {'operation': operation} data.update(kwargs) return self.invoke(data)
A generic method to call any operation supported by the Lambda handler
def add_empty_etd_ms_fields(etd_ms_dict): for element in ETD_MS_ORDER: if element not in etd_ms_dict: try: py_object = ETD_MS_CONVERSION_DISPATCH[element]( content='', qualifier='', ) except: try:...
Add empty values for ETD_MS fields that don't have values.
def insert(self, thread): thread_id = thread['id'] title = thread['title'] self.db.threads.new(thread_id, title) comments = list(map(self._build_comment, thread['comments'])) comments.sort(key=lambda comment: comment['id']) self.count += len(comments) for comment ...
Process a thread and insert its comments in the DB.
def _get_relationship_value(self, obj, column): if column['__col__'].uselist: value = self._get_to_many_relationship_value(obj, column) else: value = self._get_to_one_relationship_value(obj, column) return value
Compute datas produced for a given relationship
def long_press(self, locator, duration=1000): driver = self._current_application() element = self._element_find(locator, True, True) action = TouchAction(driver) action.press(element).wait(duration).release().perform()
Long press the element with optional duration
def worker(job): ret = False try: if job.full_url is not None: req = requests.get(job.full_url, stream=True) ret = save_and_check(req, job.local_file, job.expected_checksum) if not ret: return ret ret = create_symlink(job.local_file, job.symlin...
Run a single download job.
def _get_loader_for_url(self, url): parts = url.split('://', 1) if len(parts) < 2: type_ = 'file' else: type_ = parts[0] if '+' in type_: profile_name, scheme = type_.split('+', 1) if len(parts) == 2: url = scheme + '://' + ...
Determine loading method based on uri
def cummin(x): for i in range(1, len(x)): if x[i-1] < x[i]: x[i] = x[i-1] return x
A python implementation of the cummin function in R
def savez_two_column(matrix, row_offset, file_name, append=False): logging.info("Saving obj to file in two column .npz format %s.", file_name) tc = [] for u, items in enumerate(matrix): user = row_offset + u for item in items: tc.append([user, item]) np.savez_compressed(file_name, np.asarray(tc)) ...
Savez_compressed obj to file_name.
def cos_r(self, N=None): if not hasattr(self, 'F') or self.F.shape[1] < self.rank: self.fs_r(N=self.rank) self.dr = norm(self.F, axis=1)**2 return apply_along_axis(lambda _: _/self.dr, 0, self.F[:, :N]**2)
Return the squared cosines for each row.
def signal_catcher(callback): def _catch_exit_signal(sig_num, _frame): print('Received signal {:d} invoking callback...'.format(sig_num)) callback() signal.signal(signal.SIGINT, _catch_exit_signal) signal.signal(signal.SIGQUIT, _catch_exit_signal) signal.signal(signal.SIGTERM, _catch_exi...
Catch signals and invoke the callback method
def on_open(self, ws): def keep_alive(interval): while True: time.sleep(interval) self.ping() start_new_thread(keep_alive, (self.keep_alive_interval, ))
Websocket on_open event handler
def generate_password(mode, length): r = random.SystemRandom() length = length or RANDOM_PASSWORD_DEFAULT_LENGTH password = "".join(r.choice(RANDOM_PASSWORD_ALPHABET) for _ in range(length)) if mode == Mode.ECHO: click.echo(style_password(password)) elif mode == Mode.COPY: try: ...
generate a random password
def remove_argument(self, name): for index, arg in enumerate(self.args[:]): if name == arg.name: del self.args[index] break return self
Remove the argument matching the given name.
def run(self): self._setup_kafka() self._load_plugins() self._setup_stats() self._main_loop()
Set up and run
def dict_pick(dictionary, allowed_keys): return {key: value for key, value in viewitems(dictionary) if key in allowed_keys}
Return a dictionary only with keys found in `allowed_keys`
def UTF8ToUTF16BE(instr, setbom=True): "Converts UTF-8 strings to UTF16-BE." outstr = "".encode() if (setbom): outstr += "\xFE\xFF".encode("latin1") if not isinstance(instr, unicode): instr = instr.decode('UTF-8') outstr += instr.encode('UTF-16BE') if PY3K: outstr = outst...
Converts UTF-8 strings to UTF16-BE.
def user_to_request(handler): @wraps(handler) async def decorator(*args): request = _get_request(args) request[cfg.REQUEST_USER_KEY] = await get_cur_user(request) return await handler(*args) return decorator
Add user to request if user logged in
def add(self, resource, replace=False): uri = resource.uri for r in self: if (uri == r.uri): if (replace): r = resource return else: raise ResourceListDupeError( "Attempt to ad...
Add a single resource, check for dupes.
def add_output_arg(self, out): self.add_arg(out._dax_repr()) self._add_output(out)
Add an output as an argument
def string_to_datetime(self, obj): if isinstance(obj, six.string_types) and len(obj) == 19: try: return datetime.strptime(obj, "%Y-%m-%dT%H:%M:%S") except ValueError: pass if isinstance(obj, six.string_types) and len(obj) > 19: try: ...
Decode a datetime string to a datetime object
def _LoadAuditEvents(handlers, get_report_args, actions=None, token=None, transformers=None): if transformers is None: transformers = {} if data_store.RelationalDBEnabled(): entries = data_store.REL_DB.ReadAPIAuditEntries( ...
Returns AuditEvents for given handlers, actions, and timerange.
def main(output): client = SubscriptionClient(Session().get_credentials()) subs = [sub.serialize(True) for sub in client.subscriptions.list()] results = [] for sub in subs: sub_info = { 'subscription_id': sub['subscriptionId'], 'name': sub['displayName'] } ...
Generate a c7n-org subscriptions config file
def async_refresh(self, *args, **kwargs): try: enqueue_task( dict( klass_str=self.class_path, obj_args=self.get_init_args(), obj_kwargs=self.get_init_kwargs(), call_args=args, call_kwa...
Trigger an asynchronous job to refresh the cache
def _handle_config(self, data): self.room.config.update(data) self.conn.enqueue_data("config", data)
Handle initial config push and config changes
def security_code_date(self): return sa.Column( sa.TIMESTAMP(timezone=False), default=datetime(2000, 1, 1), server_default="2000-01-01 01:01", )
Date of user's security code update
def find_env_paths_in_basedirs(base_dirs): env_path = [] for base_dir in base_dirs: env_path.extend(glob.glob(os.path.join( os.path.expanduser(base_dir), '*', ''))) return env_path
Returns all potential envs in a basedir
def posterior_samples(self, X, size=10, full_cov=False, Y_metadata=None, likelihood=None, **predict_kwargs): return self.posterior_samples_f(X, size, full_cov=full_cov, **predict_kwargs)
Samples the posterior GP at the points X, equivalent to posterior_samples_f due to the absence of a likelihood.
def ttl(self, key, **opts): key, store = self._expand_opts(key, opts) if hasattr(store, 'ttl'): return store.ttl(key) data = store.get(key) if data is None: return None expiry = data[EXPIRY_INDEX] if expiry is not None: return max(0, ex...
Get the time-to-live of a given key; None if not set.
def alert_policy_condition_path(cls, project, alert_policy, condition): return google.api_core.path_template.expand( "projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}", project=project, alert_policy=alert_policy, condition=condition, ...
Return a fully-qualified alert_policy_condition string.
def _recv_nack(self, method_frame): if self._nack_listener: delivery_tag = method_frame.args.read_longlong() multiple, requeue = method_frame.args.read_bits(2) if multiple: while self._last_ack_id < delivery_tag: self._last_ack_id += 1 ...
Receive a nack from the broker.
async def iterStormPodes(self, text, opts=None, user=None): if user is None: user = self.user dorepr = False dopath = False self.core._logStormQuery(text, user) if opts is not None: dorepr = opts.get('repr', False) dopath = opts.get('path', Fal...
Yield packed node tuples for the given storm query text.
def get(self, cid1, cid2, annotator_id): t = (cid1, cid2, annotator_id) for k, v in self.kvl.scan(self.TABLE, (t, t)): return self._label_from_kvlayer(k, v)
Retrieve a relation label from the store.
def map_legacy_frequencies(form, field): if field.data in LEGACY_FREQUENCIES: field.data = LEGACY_FREQUENCIES[field.data]
Map legacy frequencies to new ones
def build_payload(self, payload): for segment in self.segments: segment.pack(payload, commit=self.autocommit)
Build payload of message.
def wrap_all(self, rows: Iterable[Union[Mapping[str, Any], Sequence[Any]]]): return (self.wrap(r) for r in rows)
Return row tuple for each row in rows.
def _fix_json_agents(ag_obj): if isinstance(ag_obj, str): logger.info("Fixing string agent: %s." % ag_obj) ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}} elif isinstance(ag_obj, list): ret = [_fix_json_agents(ag) for ag in ag_obj] elif isinstance(ag_obj, dict) and 'TEXT' in ag_o...
Fix the json representation of an agent.
def layer_norm_vars(filters): scale = tf.get_variable( "layer_norm_scale", [filters], initializer=tf.ones_initializer()) bias = tf.get_variable( "layer_norm_bias", [filters], initializer=tf.zeros_initializer()) return scale, bias
Create Variables for layer norm.
def create_cbz(directory): if not os.path.isdir(directory): print("ERROR: Directory", directory, "not found.") return base = os.path.basename(directory.rstrip(os.path.sep)) zipname = '%s.cbz' % base zipname = os.path.join(directory, zipname) d = os.path.join(directory, 'inorder') ...
Creates or updates a CBZ from files in the given comic directory.
def normalize_std_array(vector): length = 1 n_samples = len(vector) mean = numpy.ndarray((length,), 'float64') std = numpy.ndarray((length,), 'float64') mean.fill(0) std.fill(0) for array in vector: x = array.astype('float64') mean += x std += (x ** 2) mean /= n_samples std /= n_samples ...
Applies a unit mean and variance normalization to an arrayset
def placeholder_plugin_filter(self, request, queryset): if not request: return queryset if GLL.is_active: return queryset.filter(language=GLL.language_code) return queryset
This is only used on models which use placeholders from the django-cms
def close(self): if getattr(self, '_connection', None): logger.debug('Closing sqlite connection.') self._connection.close() self._connection = None
Closes connection to sqlite database.
def _get_voltage_magnitude_var(self, buses, generators): Vm = array([b.v_magnitude for b in buses]) for g in generators: Vm[g.bus._i] = g.v_magnitude Vmin = array([b.v_min for b in buses]) Vmax = array([b.v_max for b in buses]) return Variable("Vm", len(buses), Vm, Vm...
Returns the voltage magnitude variable set.
def container_running(self, id=None, name=None): running = False if id: running = self.inspect_container(id)['State']['Running'] elif name: running = self.inspect_container(name)['State']['Running'] return running
Checks if container is running
def upcaseTokens(s,l,t): return [ tt.upper() for tt in map(_ustr,t) ]
Helper parse action to convert tokens to upper case.
def app_score(self): precisions, pct_pred_pos, taus = self.precision_pct_pred_pos_curve(interval=False) app = 0 total = 0 for k in range(len(precisions)-1): cur_prec = precisions[k] cur_pp = pct_pred_pos[k] cur_tau = taus[k] next_prec = pre...
Computes the area under the app curve.
def apply_patch(document, patch): op = patch.op parent, idx = resolve_path(document, patch.path) if op == "add": return add(parent, idx, patch.value) elif op == "remove": return remove(parent, idx) elif op == "replace": return replace(parent, idx, patch.value, patch.src) elif op == "merge": ...
Apply a Patch object to a document.
def sync(self): output = get_profile(self.profile_id) output['response'].raise_if_error() for payment_profile in output['payment_profiles']: instance, created = CustomerPaymentProfile.objects.get_or_create( customer_profile=self, payment_profile_id=pay...
Overwrite local customer profile data with remote data
def lookup_ips (ips): hosts = set() for ip in ips: try: hosts.add(socket.gethostbyaddr(ip)[0]) except socket.error: hosts.add(ip) return hosts
Return set of host names that resolve to given ips.
def prettyXml(elem): roughString = ET.tostring(elem, "utf-8") reparsed = minidom.parseString(roughString) return reparsed.toprettyxml(indent=" ")
Return a pretty-printed XML string for the ElementTree Element.
def axes(self): return tuple(i for i in range(self.domain.ndim) if self.domain.shape[i] != self.range.shape[i])
Dimensions in which an actual resizing is performed.
def noop(*layers): def begin_update(X, drop=0.0): return X, lambda D, *a, **k: D return begin_update
Transform a sequences of layers into a null operation.
def tcp_reassembly(packet, *, count=NotImplemented): if 'TCP' in packet: ip = packet['IP'] if 'IP' in packet else packet['IPv6'] tcp = packet['TCP'] data = dict( bufid=( ipaddress.ip_address(ip.src), ipaddress.ip_address(ip.dst), tc...
Store data for TCP reassembly.
def save(self, bulk=False, id=None, parent=None, routing=None, force=False): meta = self._meta conn = meta['connection'] id = id or meta.get("id", None) parent = parent or meta.get('parent', None) routing = routing or meta.get('routing', None) qargs = None if rout...
Save the object and returns id
def bucket(things, key): ret = defaultdict(list) for thing in things: ret[key(thing)].append(thing) return ret
Return a map of key -> list of things.
def shuffle_data(X, y=None, sample_weight=None): if len(X) > 1: ind = np.arange(len(X), dtype=np.int) np.random.shuffle(ind) Xt = X[ind] yt = y swt = sample_weight if yt is not None: yt = yt[ind] if swt is not None: swt = swt[ind] ...
Shuffles indices X, y, and sample_weight together
def fetch_all_data(self, limit=50000): query = text( ) try: print("Querying the database, this could take a while") response = self.perform_query(query, limit=limit) master_df = pd.DataFrame(response.fetchall()) print("master_df created successfull...
Fetch data for all entities.
def show_tree(self): self.initialize_view() self.setItemsExpandable(True) self.setSortingEnabled(False) rootkey = self.find_root() if rootkey: self.populate_tree(self, self.find_callees(rootkey)) self.resizeColumnToContents(0) self.setSor...
Populate the tree with profiler data and display it.
def documentation(default=None, api_version=None, api=None, **kwargs): api_version = default or api_version if api: return api.http.documentation(base_url="", api_version=api_version)
returns documentation for the current api
def expand(sequence): expanse = [] for point in sequence: if 'sequence' in point: expanse.extend(expand(point['sequence'])) else: expanse.append(point) return sequence.__class__(expanse)
expands a tree of sequences into a single, flat sequence, recursively.
def _from_dict(cls, _dict): args = {} if 'documents' in _dict: args['documents'] = EnvironmentDocuments._from_dict( _dict.get('documents')) if 'disk_usage' in _dict: args['disk_usage'] = DiskUsage._from_dict(_dict.get('disk_usage')) if 'collections...
Initialize a IndexCapacity object from a json dictionary.
def _check_and_install_python(ret, python, default=False, user=None): ret = _python_installed(ret, python, user=user) if not ret['result']: if __salt__['pyenv.install_python'](python, runas=user): ret['result'] = True ret['changes'][python] = 'Installed' ret['comment'...
Verify that python is installed, install if unavailable
def spots_at(self, x, y): for spot in self.spot.values(): if spot.collide_point(x, y): yield spot
Iterate over spots that collide the given point.
def ednde(self, x, params=None): params = self.params if params is None else params return np.squeeze(self.eval_ednde(x, params, self.scale, self.extra_params))
Evaluate E times differential flux.
def put (self, ch): if isinstance(ch, bytes): ch = self._decode(ch) self.put_abs (self.cur_r, self.cur_c, ch)
This puts a characters at the current cursor position.
def parsebool(el): txt = text(el) up = txt.upper() if up == "OUI": return True if up == "NON": return False return bool(parseint(el))
Parse a ``BeautifulSoup`` element as a bool
def editText(self, y, x, w, record=True, **kwargs): 'Wrap global editText with `preedit` and `postedit` hooks.' v = self.callHook('preedit') if record else None if not v or v[0] is None: with EnableCursor(): v = editText(self.scr, y, x, w, **kwargs) else: ...
Wrap global editText with `preedit` and `postedit` hooks.
def acquisition_function(self,x): f_acqu = self._compute_acq(x) cost_x, _ = self.cost_withGradients(x) return -(f_acqu*self.space.indicator_constraints(x))/cost_x
Takes an acquisition and weights it so the domain and cost are taken into account.
def all_mouse_sprites(self): def all_recursive(sprites): if not sprites: return for sprite in sprites: if sprite.visible: yield sprite for child in all_recursive(sprite.get_mouse_sprites()): y...
Returns flat list of the sprite tree for simplified iteration
def _load_file(self, log_file, message_name_filter_list): if isinstance(log_file, str): self._file_handle = open(log_file, "rb") else: self._file_handle = log_file self._read_file_header() self._last_timestamp = self._start_timestamp self._read_file_defini...
load and parse an ULog file into memory
def cache_return(func): _cache = [] def wrap(): if not _cache: _cache.append(func()) return _cache[0] return wrap
Cache the return value of a function without arguments
def __allocateBits(self): if self._bit_count < 0: raise Exception( "A margin cannot request negative number of bits" ) if self._bit_count == 0: return margins = self._qpart.getMargins() occupiedRanges = [] for margin in margins: bitRange = marg...
Allocates the bit range depending on the required bit count
def assert_page_source_contains(self, expected_value, failure_message='Expected page source to contain: "{}"'): assertion = lambda: expected_value in self.driver_wrapper.page_source() self.webdriver_assert(assertion, unicode(failure_message).format(expected_value))
Asserts that the page source contains the string passed in expected_value
def author_list(self): author_list = [self.submitter] + \ [author for author in self.authors.all().exclude(pk=self.submitter.pk)] return ",\n".join([author.get_full_name() for author in author_list])
The list of authors als text, for admin submission list overview.
def _disable_module(module): try: subprocess.check_call(['a2dismod', module]) except subprocess.CalledProcessError as e: log('Error occurred disabling module %s. ' 'Output is: %s' % (module, e.output), level=ERROR)
Disables the specified module in Apache.
def view_for(self, action='view'): app = current_app._get_current_object() view, attr = self.view_for_endpoints[app][action] return getattr(view(self), attr)
Return the classview viewhandler that handles the specified action
def checklink (form=None, env=os.environ): if form is None: form = {} try: checkform(form, env) except LCFormError as errmsg: log(env, errmsg) yield encode(format_error(errmsg)) return out = ThreadsafeIO() config = get_configuration(form, out) url = strfor...
Validates the CGI form and checks the given links.
def parse_address(address: str) -> str: display_name, parsed_address = email.utils.parseaddr(address) return parsed_address or address
Parse an email address, falling back to the raw string given.