Search is not available for this dataset
text
stringlengths
75
104k
def compute(self, name, tdb): """[DEPRECATED] Legacy routine that concatenates position and velocity vectors. This routine is deprecated. Use the methods `position()` and `position_and_velocity()` instead. This method follows the same calling convention, but incurs extra copy operatio...
def compute_bundle(self, name, tdb, tdb2=0.0): """[DEPRECATED] Return a tuple of coefficients and parameters for `tdb`. The return value is a tuple that bundles together the coefficients and other Chebyshev intermediate values that are needed for the computation of either the position o...
def position_from_bundle(self, bundle): """[DEPRECATED] Return position, given the `coefficient_bundle()` return value.""" coefficients, days_per_set, T, twot1 = bundle return (T.T * coefficients).sum(axis=2)
def velocity_from_bundle(self, bundle): """[DEPRECATED] Return velocity, given the `coefficient_bundle()` return value.""" coefficients, days_per_set, T, twot1 = bundle coefficient_count = coefficients.shape[2] # Chebyshev derivative: dT = np.empty_like(T) dT[0] = 0.0 ...
def read_record(self, n): """Return record `n` as 1,024 bytes; records are indexed from 1.""" self.file.seek(n * K - K) return self.file.read(K)
def write_record(self, n, data): """Write `data` to file record `n`; records are indexed from 1.""" self.file.seek(n * K - K) return self.file.write(data)
def map_words(self, start, end): """Return a memory-map of the elements `start` through `end`. The memory map will offer the 8-byte double-precision floats ("elements") in the file from index `start` through to the index `end`, inclusive, both counting the first float as element 1. ...
def comments(self): """Return the text inside the comment area of the file.""" record_numbers = range(2, self.fward) if not record_numbers: return '' data = b''.join(self.read_record(n)[0:1000] for n in record_numbers) try: return data[:data.find(b'\4')].d...
def read_array(self, start, end): """Return floats from `start` to `end` inclusive, indexed from 1. The entire range of floats is immediately read into memory from the file, making this efficient for small sequences of floats whose values are all needed immediately. """ ...
def map_array(self, start, end): """Return floats from `start` to `end` inclusive, indexed from 1. Instead of pausing to load all of the floats into RAM, this routine creates a memory map which will load data from the file only as it is accessed, and then will let it expire back out to ...
def summary_records(self): """Yield (record_number, n_summaries, record_data) for each record. Readers will only use the second two values in each tuple. Writers can update the record using the `record_number`. """ record_number = self.fward unpack = self.summary_contro...
def summaries(self): """Yield (name, (value, value, ...)) for each summary in the file.""" length = self.summary_length step = self.summary_step for record_number, n_summaries, summary_data in self.summary_records(): name_data = self.read_record(record_number + 1) ...
def add_array(self, name, values, array): """Add a new array to the DAF file. The summary will be initialized with the `name` and `values`, and will have its start word and end word fields set to point to where the `array` of floats has been appended to the file. """ f ...
def close(self): """Close this SPK file.""" self.daf.file.close() for segment in self.segments: if hasattr(segment, '_data'): del segment._data self.daf._array = None self.daf._map = None
def describe(self, verbose=True): """Return a textual description of the segment.""" center = titlecase(target_names.get(self.center, 'Unknown center')) target = titlecase(target_names.get(self.target, 'Unknown target')) text = ('{0.start_jd:.2f}..{0.end_jd:.2f} {1} ({0.center})' ...
def compute(self, tdb, tdb2=0.0): """Compute the component values for the time `tdb` plus `tdb2`.""" for position in self.generate(tdb, tdb2): return position
def close(self): """Close this file.""" self.daf.file.close() for segment in self.segments: if hasattr(segment, '_data'): del segment._data
def describe(self, verbose=True): """Return a textual description of the segment.""" body = titlecase(target_names.get(self.body, 'Unknown body')) text = ('{0.start_jd:.2f}..{0.end_jd:.2f} frame={0.frame}' ' {1} ({0.body})'.format(self, body)) if verbose: tex...
def _load(self): """Map the coefficients into memory using a NumPy array. """ if self.data_type == 2: component_count = 3 else: raise ValueError('only binary PCK data type 2 is supported') init, intlen, rsize, n = self.daf.read_array(self.end_i - 3, self...
def compute(self, tdb, tdb2, derivative=True): """Generate angles and derivatives for time `tdb` plus `tdb2`. If ``derivative`` is true, return a tuple containing both the angle and its derivative; otherwise simply return the angles. """ scalar = not getattr(tdb, 'shape', 0) an...
def notify(msg, msg_type=0, t=None): "Show system notification with duration t (ms)" if platform.system() == 'Darwin': command = notify_command_osx(msg, msg_type, t) else: command = notify_command_linux(msg, t) os.system(command.encode('utf-8'))
def geturls_new_api(song_ids): """ 批量获取音乐的地址 """ br_to_quality = {128000: 'MD 128k', 320000: 'HD 320k'} alters = NetEase().songs_detail_new_api(song_ids) urls = [alter['url'] for alter in alters] return urls
def visit_Call(self, node): """ Visit a function call. We expect every logging statement and string format to be a function call. """ # CASE 1: We're in a logging statement if self.within_logging_statement(): if self.within_logging_argument() and self.is_for...
def visit_BinOp(self, node): """ Process binary operations while processing the first logging argument. """ if self.within_logging_statement() and self.within_logging_argument(): # handle percent format if isinstance(node.op, Mod): self.violations...
def visit_Dict(self, node): """ Process dict arguments. """ if self.should_check_whitelist(node): for key in node.keys: if key.s in self.whitelist or key.s.startswith("debug_"): continue self.violations.append((self.current...
def visit_JoinedStr(self, node): """ Process f-string arguments. """ if version_info >= (3, 6): if self.within_logging_statement(): if any(isinstance(i, FormattedValue) for i in node.values): if self.within_logging_argument(): ...
def visit_keyword(self, node): """ Process keyword arguments. """ if self.should_check_whitelist(node): if node.arg not in self.whitelist and not node.arg.startswith("debug_"): self.violations.append((self.current_logging_call, WHITELIST_VIOLATION.format(node...
def visit_ExceptHandler(self, node): """ Process except blocks. """ name = self.get_except_handler_name(node) if not name: super(LoggingVisitor, self).generic_visit(node) return self.current_except_names.append(name) super(LoggingVisitor,...
def detect_logging_level(self, node): """ Heuristic to decide whether an AST Call is a logging call. """ try: if self.get_id_attr(node.func.value) == "warnings": return None # NB: We could also look at the argument signature or the target attribut...
def get_except_handler_name(self, node): """ Helper to get the exception name from an ExceptHandler node in both py2 and py3. """ name = node.name if not name: return None if version_info < (3,): return name.id return name
def get_id_attr(self, value): """Check if value has id attribute and return it. :param value: The value to get id from. :return: The value.id. """ if not hasattr(value, "id") and hasattr(value, "value"): value = value.value return value.id
def is_bare_exception(self, node): """ Checks if the node is a bare exception name from an except block. """ return isinstance(node, Name) and node.id in self.current_except_names
def is_str_exception(self, node): """ Checks if the node is the expression str(e) or unicode(e), where e is an exception name from an except block """ return ( isinstance(node, Call) and isinstance(node.func, Name) and node.func.id in ('str', 'unicode...
def check_exc_info(self, node): """ Reports a violation if exc_info keyword is used with logging.error or logging.exception. """ if self.current_logging_level not in ('error', 'exception'): return for kw in node.keywords: if kw.arg == 'exc_info': ...
def delete_file_if_needed(instance, filefield_name): """Delete file from database only if needed. When editing and the filefield is a new file, deletes the previous file (if any) from the database. Call this function immediately BEFORE saving the instance. """ if instance.pk: model_clas...
def delete_file(instance, filefield_name): """Delete the file (if any) from the database. Call this function immediately AFTER deleting the instance. """ file_instance = getattr(instance, filefield_name) if file_instance: DatabaseFileStorage().delete(file_instance.name)
def db_file_widget(cls): """Edit the download-link inner text.""" def get_link_display(url): unquoted = unquote(url.split('%2F')[-1]) if sys.version_info.major == 2: # python 2 from django.utils.encoding import force_unicode unquoted = force_unicode(unquoted) re...
def rendered_content(self): """Returns the freshly rendered content for the template and context described by the PDFResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using t...
def render_to_response(self, context, **response_kwargs): """ Returns a PDF response with a template rendered with the given context. """ filename = response_kwargs.pop('filename', None) cmd_options = response_kwargs.pop('cmd_options', None) if issubclass(self.response_c...
def _options_to_args(**options): """ Converts ``options`` into a list of command-line arguments. Skip arguments where no value is provided For flag-type (No argument) variables, pass only the name and only then if the value is True """ flags = [] for name in sorted(options): value = ...
def wkhtmltopdf(pages, output=None, **kwargs): """ Converts html to PDF using http://wkhtmltopdf.org/. pages: List of file paths or URLs of the html to be converted. output: Optional output file path. If None, the output is returned. **kwargs: Passed to wkhtmltopdf via _extra_args() (See ...
def http_quote(string): """ Given a unicode string, will do its dandiest to give you back a valid ascii charset string you can use in, say, http headers and the like. """ if isinstance(string, six.text_type): try: import unidecode except ImportError: pass ...
def make_absolute_paths(content): """Convert all MEDIA files into a file://URL paths in order to correctly get it displayed in PDFs.""" overrides = [ { 'root': settings.MEDIA_ROOT, 'url': settings.MEDIA_URL, }, { 'root': settings.STATIC_ROOT, ...
def match(self, text): """If text is matched with pattern, return variable names specified(%{pattern:variable name}) in pattern and their corresponding values.If not matched, return None. custom patterns can be passed in by custom_patterns(pattern name, pattern regular expression pair) o...
def configure(module=None, prefix='MONGODB_', **kwargs): """Sets defaults for ``class Meta`` declarations. Arguments can either be extracted from a `module` (in that case all attributes starting from `prefix` are used): >>> import foo >>> configure(foo) or passed explicictly as keyword argume...
def _configure(cls, **defaults): """Updates class-level defaults for :class:`_Options` container.""" for attr in defaults: setattr(cls, attr, defaults[attr])
def to_underscore(string): """Converts a given string from CamelCase to under_score. >>> to_underscore('FooBar') 'foo_bar' """ new_string = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', string) new_string = re.sub(r'([a-z\d])([A-Z])', r'\1_\2', new_string) return new_string.lower()
def auto_index(mcs): """Builds all indices, listed in model's Meta class. >>> class SomeModel(Model) ... class Meta: ... indices = ( ... Index('foo'), ... ) .. note:: this will result in calls to :...
def find(self, *args, **kwargs): """Same as :meth:`pymongo.collection.Collection.find`, except it returns the right document class. """ return Cursor(self, *args, wrap=self.document_class, **kwargs)
def find_one(self, *args, **kwargs): """Same as :meth:`pymongo.collection.Collection.find_one`, except it returns the right document class. """ data = super(Collection, self).find_one(*args, **kwargs) if data: return self.document_class(data) return None
def parse_file(self, file_path, currency) -> List[PriceModel]: """ Load and parse a .csv file """ # load file # read csv into memory? contents = self.load_file(file_path) prices = [] # parse price elements for line in contents: price = self.pa...
def load_file(self, file_path) -> List[str]: """ Loads the content of the text file """ content = [] content = read_lines_from_file(file_path) return content
def parse_line(self, line: str) -> PriceModel: """ Parse a CSV line into a price element """ line = line.rstrip() parts = line.split(',') result = PriceModel() # symbol result.symbol = self.translate_symbol(parts[0]) # value result.value = Decimal(parts...
def translate_symbol(self, in_symbol: str) -> str: """ translate the incoming symbol into locally-used """ # read all mappings from the db if not self.symbol_maps: self.__load_symbol_maps() # translate the incoming symbol result = self.symbol_maps[in_symbol] if in_sym...
def __load_symbol_maps(self): """ Loads all symbol maps from db """ repo = SymbolMapRepository(self.__get_session()) all_maps = repo.get_all() self.symbol_maps = {} for item in all_maps: self.symbol_maps[item.in_symbol] = item.out_symbol
def __get_session(self): """ Reuses the same db session """ if not self.session: self.session = dal.get_default_session() return self.session
def add(symbol: str, date, value, currency: str): """ Add individual price """ symbol = symbol.upper() currency = currency.upper() app = PriceDbApplication() price = PriceModel() # security = SecuritySymbol("", "") price.symbol.parse(symbol) # price.symbol.mnemonic = price.symbol.mnemo...
def import_csv(filepath: str, currency: str): """ Import prices from CSV file """ logger.debug(f"currency = {currency}") # auto-convert to uppercase. currency = currency.upper() app = PriceDbApplication() app.logger = logger app.import_prices(filepath, currency)
def last(symbol: str): """ displays last price, for symbol if provided """ app = PriceDbApplication() # convert to uppercase if symbol: symbol = symbol.upper() # extract namespace sec_symbol = SecuritySymbol("", "") sec_symbol.parse(symbol) latest = app.get_late...
def list_prices(date, currency, last): """ Display all prices """ app = PriceDbApplication() app.logger = logger if last: # fetch only the last prices prices = app.get_latest_prices() else: prices = app.get_prices(date, currency) for price in prices: print(price)...
def download(ctx, help: bool, symbol: str, namespace: str, agent: str, currency: str): """ Download the latest prices """ if help: click.echo(ctx.get_help()) ctx.exit() app = PriceDbApplication() app.logger = logger if currency: currency = currency.strip() currency ...
def prune(symbol: str, all: str): """ Delete old prices, leaving just the last. """ app = PriceDbApplication() app.logger = logger count = 0 if symbol is not None: sec_symbol = SecuritySymbol("", "") sec_symbol.parse(symbol) deleted = app.prune(sec_symbol) if delete...
def get_default_session(): """ Return the default session. The path is read from the default config. """ from .config import Config, ConfigKeys db_path = Config().get(ConfigKeys.price_database) if not db_path: raise ValueError("Price database not set in the configuration file!") return get_...
def add_map(incoming, outgoing): """ Creates a symbol mapping """ db_path = Config().get(ConfigKeys.pricedb_path) session = get_session(db_path) new_map = SymbolMap() new_map.in_symbol = incoming new_map.out_symbol = outgoing session.add(new_map) session.commit() click.echo("Record...
def list_maps(): """ Displays all symbol maps """ db_path = Config().get(ConfigKeys.price_database) session = get_session(db_path) maps = session.query(SymbolMap).all() for item in maps: click.echo(item)
def get_by_id(self, symbol: str) -> SymbolMap: """ Finds the map by in-symbol """ return self.query.filter(SymbolMap.in_symbol == symbol).first()
def read_lines_from_file(file_path: str) -> List[str]: """ Read text lines from a file """ # check if the file exists? with open(file_path) as csv_file: content = csv_file.readlines() return content
def map_entity(self, entity: dal.Price) -> PriceModel: """ Map the price entity """ if not entity: return None result = PriceModel() result.currency = entity.currency # date/time dt_string = entity.date format_string = "%Y-%m-%d" if entity.ti...
def map_model(self, model: PriceModel) -> Price: """ Parse into the Price entity, ready for saving """ # assert isinstance(model, PriceModel) assert isinstance(model.symbol, SecuritySymbol) assert isinstance(model.datum, Datum) entity = Price() # Format date as ISO stri...
def __read_config(self, file_path: str): """ Read the config file """ if not os.path.exists(file_path): raise FileNotFoundError(f"File path not found: {file_path}") # check if file exists if not os.path.isfile(file_path): self.logger.error(f"file not found: {file_...
def __get_config_template_path(self) -> str: """ gets the default config path from resources """ filename = resource_filename( Requirement.parse(package_name), template_path + config_filename) return filename
def __create_user_config(self): """ Copy the config template into user's directory """ src_path = self.__get_config_template_path() src = os.path.abspath(src_path) if not os.path.exists(src): message = f"Config template not found {src}" self.logger.error(message)...
def get_config_path(self) -> str: """ Returns the path where the active config file is expected. This is the user's profile folder. """ dst_dir = self.__get_user_path() dst = dst_dir + "/" + config_filename return dst
def get_contents(self) -> str: """ Reads the contents of the config file """ content = None # with open(file_path) as cfg_file: # contents = cfg_file.read() # Dump the current contents into an in-memory file. in_memory = io.StringIO("") self.config.write(in_m...
def set(self, option: ConfigKeys, value): """ Sets a value in config """ assert isinstance(option, ConfigKeys) # As currently we only have 1 section. section = SECTION self.config.set(section, option.name, value) self.save()
def get(self, option: ConfigKeys): """ Retrieves a config value """ assert isinstance(option, ConfigKeys) # Currently only one section is used section = SECTION return self.config.get(section, option.name)
def save(self): """ Save the config file """ file_path = self.get_config_path() contents = self.get_contents() with open(file_path, mode='w') as cfg_file: cfg_file.write(contents)
def parse(self, symbol: str) -> (str, str): """ Splits the symbol into namespace, symbol tuple """ symbol_parts = symbol.split(":") namespace = None mnemonic = symbol if len(symbol_parts) > 1: namespace = symbol_parts[0] mnemonic = symbol_parts[1] ...
def add_price(self, price: PriceModel): """ Creates a new price record """ # assert isinstance(price, PriceModel) if not price: raise ValueError("Cannot add price. The received model is null!") mapper = mappers.PriceMapper() entity = mapper.map_model(price) ...
def add_price_entity(self, price: dal.Price): """ Adds the price """ from decimal import Decimal # check if the price already exists in db. repo = self.get_price_repository() existing = ( repo.query .filter(dal.Price.namespace == price.namespace) ...
def download_price(self, symbol: str, currency: str, agent: str) -> PriceModel: """ Download and save price online """ price = self.__download_price(symbol, currency, agent) self.save() return price
def download_prices(self, **kwargs): """ Downloads all the prices that are listed in the Security table. Accepts filter arguments: currency, agent, symbol, namespace. """ currency: str = kwargs.get('currency', None) if currency: currency = currency.upper() age...
def import_prices(self, file_path: str, currency_symbol: str): """ Incomplete """ from .csv import CsvParser assert isinstance(file_path, str) assert isinstance(currency_symbol, str) self.logger.debug(f"Importing {file_path}") parser = CsvParser() prices = parse...
def session(self): """ Returns the current db session """ if not self.__session: self.__session = dal.get_default_session() return self.__session
def get_prices(self, date: str, currency: str) -> List[PriceModel]: """ Fetches all the prices for the given arguments """ from .repositories import PriceRepository session = self.session repo = PriceRepository(session) query = repo.query if date: query = que...
def get_prices_on(self, on_date: str, namespace: str, symbol: str): """ Returns the latest price on the date """ repo = self.get_price_repository() query = ( repo.query.filter(dal.Price.namespace == namespace) .filter(dal.Price.symbol == symbol) .filter(dal.Pr...
def get_price_repository(self): """ Price repository """ from .repositories import PriceRepository if not self.price_repo: self.price_repo = PriceRepository(self.session) return self.price_repo
def get_security_repository(self): """ Security repository """ from .repositories import SecurityRepository if not self.security_repo: self.security_repo = SecurityRepository(self.session) return self.security_repo
def prune_all(self) -> int: """ Prune historical prices for all symbols, leaving only the latest. Returns the number of items removed. """ from .repositories import PriceRepository # get all symbols that have prices repo = PriceRepository() items = repo.q...
def prune(self, symbol: SecuritySymbol): """ Delete all but the latest available price for the given symbol. Returns the number of items removed. """ from .repositories import PriceRepository assert isinstance(symbol, SecuritySymbol) self.logger.debug(f"pruning ...
def save(self): """ Save changes """ if self.__session: self.session.commit() else: self.logger.warning("Save called but no session open.")
def __download_price(self, symbol: str, currency: str, agent: str): """ Downloads and parses the price """ from finance_quote_python import Quote assert isinstance(symbol, str) assert isinstance(currency, str) assert isinstance(agent, str) if not symbol: ret...
def __get_securities(self, currency: str, agent: str, symbol: str, namespace: str) -> List[dal.Security]: """ Fetches the securities that match the given filters """ repo = self.get_security_repository() query = repo.query if currency is not None: qu...
def partial(self): """Return partial of original function call""" ba = self.data["bound_args"] return state_partial(self.data["func"], *ba.args[1:], **ba.kwargs)
def update_child_calls(self): """Replace child nodes on original function call with their partials""" for node in filter(lambda n: len(n.arg_name), self.child_list): self.data["bound_args"].arguments[node.arg_name] = node.partial() self.updated = True
def descend(self, include_me=True): """Descend depth first into all child nodes""" if include_me: yield self for child in self.child_list: yield child yield from child.descend()
def multi_dec(f): """Decorator for multi to remove nodes for original test functions from root node""" @wraps(f) def wrapper(*args, **kwargs): args = ( args[0] if len(args) == 1 and isinstance(args[0], (list, tuple)) else args ) for arg in args: if isinstance...
def has_equal_part_len(state, name, unequal_msg): """Verify that a part that is zoomed in on has equal length. Typically used in the context of ``check_function_def()`` Arguments: name (str): name of the part for which to check the length to the corresponding part in the solution. unequal_...
def has_equal_ast(state, incorrect_msg=None, code=None, exact=True, append=None): """Test whether abstract syntax trees match between the student and solution code. ``has_equal_ast()`` can be used in two ways: * As a robust version of ``has_code()``. By setting ``code``, you can look for the AST represent...
def has_code(state, text, pattern=True, not_typed_msg=None): """Test the student code. Tests if the student typed a (pattern of) text. It is advised to use ``has_equal_ast()`` instead of ``has_code()``, as it is more robust to small syntactical differences that don't change the code's behavior. Args: ...