code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def add_if_changed(self, resource): if (resource.change is not None): self.resources.append(resource) else: raise ChangeTypeError(resource.change)
Add resource if change is not None else ChangeTypeError.
def _set_publication_info_field(self, field_name, value): self._ensure_reference_field('publication_info', {}) self.obj['reference']['publication_info'][field_name] = value
Put a value in the publication info of the reference.
def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation): end_time = datetime.datetime.now() duration = end_time - start_time duration_sec = float(duration.seconds * 1000) duration_ms = float(duration.microseconds / 1000) duration = duration_sec ...
Print ping exit statistics
def target_to_hostname(target): if len(target) == 0 or len(target) > 255: return None if not re.match(r'^[\w.-]+$', target): return None return [target]
Attempt to return a single hostname list from a target string.
def ip_in_subnet(ip, subnet): ipaddr = int(''.join(['%02x' % int(x) for x in ip.split('.')]), 16) netstr, bits = subnet.split('/') netaddr = int(''.join(['%02x' % int(x) for x in netstr.split('.')]), 16) mask = (0xffffffff << (32 - int(bits))) & 0xffffffff return (ipaddr & mask) == (netaddr & mask)
Does IP exists in a given subnet utility. Returns a boolean
def rm_blanks(self): _blanks = [k for k in self._dict.keys() if not self._dict[k]] for key in _blanks: del self._dict[key]
Get rid of parameters that has no value.
def check_origin(self, origin): mod_opts = self.application.mod_opts if mod_opts.get('cors_origin'): return bool(_check_cors_origin(origin, mod_opts['cors_origin'])) else: return super(AllEventsHandler, self).check_origin(origin)
If cors is enabled, check that the origin is allowed
def save_slope(self, rootpath, raw=False, as_int=False): self.save_array(self.mag, None, 'mag', rootpath, raw, as_int=as_int)
Saves the magnitude of the slope to a file
def as_serializable(self): other = MeanStdFilter(self.shape) other.sync(self) return other
Returns non-concurrent version of current class
def getServices(self): try: conn = self.dbi.connection() result = self.serviceslist.execute(conn) return result except Exception as ex: msg = (("%s DBSServicesRegistry/getServices." + " %s\n. Exception trace: \n %s") % ...
Simple method that returs list of all know DBS instances, instances known to this registry
def _fetch(self, request): client = self.client call = Call(__id__=client.newCall(request.request)) call.enqueue(request.handler) request.call = call
Fetch using the OkHttpClient
def _reroot(self): rerooter = Rerooter() self.tree = rerooter.reroot_by_tree(self.reference_tree, self.tree)
Run the re-rooting algorithm in the Rerooter class.
def DiamReq(cmd, **fields): upfields, name = getCmdParams(cmd, True, **fields) p = DiamG(**upfields) p.name = name return p
Craft Diameter request commands
def end_prov_graph(self): endTime = Literal(datetime.now()) self.prov_g.add((self.entity_d, self.prov.generatedAtTime, endTime)) self.prov_g.add((self.activity, self.prov.endedAtTime, endTime))
Finalize prov recording with end time
def _expect_vars(vs=None): if vs is None: return list() elif isinstance(vs, Variable): return [vs] else: checked = list() for v in vs: if isinstance(v, Variable): checked.append(v) else: ...
Verify the input type and return a list of Variables.
def end_script(self): if self.remote_bridge.status not in (BRIDGE_STATUS.RECEIVED, BRIDGE_STATUS.WAITING): return [1] self.remote_bridge.status = BRIDGE_STATUS.RECEIVED return [0]
Indicate that we have finished receiving a script.
def legal_date(year, month, day): try: assert year >= 1 assert 0 < month <= 14 assert 0 < day <= 28 if month == 14: if isleap(year + YEAR_EPOCH - 1): assert day <= 2 else: assert day == 1 except AssertionError: raise...
Checks if a given date is a legal positivist date
def accounts(): import yaml for path in account_files: try: c_dir = os.path.dirname(path) if not os.path.exists(c_dir): os.makedirs(c_dir) with open(path, 'rb') as f: return yaml.load(f)['accounts'] except (OSError, IOError) as ...
Load the accounts YAML file and return a dict
def patchFile(filename, replacements): patched = Utility.readFile(filename) for key in replacements: patched = patched.replace(key, replacements[key]) Utility.writeFile(filename, patched)
Applies the supplied list of replacements to a file
def _getMyFirstDatetimeTo(self): myFirstDt = self._getMyFirstDatetimeFrom() if myFirstDt is not None: daysDelta = dt.timedelta(days=self.num_days - 1) return getAwareDatetime(myFirstDt.date() + daysDelta, self.time_to, ...
The datetime this event first finished, or None if it never did.
def __get_value(self, field_name): value = request.values.get(field_name) if value is None: if self.json_form_data is None: value = None elif field_name in self.json_form_data: value = self.json_form_data[field_name] return value
Get request Json value by field name
def Join(self): for _ in range(self.JOIN_TIMEOUT_DECISECONDS): if self._queue.empty() and not self.busy_threads: return time.sleep(0.1) raise ValueError("Timeout during Join() for threadpool %s." % self.name)
Waits until all outstanding tasks are completed.
async def handle_client_ping(self, client_addr, _: Ping): await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
Handle an Ping message. Pong the client
def clear(self): "Removes all entries from the config map" self._pb.IntMap.clear() self._pb.StringMap.clear() self._pb.FloatMap.clear() self._pb.BoolMap.clear()
Removes all entries from the config map
def update(ctx, no_restart, no_rebuild): instance = ctx.obj['instance'] log('Pulling github updates') run_process('.', ['git', 'pull', 'origin', 'master']) run_process('./frontend', ['git', 'pull', 'origin', 'master']) if not no_rebuild: log('Rebuilding frontend') install_frontend(in...
Update a HFOS node
def endpoint(request): s = getServer(request) query = util.normalDict(request.GET or request.POST) try: openid_request = s.decodeRequest(query) except ProtocolError, why: return direct_to_template( request, 'server/endpoint.html', {'error': str(why)}) ...
Respond to low-level OpenID protocol messages.
def update_user_label(self): self._user_label = _uniqueid_to_uniquetwig(self._bundle, self.unique_label) self._set_curly_label()
finds this parameter and gets the least_unique_twig from the bundle
def combine_nt_lists(lists, flds, dflt_null=""): combined_nt_list = [] lens = [len(lst) for lst in lists] assert len(set(lens)) == 1, \ "LIST LENGTHS MUST BE EQUAL: {Ls}".format(Ls=" ".join(str(l) for l in lens)) ntobj = cx.namedtuple("Nt", " ".join(flds)) for lst0_lstn in zip(*lists): ...
Return a new list of namedtuples by zipping "lists" of namedtuples or objects.
def health(): up_time = time.time() - START_TIME response = dict(service=__service_id__, uptime='{:.2f}s'.format(up_time)) return response, HTTPStatus.OK
Check the health of this service.
def check_engine(handle): if handle == 'help': dump_engines() sys.exit(0) if handle not in engines.engines: print('Engine "%s" is not available.' % (handle,), file=sys.stderr) sys.exit(1)
Check availability of requested template engine.
def list_users(self): crypt = self._decrypt_file() self.logger.info(crypt.stderr) raw_userlist = crypt.stderr.split('\n') userlist = list() for index, line in enumerate(raw_userlist): if 'gpg: encrypted' in line: m = re.search('ID (\w+)', line) ...
Get user list from the encrypted passdb file
def _parse_table(self): reset = self._head self._head += 2 try: self._push(contexts.TABLE_OPEN) padding = self._handle_table_style("\n") except BadRoute: self._head = reset self._emit_text("{") return style = self._pop()...
Parse a wikicode table by starting with the first line.
def calibration_cache_path(self): if self.__ifo and self.__start > 0: cal_path = self.job().get_config('calibration','path') if ( self.__LHO2k.match(self.__ifo) and (self.__start >= 729273613) and (self.__start <= 734367613) ): if self.__start < int( self.job().get_co...
Determine the path to the correct calibration cache file to use.
def download(self, filename, format='sdf', overwrite=False, resolvers=None, **kwargs): download(self.input, filename, format, overwrite, resolvers, **kwargs)
Download the resolved structure as a file
def deb64_app(parser, cmd, args): parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?') args = parser.parse_args(args) return deb64(pwnypack.main.string_value_or_stdin(args.value))
base64 decode a value.
def list_files(start_path): s = u'\n' for root, dirs, files in os.walk(start_path): level = root.replace(start_path, '').count(os.sep) indent = ' ' * 4 * level s += u'{}{}/\n'.format(indent, os.path.basename(root)) sub_indent = ' ' * 4 * (level + 1) for f in files: ...
tree unix command replacement.
def needs_confirmation(self): if EMAIL_CONFIRMATION: self.is_active = False self.save() return True else: return False
set is_active to False if needs email confirmation
def coord_wrap(self, *args): yield from self.cell.coord.start(self) yield from self.coro(*args) yield from self.cell.coord.finish(self)
Wrap the coroutine with coordination throttles.
def load_notebook(self, name): with open(self.get_path('%s.ipynb'%name)) as f: nb = nbformat.read(f, as_version=4) return nb,f
Loads a notebook file into memory.
def node_query(self, node): if isinstance(node, ast.Call): assert node.args arg = node.args[0] if not isinstance(arg, ast.Str): return else: raise TypeError(type(node)) return arg.s
Return the query for the gql call node
def duplicate(self, template_fact, **modifiers): newfact = template_fact.copy() newfact.update(dict(self._get_real_modifiers(**modifiers))) return self.declare(newfact)
Create a new fact from an existing one.
def merge(self, other): for this, other in zip(self.stats, other.stats): this.merge(other)
Merge all children stats.
def read_byte(self, address): LOGGER.debug("Reading byte from device %s!", hex(address)) return self.driver.read_byte(address)
Reads unadressed byte from a device.
def refs_equal(olditem, newitem): oldrefs = olditem.references newrefs = newitem.references ref_equal = lambda oldref, newref: True if (len(oldref) == len(newref)) and all( x in oldref for x in newref) else False if len(oldrefs) == len(newrefs) and all( any(re...
tests for exactly identical references
def _format_lon(self, lon): if self.ppd in [4, 16, 64, 128]: return None else: return map(lambda x: "{0:0>3}".format(int(x)), self._map_center('long', lon))
Returned a formated longitude format for the file
def wheel_dist_name(self): components = (safer_name(self.distribution.get_name()), safer_version(self.distribution.get_version())) if self.build_number: components += (self.build_number,) return '-'.join(components)
Return distribution full name with - replaced with _
def _render_rate_limit_page(self, exception=None): auth = request.args.get('auth') is_auth = auth == '1' if auth else bool(self.auth) return render_template('limit.html', is_authenticated=is_auth), 403
Renders the rate limit page.
def namedb_get_all_namespace_ids( cur ): query = "SELECT namespace_id FROM namespaces WHERE op = ?;" args = (NAMESPACE_READY,) namespace_rows = namedb_query_execute( cur, query, args ) ret = [] for namespace_row in namespace_rows: ret.append( namespace_row['namespace_id'] ) return ret
Get a list of all READY namespace IDs.
def evaluate_object(obj, cls=None, cache=False, **kwargs): old_obj = obj if isinstance(obj, Element): if cache: obj = obj.evaluate_cached(**kwargs) else: obj = obj.evaluate(cache=cache, **kwargs) if cls is not None and type(obj) != cls: ...
Evaluates elements, and coerces objects to a class if needed
def filterMapAttrs(records=getIndex(), **tags): if len(tags) == 0: return records ret = [] for record in records: if matchRecordAttrs(record, tags): ret.append(record) return ret
matches available maps if their attributes match as specified
def artist(netease, name, id): if name: netease.download_artist_by_search(name) if id: netease.download_artist_by_id(id, 'artist'+str(id))
Download a artist's hot songs by name or id.
def _dataflash_dir(self, mpstate): if mpstate.settings.state_basedir is None: ret = 'dataflash' else: ret = os.path.join(mpstate.settings.state_basedir,'dataflash') try: os.makedirs(ret) except OSError as e: if e.errno != errno.EEXIST: ...
returns directory path to store DF logs in. May be relative
def groups(self): return Groups(url="%s/groups" % self.root, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port, initalize=False)
returns the group object
def standard_program_header(self, title, length, line=32768): self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)
Generates a standard header block of PROGRAM type
def vectorize(self, docs): doc_core_sems, all_concepts = self._extract_core_semantics(docs) shape = (len(docs), len(all_concepts)) vecs = np.zeros(shape) for i, core_sems in enumerate(doc_core_sems): for con, weight in core_sems: j = all_concepts.index(con) ...
Vectorizes a list of documents using their DCS representations.
def data_slice(self, slice_ind): if self.height is None: return self.data[slice_ind] return self.data[slice_ind, ...]
Returns a slice of datapoints
def classifyplot_from_plotfiles(plot_files, out_csv, outtype="png", title=None, size=None): dfs = [pd.read_csv(x) for x in plot_files] samples = [] for df in dfs: for sample in df["sample"].unique(): if sample not in samples: samples.append(sample) df = pd.concat(dfs)...
Create a plot from individual summary csv files with classification metrics.
def list_npm_modules(collector, no_print=False): default = ReactServer().default_npm_deps() for _, module in sorted(collector.configuration["__active_modules__"].items()): default.update(module.npm_deps()) if not no_print: print(json.dumps(default, indent=4, sort_keys=True)) return defau...
List the npm modules that get installed in a docker image for the react server
def path(self): (x, y) = self.tile return os.path.join('%u' % self.zoom, '%u' % y, '%u.img' % x)
return relative path of tile image
def build_url_base(host, port, is_https): base = "http" if is_https: base += 's' base += "://" base += host if port: base += ":" base += str(port) return base
Make base of url based on config
def save_model(self, request, obj, form, change): if 'config.menu_structure' in form.changed_data: from menus.menu_pool import menu_pool menu_pool.clear(all=True) return super(BlogConfigAdmin, self).save_model(request, obj, form, change)
Clear menu cache when changing menu structure
def register_trading_control(self, control): if self.initialized: raise RegisterTradingControlPostInit() self.trading_controls.append(control)
Register a new TradingControl to be checked prior to order calls.
def glob_by_extensions(directory, extensions): directorycheck(directory) files = [] xt = files.extend for ex in extensions: xt(glob.glob('{0}/*.{1}'.format(directory, ex))) return files
Returns files matched by all extensions in the extensions list
def fetch_logins(roles, repo): users = set() if 'stargazer' in roles: printmp('Fetching stargazers') users |= set(repo.stargazers()) if 'collaborator' in roles: printmp('Fetching collaborators') users |= set(repo.collaborators()) if 'issue' in roles: printmp('Fetc...
Fetch logins for users with given roles.
def dt_to_ts(value): if not isinstance(value, datetime): return value return calendar.timegm(value.utctimetuple()) + value.microsecond / 1000000.0
If value is a datetime, convert to timestamp
def tls_session_update(self, msg_str): super(SSLv2ServerHello, self).tls_session_update(msg_str) s = self.tls_session client_cs = s.sslv2_common_cs css = [cs for cs in client_cs if cs in self.ciphers] s.sslv2_common_cs = css s.sslv2_connection_id = self.connection_id ...
XXX Something should be done about the session ID here.
def columns_dataset(self): cache = self.cache cache_key = 'columns_dataset' if cache_key not in cache: columns_dataset = super(CachedModelVectorBuilder, self ).columns_dataset cache[cache_key] = columns_dataset self.cache = ...
Implement high level cache system for columns and dataset.
def sign_in(self, email, password): self.email = email self.login_password = password if self.is_element_present(*self._next_button_locator): self.wait.until(expected.visibility_of_element_located( self._next_button_locator)) self.click_next() self...
Signs in using the specified email address and password.
def apply_saved_layout(self): num_widgets = self.config.get(self.config_key + "/num_widgets", int) if num_widgets: sizes = [] for i in range(num_widgets): key = "%s/size_%d" % (self.config_key, i) size = self.config.get(key, int) si...
Call this after adding your child widgets.
def _get_port_profile_id(self, request): port_profile_id = request.path.split("/")[-1].strip() if uuidutils.is_uuid_like(port_profile_id): LOG.debug("The instance id was found in request path.") return port_profile_id LOG.debug("Failed to get the instance id from the requ...
Get the port profile ID from the request path.
def execute(self, sql, params=None): with self.engine.begin() as conn: result = conn.execute(sql, params) return result
Just a pointer to engine.execute
def _sort(self): self._log.debug('Sorting responses by priority') self._responses = OrderedDict(sorted(list(self._responses.items()), reverse=True)) self.sorted = True
Sort the response dictionaries priority levels for ordered iteration
def relu(inplace:bool=False, leaky:float=None): "Return a relu activation, maybe `leaky` and `inplace`." return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky is not None else nn.ReLU(inplace=inplace)
Return a relu activation, maybe `leaky` and `inplace`.
def configure_discover(self, ns, definition): @self.add_route(ns.singleton_path, Operation.Discover, ns) def discover(): swagger = build_swagger(self.graph, ns, self.find_matching_endpoints(ns)) g.hide_body = True return make_response(swagger)
Register a swagger endpoint for a set of operations.
def rescaleX(self): self.ratio = self.figure.get_size_inches()[0]/float(self.figure.get_size_inches()[1]) self.axes.set_xlim(-self.ratio,self.ratio) self.axes.set_ylim(-1,1)
Rescales the horizontal axes to make the lengthscales equal.
def yaw(self): x, y, z, w = self.x, self.y, self.z, self.w return math.asin(2*x*y + 2*z*w)
Calculates the Yaw of the Quaternion.
def OnGetItemText(self, item, col): try: column = self.columns[col] value = column.get(self.sorted[item]) except IndexError, err: return None else: if value is None: return u'' if column.percentPossible and self.percenta...
Retrieve text for the item and column respectively
def col(self, col_name_or_num): if isinstance(col_name_or_num, basestring): return self[col_name_or_num] elif isinstance(col_name_or_num, (int, long)): if col_name_or_num > len(self.fields): raise IndexError("Invalid column index `%s` for DataTable" % ...
Returns the col at index `colnum` or name `colnum`.
def _format_report_line(self, test, time_taken, color, status, percent): return "[{0}] {3:04.2f}% {1}: {2}".format( status, test, self._colored_time(time_taken, color), percent )
Format a single report line.
def migrate_app(sender, *args, **kwargs): from .registration import registry if 'app_config' not in kwargs: return app_config = kwargs['app_config'] app_name = app_config.label fields = [fld for fld in list(registry._field_registry.keys()) if fld.startswith(app_name)] sid = transaction.s...
Migrate all models of this app registered
def validate_bool_kwarg(value, arg_name): if not (is_bool(value) or value is None): raise ValueError('For argument "{arg}" expected type bool, received ' 'type {typ}.'.format(arg=arg_name, typ=type(value).__name__)) return value
Ensures that argument passed in arg_name is of type bool.
def parse_string_expr(self, string_expr_node): string_expr_node_value = string_expr_node['value'] string_expr_str = string_expr_node_value[1:-1] if string_expr_node_value[0] == "'": string_expr_str = string_expr_str.replace("''", "'") else: string_expr_str = strin...
Parse a string node content.
def text(files): sentences = convert_timestamps(files) out = [] for s in sentences: out.append(' '.join([w[0] for w in s['words']])) return '\n'.join(out)
Returns the whole transcribed text
def _parseElfHeader(self, data): ehdr = self.__classes.EHDR.from_buffer(data) return EhdrData(header=ehdr)
Returns the elf header
def encode_example(self, video_or_path_or_fobj): if isinstance(video_or_path_or_fobj, six.string_types): if not os.path.isfile(video_or_path_or_fobj): _, video_temp_path = tempfile.mkstemp() try: tf.gfile.Copy(video_or_path_or_fobj, video_temp_path, overwrite=True) encoded_...
Converts the given image into a dict convertible to tf example.
def shorten_go_name_ptbl1(self, name): if self._keep_this(name): return name name = name.replace("negative", "neg.") name = name.replace("positive", "pos.") name = name.replace("response", "rsp.") name = name.replace("regulation", "reg.") name = name.replace("...
Shorten GO name for tables in paper.
def printJobChildren(self): for job in self.jobsToReport: children = "CHILDREN_OF_JOB:%s " % job for level, jobList in enumerate(job.stack): for childJob in jobList: children += "\t(CHILD_JOB:%s,PRECEDENCE:%i)" % (childJob, level) print(chi...
Takes a list of jobs, and prints their successors.
def add_task(self, task, func=None, **kwargs): if not self.__tasks: raise Exception("Tasks subparsers is disabled") if 'help' not in kwargs: if func.__doc__: kwargs['help'] = func.__doc__ task_parser = self.__tasks.add_parser(task, **kwargs) if sel...
Add a task parser
def _draw_ap_score(self, score, label=None): label = label or "Avg Precision={:0.2f}".format(score) if self.ap_score: self.ax.axhline( y=score, color="r", ls="--", label=label )
Helper function to draw the AP score annotation
def index_complement(index_list, len_=None): mask1 = index_to_boolmask(index_list, len_) mask2 = not_list(mask1) index_list_bar = list_where(mask2) return index_list_bar
Returns the other indicies in a list of length ``len_``
def getFlaskResponse(responseString, httpStatus=200): return flask.Response(responseString, status=httpStatus, mimetype=MIMETYPE)
Returns a Flask response object for the specified data and HTTP status.
def point_stokes(self, context): stokes = np.empty(context.shape, context.dtype) stokes[:,:,0] = 1 stokes[:,:,1:4] = 0 return stokes
Return a stokes parameter array to montblanc
def make_blastdb(self): db = os.path.splitext(self.formattedprimers)[0] nhr = '{db}.nhr'.format(db=db) if not os.path.isfile(str(nhr)): command = 'makeblastdb -in {primerfile} -parse_seqids -max_file_sz 2GB -dbtype nucl -out {outfile}'\ .format(primerfile=self.formatt...
Create a BLAST database of the primer file
def calc_temperature_stats(self): self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_course_by_month(self.data.temp, normalize=True)
Calculates statistics in order to derive diurnal patterns of temperature
def __get_file_path(self, path, saltenv='base'): try: path = self._check_proto(path) except MinionError as err: if not os.path.isfile(path): log.warning( 'specified file %s is not present to generate hash: %s', path, err ...
Return either a file path or the result of a remote find_file call.
def _filter(self, criteria: Q, db): negated = criteria.negated input_db = None if criteria.connector == criteria.AND: input_db = db for child in criteria.children: if isinstance(child, Q): input_db = self._filter(child, input_db) ...
Recursive function to filter items from dictionary
async def close_authenticator_async(self): _logger.info("Shutting down CBS session on connection: %r.", self._connection.container_id) try: self._cbs_auth.destroy() _logger.info("Auth closed, destroying session on connection: %r.", self._connection.container_id) await...
Close the CBS auth channel and session asynchronously.
def register_callback(self): cid = str(self.__cid) self.__cid += 1 event = queue.Queue() self.__callbacks[cid] = event return cid, event
Register callback that we will have to wait for
def process_bucket_inventory(bid, inventory_bucket, inventory_prefix): log.info("Loading bucket %s keys from inventory s3://%s/%s", bid, inventory_bucket, inventory_prefix) account, bucket = bid.split(':', 1) region = connection.hget('bucket-regions', bid) versioned = bool(int(connection.hg...
Load last inventory dump and feed as key source.
def make_dir(project): project_path = os.path.join(os.path.dirname(__file__), project) if os.path.exists(project_path): shutil.rmtree(project_path) os.mkdir(project_path) with open(os.path.join(project_path, '__init__.py'), 'w') as fp: fp.write('__version__ = "' + str(get_property('__ver...
Creates the project directory for compiled modules.