code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def from_timestamp( timestamp, tz=UTC ): dt = _datetime.datetime.utcfromtimestamp(timestamp) dt = datetime( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond ) if tz is not UTC or tz != "UTC": dt = dt.in_timezone(tz) return dt
Create a DateTime instance from a timestamp.
def _GetSubFlowNetworkLimit(self): subflow_network_limit = None if self.runner_args.per_client_network_limit_bytes: subflow_network_limit = self.runner_args.per_client_network_limit_bytes if self.runner_args.network_bytes_limit: remaining_network_quota = ( self.runner_args.network_byte...
Get current network limit for subflows.
def run(options, http_req_handler = HttpReqHandler): global _HTTP_SERVER for x in ('server_version', 'sys_version'): if _OPTIONS.get(x) is not None: setattr(http_req_handler, x, _OPTIONS[x]) _HTTP_SERVER = threading_tcp_server.KillableThreadingHTTPServer( _OPTIONS,...
Start and execute the server
def _unmarshall_reader(self, file_, d): return util.unmarshall_config_reader(file_, d, self._get_config_type())
Unmarshall a file into a `dict`.
def _to_spans(x): if isinstance(x, Candidate): return [_to_span(m) for m in x] elif isinstance(x, Mention): return [x.context] elif isinstance(x, TemporarySpanMention): return [x] else: raise ValueError(f"{type(x)} is an invalid argument type")
Convert a Candidate, Mention, or Span to a list of spans.
def expected_param_keys(self): expected_keys = [] r = re.compile('%\(([^\)]+)\)s') for block in self.keys(): for key in self[block].keys(): s = self[block][key] if type(s)!=str: continue md = re.search(r, s) whil...
returns a list of params that this ConfigTemplate expects to receive
def confirm_input(user_input): if isinstance(user_input, list): user_input = ''.join(user_input) try: u_inp = user_input.lower().strip() except AttributeError: u_inp = user_input if u_inp in ('q', 'quit', 'exit'): sys.exit() if u_inp in ('y', 'yes'): return Tr...
Check user input for yes, no, or an exit signal.
def replace(html, replacements=None): if not replacements: return html html = HTMLFragment(html) for r in replacements: r.replace(html) return unicode(html)
Performs replacements on given HTML string.
def textFromHTML(html): cleaner = lxml.html.clean.Cleaner(scripts=True) cleaned = cleaner.clean_html(html) return lxml.html.fromstring(cleaned).text_content()
Cleans and parses text from the given HTML.
def _template(node_id, value=None): "Check if a template is assigned to it and render that with the value" result = [] select_template_from_node = fetch_query_string('select_template_from_node.sql') try: result = db.execute(text(select_template_from_node), node_id=node_id) template_resul...
Check if a template is assigned to it and render that with the value
def list(self, search_opts=None): query = base.get_query_string(search_opts) return self._list('/plugins%s' % query, 'plugins')
Get a list of Plugins.
def read_tuple_ticks(self, symbol, start, end): if end is None: end=sys.maxint session=self.getReadSession()() try: rows=session.query(Tick).filter(and_(Tick.symbol == symbol, Tick.time >= int(start), ...
read ticks as tuple
def main(args): global logging, log args = parse_args(args) logging.basicConfig(format=LOG_FORMAT, level=logging.DEBUG if args.verbose else logging.INFO, stream=sys.stdout) df = cat_tweets(path=args.path, verbosity=args.verbose + 1, numtweets=args.numtweet...
API with args object containing configuration parameters
def prepare_fabric_fw(self, tenant_id, fw_dict, is_fw_virt, result): try: with self.mutex_lock: ret = self._prepare_fabric_fw_internal(tenant_id, fw_dict, is_fw_virt, result) except Exception as exc: LOG.error...
Top level routine to prepare the fabric.
def create_url(url_protocol, host, api, url_params): is_batch = url_params.pop("batch", None) apis = url_params.pop("apis", None) version = url_params.pop("version", None) or url_params.pop("v", None) method = url_params.pop('method', None) host_url_seg = url_protocol + "://%s" % host api_url_se...
Generate the proper url for sending off data for analysis
def fields(self) -> GraphQLFieldMap: try: fields = resolve_thunk(self._fields) except GraphQLError: raise except Exception as error: raise TypeError(f"{self.name} fields cannot be resolved: {error}") if not isinstance(fields, dict) or not all( ...
Get provided fields, wrapping them as GraphQLFields if needed.
def stop(self): self._done() if self._server: self._server.stop() self._server = None log.info('Stop!')
Stop all tasks, and the local proxy server if it's running.
def cfset_to_set(cfset): count = cf.CFSetGetCount(cfset) buffer = (c_void_p * count)() cf.CFSetGetValues(cfset, byref(buffer)) return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])
Convert CFSet to python set.
def accel_increase_transparency(self, *args): transparency = self.settings.styleBackground.get_int('transparency') if int(transparency) - 2 > 0: self.settings.styleBackground.set_int('transparency', int(transparency) - 2) return True
Callback to increase transparency.
def visit_emptynode(self, node, parent): return nodes.EmptyNode( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
visit an EmptyNode node by returning a fresh instance of it
def jtosparse(j): data = j.flatten().tolist() nobs, nf, nargs = j.shape indices = zip(*[(r, c) for n in xrange(nobs) for r in xrange(n * nf, (n + 1) * nf) for c in xrange(n * nargs, (n + 1) * nargs)]) return csr_matrix((data, indices), shape=(nobs * nf, nobs...
Generate sparse matrix coordinates from 3-D Jacobian.
def fixcode(**kwargs): repo_dir = Path(__file__).parent.absolute() source_dir = Path(repo_dir, package.__name__) if source_dir.exists(): print("Source code locate at: '%s'." % source_dir) print("Auto pep8 all python file ...") source_dir.autopep8(**kwargs) else: print("So...
auto pep8 format all python file in ``source code`` and ``tests`` dir.
def _rpc_action_stmt(self, stmt: Statement, sctx: SchemaContext) -> None: self._handle_child(RpcActionNode(), stmt, sctx)
Handle rpc or action statement.
def loads(cls, s): with closing(StringIO(s)) as fileobj: return cls.load(fileobj)
Load an instance of this class from YAML.
def repo_values(self): branches = [] commits = {} m_helper = Tools() status = m_helper.repo_branches(self.parentApp.repo_value['repo']) if status[0]: branches = status[1] status = m_helper.repo_commits(self.parentApp.repo_value['repo']) if stat...
Set the appropriate repo dir and get the branches and commits of it
def getTemplateInstruments(self): items = dict() templates = self._get_worksheet_templates_brains() for template in templates: template_obj = api.get_object(template) uid_template = api.get_uid(template_obj) instrument = template_obj.getInstrument() ...
Returns worksheet templates as JSON
def find_files(folder): files = [i for i in os.listdir(folder) if i.startswith("left")] files.sort() for i in range(len(files)): insert_string = "right{}".format(files[i * 2][4:]) files.insert(i * 2 + 1, insert_string) files = [os.path.join(folder, filename) for filename in files] re...
Discover stereo photos and return them as a pairwise sorted list.
def os_application_version_set(package): application_version = get_upstream_version(package) if not application_version: application_version_set(os_release(package)) else: application_version_set(application_version)
Set version of application for Juju 2.0 and later
def _write(self, session, openFile, replaceParamFile): targets = self.targetParameters openFile.write('%s\n' % self.numParameters) for target in targets: openFile.write('%s %s\n' % (target.targetVariable, target.varFormat))
Replace Param File Write to File Method
def profile(length=25): from werkzeug.contrib.profiler import ProfilerMiddleware app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length]) app.run()
Start the application under the code profiler
def generate(env): env['BUILDERS']['RMIC'] = RMICBuilder env['RMIC'] = 'rmic' env['RMICFLAGS'] = SCons.Util.CLVar('') env['RMICCOM'] = '$RMIC $RMICFLAGS -d ${TARGET.attributes.java_lookupdir} -classpath ${SOURCE.attributes.java_classdir} ${SOURCES.attributes.java_classname}' ...
Add Builders and construction variables for rmic to an Environment.
def read_settings(self): extent = setting('user_extent', None, str) if extent: extent = QgsGeometry.fromWkt(extent) if not extent.isGeosValid(): extent = None crs = setting('user_extent_crs', None, str) if crs: crs = QgsCoordinateRefere...
Set the IF state from QSettings.
def repeat_str(state): if state == const.REPEAT_STATE_OFF: return 'Off' if state == const.REPEAT_STATE_TRACK: return 'Track' if state == const.REPEAT_STATE_ALL: return 'All' return 'Unsupported'
Convert internal API repeat state to string.
def action_approve(self): for rec in self: if rec.state not in ['draft', 'to approve']: raise UserError( _("Can't approve page in '%s' state.") % rec.state) if not rec.am_i_approver: raise UserError(_( 'You are not a...
Set a change request as approved.
def tokenize(string, language=None, escape='___'): string = string.lower() if len(string) and not string[-1].isalnum(): character = string[-1] string = string[:-1] + ' ' + character string = string.replace('(', ' ( ') string = string.replace(')', ' ) ') if language: words = m...
Given a string, return a list of math symbol tokens
def stop_recording(self): self._stop_recording.set() with self._source_lock: self._source.stop() self._recording = False
Stop recording from the audio source.
def _from_dict(cls, _dict): args = {} if 'word_count' in _dict: args['word_count'] = _dict.get('word_count') else: raise ValueError( 'Required property \'word_count\' not present in TranslationResult JSON' ) if 'character_count' in _dic...
Initialize a TranslationResult object from a json dictionary.
def get(self, filepath): try: res = self.fs.get_file_details(filepath) res = res.to_dict() self.write(res) except OSError: raise tornado.web.HTTPError(404)
Get file details for the specified file.
def find(self, resource_id, query=None, **kwargs): if query is None: query = {} return self.client._get( self._url(resource_id), query, **kwargs )
Gets a single resource.
def _control_line(self, line): if line > float(self.LINE_LAST_PIXEL): return int(self.LINE_LAST_PIXEL) elif line < float(self.LINE_FIRST_PIXEL): return int(self.LINE_FIRST_PIXEL) else: return line
Control the asked line is ok
def add(self, path): path = os.path.abspath(path) if not os.path.exists(path): return if path in sys.path: return if self.index is not None: sys.path.insert(self.index, path) self.index += 1 else: sys.path.append(path)
Add the given path to the decided place in sys.path
def create_notifications(users, notification_model, notification_type, related_object): Notification = notification_model additional = related_object.__dict__ if related_object else '' notification_text = TEXTS[notification_type] % additional for user in users: n = Notification( to_u...
create notifications in a background job to avoid slowing down users
def getNorthSouthClone(self, i): north = self.getAdjacentClone(i, south=False) south = self.getAdjacentClone(i) return north, south
Returns the adjacent clone name from both sides.
def import_class(klass): mod = __import__(klass.rpartition('.')[0]) for segment in klass.split('.')[1:-1]: mod = getattr(mod, segment) return getattr(mod, klass.rpartition('.')[2])
Import the named class and return that class
def send_request(cls, sock, working_dir, command, *arguments, **environment): for argument in arguments: cls.write_chunk(sock, ChunkType.ARGUMENT, argument) for item_tuple in environment.items(): cls.write_chunk(sock, ChunkType.ENVIRONMENT, cls.ENVIRON_SEP...
Send the initial Nailgun request over the specified socket.
def parse_period(period: str): period = period.split(" - ") date_from = Datum() if len(period[0]) == 10: date_from.from_iso_date_string(period[0]) else: date_from.from_iso_long_date(period[0]) date_from.start_of_day() date_to = Datum() if len(period[1]) == 10: date_to...
parses period from date range picker. The received values are full ISO date
def _time_request(self, uri, method, **kwargs): start_time = time.time() resp, body = self.request(uri, method, **kwargs) self.times.append(("%s %s" % (method, uri), start_time, time.time())) return resp, body
Wraps the request call and records the elapsed time.
def Eg(self, **kwargs): return self.unstrained.Eg(**kwargs) + self.Eg_strain_shift(**kwargs)
Returns the strain-shifted bandgap, ``Eg``.
def reloadCompletedMeasurements(self): from pathlib import Path reloaded = [self.load(x.resolve()) for x in Path(self.dataDir).glob('*/*/*') if x.is_dir()] logger.info('Reloaded ' + str(len(reloaded)) + ' completed measurements') self.completeMeasurements = [x for x in reloaded if x is n...
Reloads the completed measurements from the backing store.
def draw_lines(self, callback): from MAVProxy.modules.mavproxy_map import mp_slipmap self.draw_callback = callback self.draw_line = [] self.map.add_object(mp_slipmap.SlipDefaultPopup(None))
draw a series of connected lines on the map, calling callback when done
def not_query(expression): compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): all_keys = index.get_all_keys() returned_keys = expression(index) return [key for key in all_keys if key not in returned_keys] return _not
Apply logical not operator to expression.
def nelect(self): site_symbols = list(set(self.poscar.site_symbols)) nelect = 0. for ps in self.potcar: if ps.element in site_symbols: site_symbols.remove(ps.element) nelect += self.structure.composition.element_composition[ ...
Gets the default number of electrons for a given structure.
def reset_max_values(self): self._max_values = {} for k in self._max_values_list: self._max_values[k] = 0.0
Reset the maximum values dict.
def avail_sizes(call=None): if call == 'action': raise SaltCloudSystemExit( 'The avail_sizes function must be called with ' '-f or --function, or with the --list-sizes option' ) conn = get_conn() data = conn.list_role_sizes() ret = {} for item in data.role_siz...
Return a list of sizes from Azure
def num_failures(self): min_time = time.time() - self.window while self.failures and self.failures[0] < min_time: self.failures.popleft() return len(self.failures)
Return the number of failures in the window.
def cli(ctx, hostname, username, password, config_dir, https): ctx.is_root = True ctx.user_values_entered = False ctx.config_dir = os.path.abspath(os.path.expanduser(config_dir)) ctx.config = load_config(ctx) ctx.hostname = hostname ctx.username = username ctx.password = password ctx.htt...
Command-line interface for interacting with a WVA device
def _rand1(self): "generate a single random sample" Z = _unwhiten_cf(self._S_cf, self._genA()) return Z.dot(Z.T)
generate a single random sample
def __initialize(self, resp): raw_data = xmltodict.parse(resp.content) root_key = list(raw_data.keys())[0] self.raw_data = raw_data.get(root_key) self.__initializeFromRaw()
Initialize from the response
def cache_key(self, repo: str, branch: str, task: Task, git_repo: Repo) -> str: return "{repo}_{branch}_{hash}_{task}".format(repo=self.repo_id(repo), branch=branch, hash=self.current_git_hash(repo, branc...
Returns the key used for storing results in cache.
def info(): try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } implementation_info = _implementation() urllib3_...
Generate information for a bug report.
def write_dfile(self): f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)") with open(f_in, "w") as f: f.write(self.as_dfile()) return f_in
Write the generated d_file to a temporary file.
def command(state, args): args = parser.parse_args(args[1:]) if args.complete: query.files.delete_regexp_complete(state.db) else: if args.aid is None: parser.print_help() else: aid = state.results.parse_aid(args.aid, default_key='db') query.files.d...
Unregister watching regexp for an anime.
def insert_line_above(self, copy_margin=True): if copy_margin: insert = self.document.leading_whitespace_in_current_line + '\n' else: insert = '\n' self.cursor_position += self.document.get_start_of_line_position() self.insert_text(insert) self.cursor_posi...
Insert a new line above the current one.
def make(cls, vol): if isinstance(vol, cls): return vol elif vol is None: return None else: return cls(vol, None)
Convert uuid to Volume, if necessary.
def _suicide_when_without_parent(self, parent_pid): while True: time.sleep(5) try: os.kill(parent_pid, 0) except OSError: self.stop() log.warning('The parent is not alive, exiting.') os._exit(999)
Kill this process when the parent died.
def selectnotin(table, field, value, complement=False): return select(table, field, lambda v: v not in value, complement=complement)
Select rows where the given field is not a member of the given value.
def write_output(self, data, args=None, filename=None, label=None): if args: if not args.outlog: return 0 if not filename: filename=args.outlog lastpath = '' with open(str(filename), 'w') as output_file: for entry in data['entries']: ...
Write log data to a log file
def create_html(s1, s2, output='test.html'): html = difflib.HtmlDiff().make_file(s1.split(), s2.split()) with open(output, 'w') as f: f.write(html)
creates basic html based on the diff of 2 strings
def fulfill(self, value): assert self._state==self.PENDING self._state=self.FULFILLED; self.value = value for callback in self._callbacks: try: callback(value) except Exception: pass self._callbacks = []
Fulfill the promise with a given value.
def count(self, *criterion, **kwargs): query = self._query(*criterion) query = self._filter(query, **kwargs) return query.count()
Count the number of models matching some criterion.
def _with_context(self, *args, **kwargs): context = dict(args[0] if args else self.env.context, **kwargs) return self.with_env(self.env(context=context))
As the `with_context` class method but for recordset.
def create_space(self): cur = self._conn.cursor() cur.executescript(SQL_MODEL) self._conn.commit() cur.close() return
Set up a new table space for the first time
def fixed_interval_scheduler(interval): start = time.time() next_tick = start while True: next_tick += interval yield next_tick
A scheduler that ticks at fixed intervals of "interval" seconds
def save(self, model_filename, optimizer_filename): serializers.save_hdf5(model_filename, self.model) serializers.save_hdf5(optimizer_filename, self.optimizer)
Save the state of the model & optimizer to disk
def health_check(cls): try: assert isinstance(settings.MIDDLEWARES, list) except AssertionError: yield HealthCheckFail( '00005', 'The "MIDDLEWARES" configuration key should be assigned ' 'to a list', ) return...
Checks that the configuration makes sense.
def _AddFieldPaths(node, prefix, field_mask): if not node: field_mask.paths.append(prefix) return for name in sorted(node): if prefix: child_path = prefix + '.' + name else: child_path = name _AddFieldPaths(node[name], child_path, field_mask)
Adds the field paths descended from node to field_mask.
def _extrn_path(self, url, saltenv, cachedir=None): url_data = urlparse(url) if salt.utils.platform.is_windows(): netloc = salt.utils.path.sanitize_win_path(url_data.netloc) else: netloc = url_data.netloc netloc = netloc.split('@')[-1] if cachedir is None:...
Return the extrn_filepath for a given url
def _ask_questionnaire(): answers = {} print(info_header) pprint(questions.items()) for question, default in questions.items(): response = _ask(question, default, str(type(default)), show_hint=True) if type(default) == unicode and type(response) != str: response = response.de...
Asks questions to fill out a HFOS plugin template
def frombits(cls, bits): return cls.frombitsets(map(cls.BitSet.frombits, bits))
Series from binary string arguments.
def check_validity(self): if not isinstance(self.pianoroll, np.ndarray): raise TypeError("`pianoroll` must be a numpy array.") if not (np.issubdtype(self.pianoroll.dtype, np.bool_) or np.issubdtype(self.pianoroll.dtype, np.number)): raise TypeError("The data type ...
Raise error if any invalid attribute found.
def check_transaction(self, code): response = self.get(url=self.config.TRANSACTION_URL % code) return PagSeguroNotificationResponse(response.content, self.config)
check a transaction by its code
def _has_z(self, kwargs): return ((self._type == 1 or self._type ==2) and (('z' in kwargs) or (self._element_z in kwargs)))
Returns True if type is 1 or 2 and z is explicitly defined in kwargs.
def _delete(self, bits, pos): assert 0 <= pos <= self.len assert pos + bits <= self.len if not pos: self._truncatestart(bits) return if pos + bits == self.len: self._truncateend(bits) return if pos > self.len - pos - bits: ...
Delete bits at pos.
def assert_subset(self, subset, superset, failure_message='Expected collection "{}" to be a subset of "{}'): assertion = lambda: set(subset).issubset(set(superset)) failure_message = unicode(failure_message).format(superset, subset) self.webdriver_assert(assertion, failure_message)
Asserts that a superset contains all elements of a subset
def _sec_to_readable(t): t = datetime(1, 1, 1) + timedelta(seconds=t) t = '{0:02d}:{1:02d}.{2:03d}'.format( t.hour * 60 + t.minute, t.second, int(round(t.microsecond / 1000.))) return t
Convert a number of seconds to a more readable representation.
def __redraw_loop(self): self.queue_draw() self.__drawing_queued = self.tweener and self.tweener.has_tweens() return self.__drawing_queued
loop until there is nothing more to tween
def list_backends(self, service_id, version_number): content = self._fetch("/service/%s/version/%d/backend" % (service_id, version_number)) return map(lambda x: FastlyBackend(self, x), content)
List all backends for a particular service and version.
def to_json(obj): i = StringIO.StringIO() w = Writer(i, encoding='UTF-8') w.write_value(obj) return i.getvalue()
Return a json string representing the python object obj.
def users(self): return Users(url="%s/users" % self.root, securityHandler=self._securityHandler, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
Provides access to all user resources
def abort_request(self, request): self.timedout = True try: request.cancel() except error.AlreadyCancelled: return
Called to abort request on timeout
def filter_directories(self): index = self.get_index('.spyproject') if index is not None: self.setRowHidden(index.row(), index.parent(), True)
Filter the directories to show
def load_all_from_directory(self, directory_path): datas = [] for root, folders, files in os.walk(directory_path): for f in files: datas.append(self.load_from_file(os.path.join(root, f))) return datas
Return a list of dict from a directory containing files
def _remove_decoration(self): if self._deco is not None: self.editor.decorations.remove(self._deco) self._deco = None
Removes the word under cursor's decoration
def GetRDFValueType(self): result = self.attribute_type for field_name in self.field_names: try: result = result.type_infos.get(field_name).type except AttributeError: raise AttributeError("Invalid attribute %s" % field_name) return result
Returns this attribute's RDFValue class.
def _fitImg(self, img): img = imread(img, 'gray') if self.bg is not None: img = cv2.subtract(img, self.bg) if self.lens is not None: img = self.lens.correct(img, keepSize=True) (H, _, _, _, _, _, _, n_matches) = self.findHomography(img) H_inv = self...
fit perspective and size of the input image to the reference image
def all_regions(self): regions = [] for sq in self._bam.header["SQ"]: regions.append((sq["SN"], 1, int(sq["LN"]))) return regions
Get a tuple of all chromosome, start and end regions.
def _process_metadata_response(topics, zk, default_min_isr): not_in_sync_partitions = [] for topic_name, partitions in topics.items(): min_isr = get_min_isr(zk, topic_name) or default_min_isr if min_isr is None: continue for metadata in partitions.values(): cur_is...
Returns not in sync partitions.
def add_space(window): row, col = window.getyx() _, max_cols = window.getmaxyx() n_cols = max_cols - col - 1 if n_cols <= 0: return window.addstr(row, col, ' ')
Shortcut for adding a single space to a window at the current position
def filelist2html(lst, fldr, hasHeader='N'): txt = '<TABLE width=100% border=0>' numRows = 1 if lst: for l in lst: if hasHeader == 'Y': if numRows == 1: td_begin = '<TH>' td_end = '</TH>' else: td...
formats a standard filelist to htmk using table formats
def fields(self): return ( self.locus, self.offset_start, self.offset_end, self.alignment_key)
Fields that should be considered for our notion of object equality.