INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Add an event to the heap/ priority queue
def add_event(self, event): """ Add an event to the heap/priority queue Parameters ---------- event : Event """ assert event.dep_time_ut <= event.arr_time_ut heappush(self.heap, event)
Parameters ---------- transfer_distances: e: Event start_time_ut: int walk_speed: float uninfected_stops: list max_duration_ut: int
def add_walk_events_to_heap(self, transfer_distances, e, start_time_ut, walk_speed, uninfected_stops, max_duration_ut): """ Parameters ---------- transfer_distances: e : Event start_time_ut : int walk_speed : float uninfected_stops : list max_durat...
A simple checker that connections are coming in descending order of departure time and that no departure time has been skipped.
def _check_dep_time_is_valid(self, dep_time): """ A simple checker, that connections are coming in descending order of departure time and that no departure time has been "skipped". Parameters ---------- dep_time Returns ------- None """ ...
Update the profile with the new labels. Each new label should have the same departure_time.
def update(self, new_labels, departure_time_backup=None): """ Update the profile with the new labels. Each new label should have the same departure_time. Parameters ---------- new_labels: list[LabelTime] Returns ------- added: bool wh...
Get the pareto_optimal set of Labels given a departure time.
def evaluate(self, dep_time, first_leg_can_be_walk=True, connection_arrival_time=None): """ Get the pareto_optimal set of Labels, given a departure time. Parameters ---------- dep_time : float, int time in unix seconds first_leg_can_be_walk : bool, optional ...
Parameters ---------- neighbor_label_bags: list each list element is a list of labels corresponding to a neighboring node ( note: only labels with first connection being a departure should be included ) walk_durations: list departure_arrival_stop_pairs: list of tuples Returns ------- None
def finalize(self, neighbor_label_bags=None, walk_durations=None, departure_arrival_stop_pairs=None): """ Parameters ---------- neighbor_label_bags: list each list element is a list of labels corresponding to a neighboring node (note: only labels with first conne...
Does this GTFS contain this file? ( file specified by the class )
def exists_by_source(self): """Does this GTFS contain this file? (file specified by the class)""" exists_list = [] for source in self.gtfs_sources: if isinstance(source, dict): # source can now be either a dict or a zipfile if self.fname in source: ...
Make table definitions
def create_table(self, conn): """Make table definitions""" # Make cursor cur = conn.cursor() # Drop table if it already exists, to be recreated. This # could in the future abort if table already exists, and not # recreate it from scratch. #cur.execute('''DROP TAB...
Load data from GTFS file into database
def insert_data(self, conn): """Load data from GTFS file into database""" cur = conn.cursor() # This is a bit hackish. It is annoying to have to write the # INSERT statement yourself and keep it up to date with the # table rows. This gets the first row, figures out the field ...
Do the actual import. Copy data and store in connection object.
def import_(self, conn): """Do the actual import. Copy data and store in connection object. This function: - Creates the tables - Imports data (using self.gen_rows) - Run any post_import hooks. - Creates any indexs - Does *not* run self.make_views - those must be...
Copy data from one table to another while filtering data at the same time
def copy(cls, conn, **where): """Copy data from one table to another while filtering data at the same time Parameters ---------- conn: sqlite3 DB connection. It must have a second database attached as "other". **where : keyword arguments specifying (star...
Returns a dataframe of aggregated sections from source nodes to target. The returned sections are either transfer point to transfer point or stop to stop. In a before after setting the results can be filtered based on values in a difference db.: param target:: param fastest_path:: param min_boardings:: param all_leg_se...
def get_journey_legs_to_target(self, target, fastest_path=True, min_boardings=False, all_leg_sections=True, ignore_walk=False, diff_threshold=None, diff_path=None): """ Returns a dataframe of aggregated sections from source nodes to target. The returned...
Selects the stops for which the ratio or higher proportion of trips to the target passes trough a set of trough stops: param target: target of trips: param trough_stops: stops where the selected trips are passing trough: param ratio: threshold for inclusion: return:
def get_upstream_stops_ratio(self, target, trough_stops, ratio): """ Selects the stops for which the ratio or higher proportion of trips to the target passes trough a set of trough stops :param target: target of trips :param trough_stops: stops where the selected trips are passing trough...
Parameters ---------- gtfs
def get_spatial_bounds(gtfs, as_dict=False): """ Parameters ---------- gtfs Returns ------- min_lon: float max_lon: float min_lat: float max_lat: float """ stats = get_stats(gtfs) lon_min = stats['lon_min'] lon_max = stats['lon_max'] lat_min = stats['lat_min'...
Get median latitude AND longitude of stops
def get_median_lat_lon_of_stops(gtfs): """ Get median latitude AND longitude of stops Parameters ---------- gtfs: GTFS Returns ------- median_lat : float median_lon : float """ stops = gtfs.get_table("stops") median_lat = numpy.percentile(stops['lat'].values, 50) me...
Get mean latitude AND longitude of stops
def get_centroid_of_stops(gtfs): """ Get mean latitude AND longitude of stops Parameters ---------- gtfs: GTFS Returns ------- mean_lat : float mean_lon : float """ stops = gtfs.get_table("stops") mean_lat = numpy.mean(stops['lat'].values) mean_lon = numpy.mean(stop...
Writes data from get_stats to csv file
def write_stats_as_csv(gtfs, path_to_csv, re_write=False): """ Writes data from get_stats to csv file Parameters ---------- gtfs: GTFS path_to_csv: str filepath to the csv file to be generated re_write: insted of appending, create a new one. """ stats_dict = get_stat...
Get basic statistics of the GTFS data.
def get_stats(gtfs): """ Get basic statistics of the GTFS data. Parameters ---------- gtfs: GTFS Returns ------- stats: dict A dictionary of various statistics. Keys should be strings, values should be inputtable to a database (int, date, str, ...) (but not a li...
Count occurrences of values AND return it as a string.
def _distribution(gtfs, table, column): """Count occurrences of values AND return it as a string. Example return value: '1:5 2:15'""" cur = gtfs.conn.cursor() cur.execute('SELECT {column}, count(*) ' 'FROM {table} GROUP BY {column} ' 'ORDER BY {column}'.format(column=c...
Calculates fleet size estimates by two separate formula: 1. Considering all routes separately with no interlining and doing a deficit calculation at every terminal 2. By looking at the maximum number of vehicles in simultaneous movement
def _fleet_size_estimate(gtfs, hour, date): """ Calculates fleet size estimates by two separate formula: 1. Considering all routes separately with no interlining and doing a deficit calculation at every terminal 2. By looking at the maximum number of vehicles in simultaneous movement Parameters ...
Computes the temporal coverage of each source feed
def _feed_calendar_span(gtfs, stats): """ Computes the temporal coverage of each source feed Parameters ---------- gtfs: gtfspy.GTFS object stats: dict where to append the stats Returns ------- stats: dict """ n_feeds = _n_gtfs_sources(gtfs)[0] max_start = None ...
Return the frequency of all types of routes per day.
def route_frequencies(gtfs, results_by_mode=False): """ Return the frequency of all types of routes per day. Parameters ----------- gtfs: GTFS Returns ------- pandas.DataFrame with columns route_I, type, frequency """ day = gtfs.get_suitable_date_for_daily_extract() ...
Return all the number of vehicles ( i. e. busses trams etc ) that pass hourly through a stop in a time frame.
def hourly_frequencies(gtfs, st, et, route_type): """ Return all the number of vehicles (i.e. busses,trams,etc) that pass hourly through a stop in a time frame. Parameters ---------- gtfs: GTFS st : int start time of the time framein unix time et : int end time of the time f...
Return the sum of vehicle hours in a particular day by route type.
def get_vehicle_hours_by_type(gtfs, route_type): """ Return the sum of vehicle hours in a particular day by route type. """ day = gtfs.get_suitable_date_for_daily_extract() query = (" SELECT * , SUM(end_time_ds - start_time_ds)/3600 as vehicle_hours_type" " FROM" " (SELECT...
Scan the footpaths originating from stop_id
def _scan_footpaths(self, stop_id, walk_departure_time): """ Scan the footpaths originating from stop_id Parameters ---------- stop_id: int """ for _, neighbor, data in self._walk_network.edges_iter(nbunch=[stop_id], data=True): d_walk = data["d_walk"...
A Python decorator for printing out the execution time for a function.
def timeit(method): """ A Python decorator for printing out the execution time for a function. Adapted from: www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods """ def timed(*args, **kw): time_start = time.time() result = method(*args, *...
Validates/ checks a given GTFS feed with respect to a number of different issues.
def validate_and_get_warnings(self): """ Validates/checks a given GTFS feed with respect to a number of different issues. The set of warnings that are checked for, can be found in the gtfs_validator.ALL_WARNINGS Returns ------- warnings: WarningsContainer """ ...
Check that the password is valid.
def clean_password(self): """Check that the password is valid.""" value = self.cleaned_data.get('password') if value not in self.valid_passwords: raise forms.ValidationError('Incorrect password.') return value
When receiving the filled out form check for valid access.
def clean(self): """When receiving the filled out form, check for valid access.""" cleaned_data = super(AuthForm, self).clean() user = self.get_user() if self.staff_only and (not user or not user.is_staff): raise forms.ValidationError('Sorry, only staff are allowed.') ...
Check that the password is valid.
def authenticate(self, token_value): """Check that the password is valid. This allows for revoking of a user's preview rights by changing the valid passwords. """ try: backend_path, user_id = token_value.split(':', 1) except (ValueError, AttributeError): ...
Return a form class for a given string pointing to a lockdown form.
def get_lockdown_form(form_path): """Return a form class for a given string pointing to a lockdown form.""" if not form_path: raise ImproperlyConfigured('No LOCKDOWN_FORM specified.') form_path_list = form_path.split(".") new_module = ".".join(form_path_list[:-1]) attr = form_path_list[-1] ...
Check if each request is allowed to access the current resource.
def process_request(self, request): """Check if each request is allowed to access the current resource.""" try: session = request.session except AttributeError: raise ImproperlyConfigured('django-lockdown requires the Django ' 'sessi...
Handle redirects properly.
def redirect(self, request): """Handle redirects properly.""" url = request.path querystring = request.GET.copy() if self.logout_key and self.logout_key in request.GET: del querystring[self.logout_key] if querystring: url = '%s?%s' % (url, querystring.urle...
https:// github. com/ frictionlessdata/ datapackage - py#infer
def infer(pattern, base_path=None): """https://github.com/frictionlessdata/datapackage-py#infer """ package = Package({}, base_path=base_path) descriptor = package.infer(pattern) return descriptor
Returns the profile with the received ID as a dict
def get(self, profile_id): '''Returns the profile with the received ID as a dict If a local copy of the profile exists, it'll be returned. If not, it'll be downloaded from the web. The results are cached, so any subsequent calls won't hit the filesystem or the web. Args: ...
dict: Return the profile with the received ID as a dict ( None if it doesn t exist ).
def _get_profile(self, profile_id): '''dict: Return the profile with the received ID as a dict (None if it doesn't exist).''' profile_metadata = self._registry.get(profile_id) if not profile_metadata: return path = self._get_absolute_path(profile_metadata.get('schema...
dict: Return the registry as dict with profiles keyed by id.
def _get_registry(self, registry_path_or_url): '''dict: Return the registry as dict with profiles keyed by id.''' if registry_path_or_url.startswith('http'): profiles = self._load_json_url(registry_path_or_url) else: profiles = self._load_json_file(registry_path_or_url) ...
str: Return the received relative_path joined with the base path ( None if there were some error ).
def _get_absolute_path(self, relative_path): '''str: Return the received relative_path joined with the base path (None if there were some error).''' try: return os.path.join(self.base_path, relative_path) except (AttributeError, TypeError): pass
dict: Return the JSON at the local path or URL as a dict.
def _load_json_url(self, url): '''dict: Return the JSON at the local path or URL as a dict.''' res = requests.get(url) res.raise_for_status() return res.json()
Get descriptor base path if string or return None.
def get_descriptor_base_path(descriptor): """Get descriptor base path if string or return None. """ # Infer from path/url if isinstance(descriptor, six.string_types): if os.path.exists(descriptor): base_path = os.path.dirname(os.path.abspath(descriptor)) else: # ...
Retrieve descriptor.
def retrieve_descriptor(descriptor): """Retrieve descriptor. """ the_descriptor = descriptor if the_descriptor is None: the_descriptor = {} if isinstance(the_descriptor, six.string_types): try: if os.path.isfile(the_descriptor): with open(the_descriptor,...
Dereference data package descriptor ( IN - PLACE FOR NOW ).
def dereference_package_descriptor(descriptor, base_path): """Dereference data package descriptor (IN-PLACE FOR NOW). """ for resource in descriptor.get('resources', []): dereference_resource_descriptor(resource, base_path, descriptor) return descriptor
Dereference resource descriptor ( IN - PLACE FOR NOW ).
def dereference_resource_descriptor(descriptor, base_path, base_descriptor=None): """Dereference resource descriptor (IN-PLACE FOR NOW). """ PROPERTIES = ['schema', 'dialect'] if base_descriptor is None: base_descriptor = descriptor for property in PROPERTIES: value = descriptor.get(...
Apply defaults to data package descriptor ( IN - PLACE FOR NOW ).
def expand_package_descriptor(descriptor): """Apply defaults to data package descriptor (IN-PLACE FOR NOW). """ descriptor.setdefault('profile', config.DEFAULT_DATA_PACKAGE_PROFILE) for resource in descriptor.get('resources', []): expand_resource_descriptor(resource) return descriptor
Apply defaults to resource descriptor ( IN - PLACE FOR NOW ).
def expand_resource_descriptor(descriptor): """Apply defaults to resource descriptor (IN-PLACE FOR NOW). """ descriptor.setdefault('profile', config.DEFAULT_RESOURCE_PROFILE) if descriptor['profile'] == 'tabular-data-resource': # Schema schema = descriptor.get('schema') if schem...
Check if path is safe and allowed.
def is_safe_path(path): """Check if path is safe and allowed. """ contains_windows_var = lambda val: re.match(r'%.+%', val) contains_posix_var = lambda val: re.match(r'\$.+', val) unsafeness_conditions = [ os.path.isabs(path), ('..%s' % os.path.sep) in path, path.startswith(...
If descriptor is a path to zip file extract and return ( tempdir descriptor )
def _extract_zip_if_possible(descriptor): """If descriptor is a path to zip file extract and return (tempdir, descriptor) """ tempdir = None result = descriptor try: if isinstance(descriptor, six.string_types): res = requests.get(descriptor) res.raise_for_status() ...
Validate zipped data package
def _validate_zip(the_zip): """Validate zipped data package """ datapackage_jsons = [f for f in the_zip.namelist() if f.endswith('datapackage.json')] if len(datapackage_jsons) != 1: msg = 'DataPackage must have only one "datapackage.json" (had {n})' raise exceptions.DataPackageException(...
Slugify foreign key
def _slugify_foreign_key(schema): """Slugify foreign key """ for foreign_key in schema.get('foreignKeys', []): foreign_key['reference']['resource'] = _slugify_resource_name( foreign_key['reference'].get('resource', '')) return schema
https:// github. com/ frictionlessdata/ datapackage - py#package
def get_resource(self, name): """https://github.com/frictionlessdata/datapackage-py#package """ for resource in self.resources: if resource.name == name: return resource return None
https:// github. com/ frictionlessdata/ datapackage - py#package
def add_resource(self, descriptor): """https://github.com/frictionlessdata/datapackage-py#package """ self.__current_descriptor.setdefault('resources', []) self.__current_descriptor['resources'].append(descriptor) self.__build() return self.__resources[-1]
https:// github. com/ frictionlessdata/ datapackage - py#package
def remove_resource(self, name): """https://github.com/frictionlessdata/datapackage-py#package """ resource = self.get_resource(name) if resource: predicat = lambda resource: resource.get('name') != name self.__current_descriptor['resources'] = list(filter( ...
https:// github. com/ frictionlessdata/ datapackage - py#package
def infer(self, pattern=False): """https://github.com/frictionlessdata/datapackage-py#package """ # Files if pattern: # No base path if not self.__base_path: message = 'Base path is required for pattern infer' raise exceptions.Dat...
https:// github. com/ frictionlessdata/ datapackage - py#package
def save(self, target=None, storage=None, **options): """https://github.com/frictionlessdata/datapackage-py#package """ # Save package to storage if storage is not None: if not isinstance(storage, Storage): storage = Storage.connect(storage, **options) ...
tuple: Attributes defined in the schema and the data package.
def attributes(self): """tuple: Attributes defined in the schema and the data package. """ # Deprecate warnings.warn( 'Property "package.attributes" is deprecated.', UserWarning) # Get attributes attributes = set(self.to_dict().keys()) tr...
tuple: The schema s required attributed.
def required_attributes(self): """tuple: The schema's required attributed. """ # Deprecate warnings.warn( 'Property "package.required_attributes" is deprecated.', UserWarning) required = () # Get required try: if self.profile....
Validate this Data Package.
def validate(self): """"Validate this Data Package. """ # Deprecate warnings.warn( 'Property "package.validate" is deprecated.', UserWarning) descriptor = self.to_dict() self.profile.validate(descriptor)
Lazily yields each ValidationError for the received data dict.
def iter_errors(self): """"Lazily yields each ValidationError for the received data dict. """ # Deprecate warnings.warn( 'Property "package.iter_errors" is deprecated.', UserWarning) return self.profile.iter_errors(self.to_dict())
https:// github. com/ frictionlessdata/ datapackage - py#schema
def validate(self, descriptor): """https://github.com/frictionlessdata/datapackage-py#schema """ # Collect errors errors = [] for error in self._validator.iter_errors(descriptor): if isinstance(error, jsonschema.exceptions.ValidationError): message = ...
Lazily yields each ValidationError for the received data dict.
def iter_errors(self, data): """Lazily yields each ValidationError for the received data dict. """ # Deprecate warnings.warn( 'Property "profile.iter_errors" is deprecated.', UserWarning) for error in self._validator.iter_errors(data): yield ...
https:// github. com/ frictionlessdata/ datapackage - py#resource
def tabular(self): """https://github.com/frictionlessdata/datapackage-py#resource """ if self.__current_descriptor.get('profile') == 'tabular-data-resource': return True if not self.__strict: if self.__current_descriptor.get('format') in config.TABULAR_FORMATS: ...
https:// github. com/ frictionlessdata/ datapackage - py#resource
def iter(self, relations=False, **options): """https://github.com/frictionlessdata/datapackage-py#resource """ # Error for non tabular if not self.tabular: message = 'Methods iter/read are not supported for non tabular data' raise exceptions.DataPackageException(...
https:// github. com/ frictionlessdata/ datapackage - py#resource
def raw_iter(self, stream=False): """https://github.com/frictionlessdata/datapackage-py#resource """ # Error for inline if self.inline: message = 'Methods raw_iter/raw_read are not supported for inline data' raise exceptions.DataPackageException(message) ...
https:// github. com/ frictionlessdata/ datapackage - py#resource
def raw_read(self): """https://github.com/frictionlessdata/datapackage-py#resource """ contents = b'' with self.raw_iter() as filelike: for chunk in filelike: contents += chunk return contents
https:// github. com/ frictionlessdata/ datapackage - py#resource
def infer(self, **options): """https://github.com/frictionlessdata/datapackage-py#resource """ descriptor = deepcopy(self.__current_descriptor) # Blank -> Stop if self.__source_inspection.get('blank'): return descriptor # Name if not descriptor.get('...
https:// github. com/ frictionlessdata/ datapackage - py#resource
def commit(self, strict=None): """https://github.com/frictionlessdata/datapackage-py#resource """ if strict is not None: self.__strict = strict elif self.__current_descriptor == self.__next_descriptor: return False self.__current_descriptor = deepcopy(self...
https:// github. com/ frictionlessdata/ datapackage - py#resource
def save(self, target, storage=None, **options): """https://github.com/frictionlessdata/datapackage-py#resource """ # Save resource to storage if storage is not None: if self.tabular: self.infer() storage.create(target, self.schema.descriptor,...
Push Data Package to storage.
def push_datapackage(descriptor, backend, **backend_options): """Push Data Package to storage. All parameters should be used as keyword arguments. Args: descriptor (str): path to descriptor backend (str): backend name like `sql` or `bigquery` backend_options (dict): backend options...
Pull Data Package from storage.
def pull_datapackage(descriptor, name, backend, **backend_options): """Pull Data Package from storage. All parameters should be used as keyword arguments. Args: descriptor (str): path where to store descriptor name (str): name of the pulled datapackage backend (str): backend name l...
Convert resource s path and name to storage s table name.
def _convert_path(path, name): """Convert resource's path and name to storage's table name. Args: path (str): resource path name (str): resource name Returns: str: table name """ table = os.path.splitext(path)[0] table = table.replace(os.path.sep, '__') if name is ...
Restore resource s path and name from storage s table.
def _restore_path(table): """Restore resource's path and name from storage's table. Args: table (str): table name Returns: (str, str): resource path and name """ name = None splited = table.split('___') path = splited[0] if len(splited) == 2: name = splited[1] ...
Convert schemas to be compatible with storage schemas.
def _convert_schemas(mapping, schemas): """Convert schemas to be compatible with storage schemas. Foreign keys related operations. Args: mapping (dict): mapping between resource name and table name schemas (list): schemas Raises: ValueError: if there is no resource ...
Restore schemas from being compatible with storage schemas.
def _restore_resources(resources): """Restore schemas from being compatible with storage schemas. Foreign keys related operations. Args: list: resources from storage Returns: list: restored resources """ resources = deepcopy(resources) for resource in resources: s...
It is possible for some of gdb s output to be read before it completely finished its response. In that case a partial mi response was read which cannot be parsed into structured data. We want to ALWAYS parse complete mi records. To do this we store a buffer of gdb s output if the output did not end in a newline.
def _buffer_incomplete_responses(raw_output, buf): """It is possible for some of gdb's output to be read before it completely finished its response. In that case, a partial mi response was read, which cannot be parsed into structured data. We want to ALWAYS parse complete mi records. To do this, we store a ...
make file object non - blocking Windows doesn t have the fcntl module but someone on stack overflow supplied this code as an answer and it works http:// stackoverflow. com/ a/ 34504971/ 2893090
def _make_non_blocking(file_obj): """make file object non-blocking Windows doesn't have the fcntl module, but someone on stack overflow supplied this code as an answer, and it works http://stackoverflow.com/a/34504971/2893090""" if USING_WINDOWS: LPDWORD = POINTER(DWORD) PIPE_NOWAIT...
Spawn a new gdb subprocess with the arguments supplied to the object during initialization. If gdb subprocess already exists terminate it before spanwing a new one. Return int: gdb process id
def spawn_new_gdb_subprocess(self): """Spawn a new gdb subprocess with the arguments supplied to the object during initialization. If gdb subprocess already exists, terminate it before spanwing a new one. Return int: gdb process id """ if self.gdb_process: sel...
Verify there is a process object and that it is still running. Raise NoGdbProcessError if either of the above are not true.
def verify_valid_gdb_subprocess(self): """Verify there is a process object, and that it is still running. Raise NoGdbProcessError if either of the above are not true.""" if not self.gdb_process: raise NoGdbProcessError("gdb process is not attached") elif self.gdb_process.pol...
Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec.
def write( self, mi_cmd_to_write, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True, read_response=True, ): """Write to gdb process. Block while parsing responses from gdb for a maximum of timeout_sec. Args: mi_cmd_to_write (str or ...
Get response from GDB and block while doing so. If GDB does not have any response ready to be read by timeout_sec an exception is raised.
def get_gdb_response( self, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True ): """Get response from GDB, and block while doing so. If GDB does not have any response ready to be read by timeout_sec, an exception is raised. Args: timeout_sec (float): Maxim...
Get responses on windows. Assume no support for select and use a while loop.
def _get_responses_windows(self, timeout_sec): """Get responses on windows. Assume no support for select and use a while loop.""" timeout_time_sec = time.time() + timeout_sec responses = [] while True: try: self.gdb_process.stdout.flush() if PY...
Get responses on unix - like system. Use select to wait for output.
def _get_responses_unix(self, timeout_sec): """Get responses on unix-like system. Use select to wait for output.""" timeout_time_sec = time.time() + timeout_sec responses = [] while True: select_timeout = timeout_time_sec - time.time() # I prefer to not pass a neg...
Get parsed response list from string output Args: raw_output ( unicode ): gdb output to parse stream ( str ): either stdout or stderr
def _get_responses_list(self, raw_output, stream): """Get parsed response list from string output Args: raw_output (unicode): gdb output to parse stream (str): either stdout or stderr """ responses = [] raw_output, self._incomplete_output[stream] = _buffe...
Send signal name ( case insensitive ) or number to gdb subprocess gdbmi. send_signal_to_gdb ( 2 ) # valid gdbmi. send_signal_to_gdb ( sigint ) # also valid gdbmi. send_signal_to_gdb ( SIGINT ) # also valid
def send_signal_to_gdb(self, signal_input): """Send signal name (case insensitive) or number to gdb subprocess gdbmi.send_signal_to_gdb(2) # valid gdbmi.send_signal_to_gdb('sigint') # also valid gdbmi.send_signal_to_gdb('SIGINT') # also valid raises ValueError if signal_input...
Terminate gdb process Returns: None
def exit(self): """Terminate gdb process Returns: None""" if self.gdb_process: self.gdb_process.terminate() self.gdb_process.communicate() self.gdb_process = None return None
Build and debug an application programatically
def main(verbose=True): """Build and debug an application programatically For a list of GDB MI commands, see https://www.sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI.html """ # Build C program find_executable(MAKE_CMD) if not find_executable(MAKE_CMD): print( 'Could not fin...
Read count characters starting at self. index and return those characters as a string
def read(self, count): """Read count characters starting at self.index, and return those characters as a string """ new_index = self.index + count if new_index > self.len: buf = self.raw_text[self.index :] # return to the end, don't fail else: buf...
Advance the index past specific chars Args chars ( list ): list of characters to advance past
def advance_past_chars(self, chars): """Advance the index past specific chars Args chars (list): list of characters to advance past Return substring that was advanced past """ start_index = self.index while True: current_char = self.raw_text[self.index] ...
characters that gdb escapes that should not be escaped by this parser
def advance_past_string_with_gdb_escapes(self, chars_to_remove_gdb_escape=None): """characters that gdb escapes that should not be escaped by this parser """ if chars_to_remove_gdb_escape is None: chars_to_remove_gdb_escape = ['"'] buf = "" while True: ...
Parse gdb mi text and turn it into a dictionary.
def parse_response(gdb_mi_text): """Parse gdb mi text and turn it into a dictionary. See https://sourceware.org/gdb/onlinedocs/gdb/GDB_002fMI-Stream-Records.html#GDB_002fMI-Stream-Records for details on types of gdb mi output. Args: gdb_mi_text (str): String output from gdb Returns: ...
If values don t match print them and raise a ValueError otherwise continue Raises: ValueError if argumetns do not match
def assert_match(actual_char_or_str, expected_char_or_str): """If values don't match, print them and raise a ValueError, otherwise, continue Raises: ValueError if argumetns do not match""" if expected_char_or_str != actual_char_or_str: print("Expected") pprint(expected_char_or_str) ...
Get notify message and payload dict
def _get_notify_msg_and_payload(result, stream): """Get notify message and payload dict""" token = stream.advance_past_chars(["=", "*"]) token = int(token) if token != "" else None logger.debug("%s", fmt_green("parsing message")) message = stream.advance_past_chars([","]) logger.debug("parsed m...
Get result message and payload dict
def _get_result_msg_and_payload(result, stream): """Get result message and payload dict""" groups = _GDB_MI_RESULT_RE.match(result).groups() token = int(groups[0]) if groups[0] != "" else None message = groups[1] if groups[2] is None: payload = None else: stream.advance_past_ch...
Parse dictionary with optional starting character { return ( tuple ): Number of characters parsed from to_parse Parsed dictionary
def _parse_dict(stream): """Parse dictionary, with optional starting character '{' return (tuple): Number of characters parsed from to_parse Parsed dictionary """ obj = {} logger.debug("%s", fmt_green("parsing dict")) while True: c = stream.read(1) if c in _WHIT...
Parse key value combination return ( tuple ): Parsed key ( string ) Parsed value ( either a string array or dict )
def _parse_key_val(stream): """Parse key, value combination return (tuple): Parsed key (string) Parsed value (either a string, array, or dict) """ logger.debug("parsing key/val") key = _parse_key(stream) val = _parse_val(stream) logger.debug("parsed key/val") logger.deb...
Parse key value combination returns: Parsed key ( string )
def _parse_key(stream): """Parse key, value combination returns : Parsed key (string) """ logger.debug("parsing key") key = stream.advance_past_chars(["="]) logger.debug("parsed key:") logger.debug("%s", fmt_green(key)) return key
Parse value from string returns: Parsed value ( either a string array or dict )
def _parse_val(stream): """Parse value from string returns: Parsed value (either a string, array, or dict) """ logger.debug("parsing value") while True: c = stream.read(1) if c == "{": # Start object val = _parse_dict(stream) break ...
Parse an array stream should be passed the initial [ returns: Parsed array
def _parse_array(stream): """Parse an array, stream should be passed the initial [ returns: Parsed array """ logger.debug("parsing array") arr = [] while True: c = stream.read(1) if c in _GDB_MI_VALUE_START_CHARS: stream.seek(-1) val = _parse_val...
Dump python list as the parameter of javascript function: param parameters:: param variables:: return:
def as_parameters(*parameters, variables=None): """ Dump python list as the parameter of javascript function :param parameters: :param variables: :return: """ s = json.dumps(parameters) s = s[1:-1] if variables: for v in variables: ...
Generate the local url for a js file.: param js_name:: return:
def generate_local_url(self, js_name): """ Generate the local url for a js file. :param js_name: :return: """ host = self._settings['local_host'].format(**self._host_context).rstrip('/') return '{}/{}.js'.format(host, js_name)
getter () g ( item key ): pass
def ifetch_single(iterable, key, default=EMPTY, getter=None): """ getter() g(item, key):pass """ def _getter(item): if getter: custom_getter = partial(getter, key=key) return custom_getter(item) else: try: attrgetter = operator.attrget...