code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def _listen_comments(self): comments_queue = Queue(maxsize=self._n_jobs * 4) threads = [] try: for i in range(self._n_jobs): t = BotQueueWorker(name='CommentThread-t-{}'.format(i), jobs=comments_queue, ...
Start listening to comments, using a separate thread.
def mtf_bitransformer_base(): hparams = mtf_transformer2_base() hparams.max_length = 256 hparams.shared_embedding = True hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6) hparams.add_hparam("decoder_layers", ["self_att", "enc_att", "drd"] * 6) hparams.add_hparam("encoder_num_layers", 6) hparam...
Machine translation base configuration.
def retrieve_by_id(self, id_): items_with_id = [item for item in self if item.id == int(id_)] if len(items_with_id) == 1: return items_with_id[0].retrieve()
Return a JSSObject for the element with ID id_
def _bld_pnab_generic(self, funcname, **kwargs): margs = {'mtype': pnab, 'kwargs': kwargs} setattr(self, funcname, margs)
implement's a generic version of a non-attribute based pandas function
def _get_rate(self, value): if value == 0: return 0 else: return MINIMAL_RATE_HZ * math.exp(value * self._get_factor())
Return the rate in Hz from the short int value
def check_xlim_change(self): if self.xlim_pipe is None: return None xlim = None while self.xlim_pipe[0].poll(): try: xlim = self.xlim_pipe[0].recv() except EOFError: return None if xlim != self.xlim: return x...
check for new X bounds
def partial_update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context()) serializer.is_valid(raise_exception=True) serializer.save() if getattr(instance, '_prefetched_objects_ca...
We do not include the mixin as we want only PATCH and no PUT
def add_filter(self, filter_key, operator, value): filter_key = self._metadata_map.get(filter_key, filter_key) self.filters.append({'filter': filter_key, 'operator': operator, 'value': value})
Adds a filter given a key, operator, and value
def convert_block_dicts_to_string(self, block_1st2nd, block_1st, block_2nd, block_3rd): out = "" if self.codon_positions in ['ALL', '1st-2nd']: for gene_code, seqs in block_1st2nd.items(): out += '>{0}_1st-2nd\n----\n'.format(gene_code) for seq in seqs: ...
Takes into account whether we need to output all codon positions.
def isHiddenName(astr): if astr is not None and len(astr) > 2 and astr.startswith('_') and \ astr.endswith('_'): return True else: return False
Return True if this string name denotes a hidden par or section
def _rmv_pkg(self, package): removes = [] if GetFromInstalled(package).name() and package not in self.skip: ver = GetFromInstalled(package).version() removes.append(package + ver) self._removepkg(package) return removes
Remove one signle package
def diff_texts(a, b, filename): a = a.splitlines() b = b.splitlines() return difflib.unified_diff(a, b, filename, filename, "(original)", "(refactored)", lineterm="")
Return a unified diff of two strings.
def _get_stack(self, orchestration_client, stack_name): try: stack = orchestration_client.stacks.get(stack_name) self.log.info("Stack found, will be doing a stack update") return stack except HTTPNotFound: self.log.info("No stack found, will be doing a sta...
Get the ID for the current deployed overcloud stack if it exists.
def socket_worker(sock, msg_q): _LOGGER.debug("Starting Socket Thread.") while True: try: data, addr = sock.recvfrom(1024) except OSError as err: _LOGGER.error(err) else: _LOGGER.debug("received message: %s from %s", data, addr) msg_q.put(d...
Socket Loop that fills message queue
def inv(self): if self.det == 0: raise ValueError("SquareTensor is non-invertible") return SquareTensor(np.linalg.inv(self))
shorthand for matrix inverse on SquareTensor
def CountClientPlatformReleasesByLabel(self, day_buckets): return self._CountClientStatisticByLabel( day_buckets, lambda client_info: client_info.last_snapshot.Uname())
Computes client-activity stats for OS-release strings in the DB.
def shell_django(session: DjangoSession, backend: ShellBackend): namespace = { 'session': session } namespace.update(backend.get_namespace()) embed(user_ns=namespace, header=backend.header)
This command includes Django DB Session
def OnImport(self, event): wildcards = get_filetypes2wildcards(["csv", "txt"]).values() wildcard = "|".join(wildcards) message = _("Choose file to import.") style = wx.OPEN filepath, filterindex = \ self.interfaces.get_filepath_findex_from_user(wildcard, message, ...
File import event handler
def fixed_step_return(reward, value, length, discount, window): timestep = tf.range(reward.shape[1].value) mask = tf.cast(timestep[None, :] < length[:, None], tf.float32) return_ = tf.zeros_like(reward) for _ in range(window): return_ += reward reward = discount * tf.concat( [reward[:, 1:], tf.z...
N-step discounted return.
def delete_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False): tenant_name = fw_dict.get('tenant_name') ret = self._delete_service_nwk(tenant_id, tenant_name, 'in') if ret: res = fw_const.DCNM_IN_NETWORK_DEL_SUCCESS LOG.info("In Service network deleted for tenant %s"...
Delete the DCNM In Network and store the result in DB.
def _edge_both_nodes(nodes: List[Node]): node_ids = [node.id for node in nodes] return and_( Edge.source_id.in_(node_ids), Edge.target_id.in_(node_ids), )
Get edges where both the source and target are in the list of nodes.
def _exec(self, query, **kwargs): variables = {'entity': self.username, 'project': self.project, 'name': self.name} variables.update(kwargs) return self.client.execute(query, variable_values=variables)
Execute a query against the cloud backend
def load_vi_open_in_editor_bindings(): registry = Registry() navigation_mode = ViNavigationMode() registry.add_binding('v', filter=navigation_mode)( get_by_name('edit-and-execute-command')) return registry
Pressing 'v' in navigation mode will open the buffer in an external editor.
def _from_dict(cls, _dict): args = {} if 'source_url' in _dict: args['source_url'] = _dict.get('source_url') if 'resolved_url' in _dict: args['resolved_url'] = _dict.get('resolved_url') if 'image' in _dict: args['image'] = _dict.get('image') if...
Initialize a ClassifiedImage object from a json dictionary.
def calc_nfalse(d): dtfactor = n.sum([1./i for i in d['dtarr']]) ntrials = d['readints'] * dtfactor * len(d['dmarr']) * d['npixx'] * d['npixy'] qfrac = 1 - (erf(d['sigma_image1']/n.sqrt(2)) + 1)/2. nfalse = int(qfrac*ntrials) return nfalse
Calculate the number of thermal-noise false positives per segment.
def _convert_size(self, size_str): suffix = size_str[-1] if suffix == 'K': multiplier = 1.0 / (1024.0 * 1024.0) elif suffix == 'M': multiplier = 1.0 / 1024.0 elif suffix == 'T': multiplier = 1024.0 else: multiplier = 1 try: ...
Convert units to GB
def delete(stack, region, profile): ini_data = {} environment = {} environment['stack_name'] = stack if region: environment['region'] = region else: environment['region'] = find_myself() if profile: environment['profile'] = profile ini_data['environment'] = environmen...
Delete the given CloudFormation stack.
def diff_bearing(b1, b2): d = abs(b2 - b1) d = 360 - d if d > 180 else d return d
Compute difference between two bearings
def requires_password_auth(fn): def wrapper(self, *args, **kwargs): self.auth_context = HAPI.auth_context_password return fn(self, *args, **kwargs) return wrapper
Decorator for HAPI methods that requires the instance to be authenticated with a password
def copy(self): content = [(k, v) for k, v in self.items()] intidx = [(k, v) for k, v in content if isinstance(k, int)] args = [v for k, v in sorted(intidx)] kwargs = {k: v for k, v in content if not isinstance(k, int) and not self.is_special(k)} ...
Return a copy of this `Fact`.
def sum(self, axis=None, keepdims=False): return self.numpy().sum(axis=axis, keepdims=keepdims)
Return sum along specified axis
def _add_cookies(self, request: Request): self._cookie_jar.add_cookie_header( request, self._get_cookie_referrer_host() )
Add the cookie headers to the Request.
def distinct(iterable, keyfunc=None): seen = set() for item in iterable: key = item if keyfunc is None else keyfunc(item) if key not in seen: seen.add(key) yield item
Yields distinct items from `iterable` in the order that they appear.
def _mpv_coax_proptype(value, proptype=str): if type(value) is bytes: return value; elif type(value) is bool: return b'yes' if value else b'no' elif proptype in (str, int, float): return str(proptype(value)).encode('utf-8') else: raise TypeError('Cannot coax value of type...
Intelligently coax the given python value into something that can be understood as a proptype property.
def cli(env, identifier, enable, permission, from_user): mgr = SoftLayer.UserManager(env.client) user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username') result = False if from_user: from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username') result = mgr.permi...
Enable or Disable specific permissions.
def data(self): import warnings warnings.warn( '`data` attribute is deprecated and will be removed in a future release, ' 'use %s as an iterable instead' % (PaginatedResponse,), category=DeprecationWarning, stacklevel=2 ) return list(self)
Deprecated. Returns the data as a `list`
async def postback_send(msg: BaseMessage, platform: Platform) -> Response: await platform.inject_message(msg) return json_response({ 'status': 'ok', })
Injects the POST body into the FSM as a Postback message.
def warn(msg, *args): if not args: sys.stderr.write('WARNING: ' + msg) else: sys.stderr.write('WARNING: ' + msg % args)
Print a warning on stderr
def google(self, qs): csvf = writer(sys.stdout) csvf.writerow(['Name', 'Email']) for ent in qs: csvf.writerow([full_name(**ent), ent['email']])
CSV format suitable for importing into google GMail
def input_fn(data_file, num_epochs, shuffle, batch_size): assert tf.gfile.Exists(data_file), ( '%s not found. Please make sure you have run census_dataset.py and ' 'set the --data_dir argument to the correct path.' % data_file) def parse_csv(value): tf.logging.info('Parsing {}'.format(data_file)) ...
Generate an input function for the Estimator.
def fullpath(self, **kwargs): kwargs_copy = self.base_dict.copy() kwargs_copy.update(**kwargs) self._replace_none(kwargs_copy) return NameFactory.fullpath_format.format(**kwargs_copy)
Return a full path name for a given file
def lattice(self, lattice): self._lattice = lattice self._coords = self._lattice.get_cartesian_coords(self._frac_coords)
Sets Lattice associated with PeriodicSite
def stop_class(self, class_): "Stop all services of a given class" matches = filter(lambda svc: isinstance(svc, class_), self) map(self.stop, matches)
Stop all services of a given class
def _IsMap(message, field): value = message.get_assigned_value(field.name) if not isinstance(value, messages.Message): return False try: additional_properties = value.field_by_name('additionalProperties') except KeyError: return False else: return additional_propertie...
Returns whether the "field" is actually a map-type.
def rotate(args, credentials): current_access_key_id = credentials.get( args.identity_profile, 'aws_access_key_id') session, session3, err = make_session(args.target_profile) if err: return err iam = session3.resource('iam') current_access_key = next((key for key ...
rotate the identity profile's AWS access key pair.
def add_screenshot(self, screenshot): if screenshot in self.screenshots: return self.screenshots.append(screenshot)
Add a screenshot object if it does not already exist
def handle_output(results, output_type, action): if output_type == 'QUIET': return if not output_type == 'JSON': if action == 'list': table = generate_list_table_result( logger, results, output_type == 'TABLE-NO-HEADER') else: table = generate_tabl...
Print the relevant output for given output_type
def memoize(fn): memo = {} @wraps(fn) def wrapper(*args, **kwargs): if not memoize.disabled: key = pickle.dumps((args, kwargs)) if key not in memo: memo[key] = fn(*args, **kwargs) value = memo[key] else: value = fn(*args, **kwar...
Caches previous calls to the function.
def _setup_tf(self, stream=False): if self.tf_version < (0, 9, 0): self._set_remote(stream=stream) return self._run_tf('init', stream=stream) logger.info('Terraform initialized')
Setup terraform; either 'remote config' or 'init' depending on version.
def on_train_begin(self, epoch:int, **kwargs:Any)->None: "Initialize the schedulers for training." res = {'epoch':self.start_epoch} if self.start_epoch is not None else None self.start_epoch = ifnone(self.start_epoch, epoch) self.scheds = [p.scheds for p in self.phases] self.opt ...
Initialize the schedulers for training.
def download_to(self, folder): urlretrieve(self.maven_url, os.path.join(folder, self.filename))
Download into a folder
def unpack_from(self, buff, offset=0): return self._create(super(NamedStruct, self).unpack_from(buff, offset))
Read bytes from a buffer and return as a namedtuple.
def sendline(sock, msg, confidential=False): log.debug('<- %r', ('<snip>' if confidential else msg)) sock.sendall(msg + b'\n')
Send a binary message, followed by EOL.
def previous(self): msg = cr.Message() msg.type = cr.PREVIOUS self.send_message(msg)
Sends a "previous" command to the player.
def validate_uncle(cls, block: BaseBlock, uncle: BaseBlock, uncle_parent: BaseBlock) -> None: if uncle.block_number >= block.number: raise ValidationError( "Uncle number ({0}) is higher than block number ({1})".format( uncle.block_number, block.number)) if...
Validate the given uncle in the context of the given block.
def add(self, resource): if isinstance(resource, Resource): if isinstance(resource, Secret) and \ resource.mount != 'cubbyhole': ensure_backend(resource, SecretBackend, self._mounts, ...
Add a resource to the context
def forward_char(event): " Move forward a character. " buff = event.current_buffer buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg)
Move forward a character.
def finished(cls, jobid): output = subprocess.check_output( [SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)] ) end = output.strip().decode() return end not in {'Unknown', ''}
Check whether a SLURM job is finished or not
def generate(basename, xml_list): generate_shared(basename, xml_list) for xml in xml_list: generate_message_definitions(basename, xml)
generate complete MAVLink Objective-C implemenation
def repositories(self): if self.repo == "sbo": self.sbo_case_insensitive() self.find_pkg = sbo_search_pkg(self.name) if self.find_pkg: self.dependencies_list = Requires(self.flag).sbo(self.name) else: PACKAGES_TXT = Utils().read_file( ...
Get dependencies by repositories
def veq_samples(R_dist,Prot_dist,N=1e4,alpha=0.23,l0=20,sigl=20): ls = stats.norm(l0,sigl).rvs(N) Prots = Prot_dist.rvs(N) Prots *= diff_Prot_factor(ls,alpha) return R_dist.rvs(N)*2*np.pi*RSUN/(Prots*DAY)/1e5
Source for diff rot
def build( documentPath, outputUFOFormatVersion=3, roundGeometry=True, verbose=True, logPath=None, progressFunc=None, processRules=True, logger=None, useVarlib=False, ): import os, glob if os.path.isdir(documentPath): todo =...
Simple builder for UFO designspaces.
def _check_email_changed(cls, username, email): ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True) return ret['email'] != email
Compares email to one set on SeAT
def show_settings(self): self.notes.config.put_values() self.overview.config.put_values() self.settings.config.put_values() self.spectrum.config.put_values() self.traces.config.put_values() self.video.config.put_values() self.settings.show()
Open the Setting windows, after updating the values in GUI.
def max_abs(self): if self.__len__() == 0: return ArgumentError('empty set has no maximum absolute value.') return numpy.max(numpy.abs([self.max(), self.min()]))
Returns maximum absolute value.
def _linux_id(self): linux_id = None hardware = self.detector.get_cpuinfo_field("Hardware") if hardware is None: vendor_id = self.detector.get_cpuinfo_field("vendor_id") if vendor_id in ("GenuineIntel", "AuthenticAMD"): linux_id = GENERIC_X86 c...
Attempt to detect the CPU on a computer running the Linux kernel.
def push_entity(self, entity): if entity.id: print('Updating {} entity'.format(entity.name)) self.update(entity) else: print('Registering {} entity'.format(entity.name)) entity = self.register(entity) return entity
Registers or updates an entity and returns the entity_json with an ID
def keys_to_values(self, keys): "Return the items in the keystore with keys in `keys`." return dict((k, v) for k, v in self.data.items() if k in keys)
Return the items in the keystore with keys in `keys`.
def from_dict(cls, d): o = super(DistributionList, cls).from_dict(d) o.members = [] if 'dlm' in d: o.members = [utils.get_content(member) for member in utils.as_list(d["dlm"])] return o
Override default, adding the capture of members.
def groupQuery( self ): items = self.uiQueryTREE.selectedItems() if ( not len(items) > 2 ): return if ( isinstance(items[-1], XJoinItem) ): items = items[:-1] tree = self.uiQueryTREE parent = items[0].parent() if ( not parent ): ...
Groups the selected items together into a sub query
def _timestamps_eq(a, b): assert isinstance(a, datetime) if not isinstance(b, datetime): return False if (a.tzinfo is None) ^ (b.tzinfo is None): return False if a.utcoffset() != b.utcoffset(): return False for a, b in ((a, b), (b, a)): if isinstance(a, Timestamp): ...
Compares two timestamp operands for equivalence under the Ion data model.
def average_colors(c1, c2): r = int((c1[0] + c2[0])/2) g = int((c1[1] + c2[1])/2) b = int((c1[2] + c2[2])/2) return (r, g, b)
Average the values of two colors together
def wait_for_crm_operation(operation): logger.info("wait_for_crm_operation: " "Waiting for operation {} to finish...".format(operation)) for _ in range(MAX_POLLS): result = crm.operations().get(name=operation["name"]).execute() if "error" in result: raise Exception(re...
Poll for cloud resource manager operation until finished.
def _prune_all_if_small(self, small_size, a_or_u): "Return True and delete children if small enough." if self._nodes is None: return True total_size = (self.app_size() if a_or_u else self.use_size()) if total_size < small_size: if a_or_u: self._set...
Return True and delete children if small enough.
def listdir(self, folder_id='0', offset=None, limit=None, fields=None): 'Get Box object, representing list of objects in a folder.' if fields is not None\ and not isinstance(fields, types.StringTypes): fields = ','.join(fields) return self( join('folders', folder_id, 'items'), dict(offset=offset, limit=l...
Get Box object, representing list of objects in a folder.
def isconsistent(self): for dt1, dt0 in laggeddates(self): if dt1 <= dt0: return False return True
Check if the timeseries is consistent
def activities(self, limit=1, event=None): activities = self._activities or [] if event: activities = list( filter( lambda activity: activity[CONST.EVENT] == event, activities)) return activities[:limit]
Return device activity information.
def main(): WIDTH, HEIGHT = 120, 60 TITLE = None with tcod.console_init_root(WIDTH, HEIGHT, TITLE, order="F", renderer=tcod.RENDERER_SDL) as console: tcod.sys_set_fps(24) while True: tcod.console_flush() for event in tcod.event.wait(): ...
Example program for tcod.event
def make_string(seq): string = '' for c in seq: try: if 32 <= c and c < 256: string += chr(c) except TypeError: pass if not string: return str(seq) return string
Don't throw an exception when given an out of range character.
def group(self): yield self.current for num, item in enumerate(self.iterator, 1): self.current = item if num == self.limit: break yield item else: self.on_going = False
Yield a group from the iterable
def build_configuration_parameters(app): env = Environment(loader=FileSystemLoader("{0}/_data_templates".format(BASEPATH))) template_file = env.get_template("configuration-parameters.j2") data = {} data["schema"] = Config.schema() rendered_template = template_file.render(**data) output_dir = "{0...
Create documentation for configuration parameters.
def unused_port(hostname): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((hostname, 0)) return s.getsockname()[1]
Return a port that is unused on the current host.
def brew(clean=False): try: cmd('which brew') except: return print('-[brew]----------') cmd('brew update') p = cmd('brew outdated') if not p: return pkgs = getPackages(p) for p in pkgs: cmd('brew upgrade {}'.format(p), run=global_run) if clean: print(' > brew prune old sym links and cleanup') cmd('brew...
Handle homebrew on macOS
def edit(self, request, id): try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'error': 'The %s could not be found.'...
Render a form to edit an object.
def sender(self, func, routing=None, routing_re=None): if routing and not isinstance(routing, list): routing = [routing] if routing_re: if not isinstance(routing_re, list): routing_re = [routing_re] routing_re[:] = [re.compile(r) for r in routing_re] ...
Registers a sender function
def finalize(self, initial=True): if getattr(self, '_finalized', False): return if ( self.proxy is None or not hasattr(self.proxy, 'name') ): Clock.schedule_once(self.finalize, 0) return if initial: self.name...
Call this after you've created all the PawnSpot you need and are ready to add them to the board.
def validate(self): try: response = self.client.get_access_key_last_used( AccessKeyId=self.access_key_id ) username = response['UserName'] access_keys = self.client.list_access_keys( UserName=username ) for k...
Returns whether this plugin does what it claims to have done
def __taint_move(self, instr): op0_taint = self.get_operand_taint(instr.operands[0]) self.set_operand_taint(instr.operands[2], op0_taint)
Taint registers move instruction.
def generate_catalogue(args, parser): catalogue = tacl.Catalogue() catalogue.generate(args.corpus, args.label) catalogue.save(args.catalogue)
Generates and saves a catalogue file.
def _CheckLogFileSize(cursor): innodb_log_file_size = int(_ReadVariable("innodb_log_file_size", cursor)) required_size = 10 * mysql_blobs.BLOB_CHUNK_SIZE if innodb_log_file_size < required_size: max_blob_size = innodb_log_file_size / 10 max_blob_size_mib = max_blob_size / 2**20 logging.warning( ...
Warns if MySQL log file size is not large enough for blob insertions.
def execute(self, request): handle = None if request: request[0] = command = to_string(request[0]).lower() info = COMMANDS_INFO.get(command) if info: handle = getattr(self.store, info.method_name) if self.channels or self.patterns: ...
Execute a new ``request``.
def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray: x0 = np.linspace(0, 3.14, Np) return np.tanh(x0)*gridmax+gridmin
typically call via setupz instead
def docs(root_url, path): root_url = root_url.rstrip('/') path = path.lstrip('/') if root_url == OLD_ROOT_URL: return 'https://docs.taskcluster.net/{}'.format(path) else: return '{}/docs/{}'.format(root_url, path)
Generate URL for path in the Taskcluster docs.
def to_cartesian(r, theta, theta_units="radians"): assert theta_units in ['radians', 'degrees'],\ "kwarg theta_units must specified in radians or degrees" if theta_units == "degrees": theta = to_radians(theta) theta = to_proper_radians(theta) x = r * cos(theta) y = r * sin(theta) ...
Converts polar r, theta to cartesian x, y.
def asdict(self): d = dict(self._odict) for k,v in d.items(): if isinstance(v, Struct): d[k] = v.asdict() return d
Return a recursive dict representation of self
def combine_dictionaries(a, b): c = {} for key in list(b.keys()): c[key]=b[key] for key in list(a.keys()): c[key]=a[key] return c
returns the combined dictionary. a's values preferentially chosen
def _merge_colormaps(kwargs): from trollimage.colormap import Colormap full_cmap = None palette = kwargs['palettes'] if isinstance(palette, Colormap): full_cmap = palette else: for itm in palette: cmap = create_colormap(itm) cmap.set_range(itm["min_value"], it...
Merge colormaps listed in kwargs.
def _translate(self, x, y): return self.parent._translate((x + self.x), (y + self.y))
Convertion x and y to their position on the root Console
def print_update(self): print("\r\n") now = datetime.datetime.now() print("Update info: (from: %s)" % now.strftime("%c")) current_total_size = self.total_stined_bytes + self.total_new_bytes if self.total_errored_items: print(" * WARNING: %i omitted files!" % self.tota...
print some status information in between.
def _clauses(lexer, varname, nvars): tok = next(lexer) toktype = type(tok) if toktype is OP_not or toktype is IntegerToken: lexer.unpop_token(tok) first = _clause(lexer, varname, nvars) rest = _clauses(lexer, varname, nvars) return (first, ) + rest else: lexer.unp...
Return a tuple of DIMACS CNF clauses.