text
stringlengths
81
112k
Factory method creates objects derived from :py:class`.Event` with class name matching the :py:class`.EventType`. :param event_type: number for type of event :returns: constructed event corresponding to ``event_type`` :rtype: :py:class:`.Event` def Create(event_type): """ ...
:returns: :py:class:`.ShiftSummary` by player for the home team :rtype: dict ``{ player_num: shift_summary_obj }`` def home_shift_summ(self): """ :returns: :py:class:`.ShiftSummary` by player for the home team :rtype: dict ``{ player_num: shift_summary_obj }`` """ if not...
:returns: :py:class:`.ShiftSummary` by player for the away team :rtype: dict ``{ player_num: shift_summary_obj }`` def away_shift_summ(self): """ :returns: :py:class:`.ShiftSummary` by player for the away team :rtype: dict ``{ player_num: shift_summary_obj }`` """ if not...
Retreive and parse Play by Play data for the given :py:class:`nhlscrapi.games.game.GameKey`` :returns: ``self`` on success, ``None`` otherwise def parse(self): """ Retreive and parse Play by Play data for the given :py:class:`nhlscrapi.games.game.GameKey`` :returns: ``self`` on succes...
Parse the home and away game rosters :returns: ``self`` on success, ``None`` otherwise def parse_rosters(self): """ Parse the home and away game rosters :returns: ``self`` on success, ``None`` otherwise """ lx_doc = self.html_doc() if not self.__blocks: ...
Parse the home and away healthy scratches :returns: ``self`` on success, ``None`` otherwise def parse_scratches(self): """ Parse the home and away healthy scratches :returns: ``self`` on success, ``None`` otherwise """ lx_doc = self.html_doc() if not self.__blo...
Parse the home and away coaches :returns: ``self`` on success, ``None`` otherwise def parse_coaches(self): """ Parse the home and away coaches :returns: ``self`` on success, ``None`` otherwise """ lx_doc = self.html_doc() tr = lx_doc.xpath('//tr[@id="HeadCoache...
Parse the officials :returns: ``self`` on success, ``None`` otherwise def parse_officials(self): """ Parse the officials :returns: ``self`` on success, ``None`` otherwise """ # begin proper body of method lx_doc = self.html_doc() off_parser = opm(self.g...
Validate an email address. Keyword arguments: address --- the email address as a string check_dns --- flag for whether to check the DNS status of the domain diagnose --- flag for whether to return True/False or a Diagnosis def is_email(address, check_dns=False, diagnose=False): """Validate an e...
Decorator that enforces one time loading for scrapers. The one time loading is applied to partial loaders, e.g. only parse and load the home team roster once. This is not meant to be used directly. :param scraper: property name (string) containing an object of type :py:class:`scrapr.ReportLoader` :...
Parse shifts from TOI report :returns: self if successfule else None def parse_shifts(self): """ Parse shifts from TOI report :returns: self if successfule else None """ lx_doc = self.html_doc() pl_heads = lx_doc.xpath('//td[contains(@c...
Check whether a domain has a valid MX or A record. Keyword arguments: domain --- the domain to check diagnose --- flag to report a diagnosis or a boolean (default False) def is_valid(self, domain, diagnose=False): """Check whether a domain has a valid MX or A record. Keywor...
:returns: the lxml processed html document :rtype: ``lxml.html.document_fromstring`` output def html_doc(self): """ :returns: the lxml processed html document :rtype: ``lxml.html.document_fromstring`` output """ if self.__lx_doc is None: cn = NHLCn()...
Parse the banner matchup meta info for the game. :returns: ``self`` on success or ``None`` def parse_matchup(self): """ Parse the banner matchup meta info for the game. :returns: ``self`` on success or ``None`` """ lx_doc = self.html_doc() try: ...
Generate and yield a stream of parsed plays. Useful for per play processing. def parse_plays_stream(self): """Generate and yield a stream of parsed plays. Useful for per play processing.""" lx_doc = self.html_doc() if lx_doc is not None: parser = PlayParser(self.game_key.se...
Returns a dictionary mapping the type of information in the RTSS play row to the appropriate column number. The column locations pre/post 2008 are different. :param season: int for the season number :returns: mapping of RTSS column to info type :rtype: dict, keys are ``'play_num...
Parses table row from RTSS. These are the rows tagged with ``<tr class='evenColor' ... >``. Result set contains :py:class:`nhlscrapi.games.playbyplay.Strength` and :py:class:`nhlscrapi.games.events.EventType` objects. Returned play data is in the form .. code:: python ...
Constructs dictionary of players on the ice in the provided table at time of play. :param tab: RTSS table of the skaters and goalie on at the time of the play :rtype: dictionary, key = player number, value = [position, name] def __skaters(self, tab): """ Constructs dictionary of players...
Exclude elements in list l containing any elements from list ex. Example: >>> l = ['bob', 'r', 'rob\r', '\r\nrobert'] >>> containing = ['\n', '\r'] >>> equal_to = ['r'] >>> exclude_from(l, containing, equal_to) ['bob'] def exclude_from(l, containing = [], equal_to = []): ...
inputs: surface - surface file (e.g. lh.pial, with full path) labels - label file (e.g. lh.cortex.label, with full path) annot - annot file (e.g. lh.aparc.a2009s.annot, with full path) reg - registration file (lh.sphere.reg) origin - the label from which we calculate distances target - target surface (e.g. ...
This function takes a list of files as input and vstacks them def stack_files(files, hemi, source, target): """ This function takes a list of files as input and vstacks them """ import csv import os import numpy as np fname = "sdist_%s_%s_%s.csv" % (hemi, source, target) filename = os.path.join(os.get...
Get short URL of blog post like '/blog/<slug>/' using ``get_absolute_url`` if available. Removes dependency on reverse URLs of Mezzanine views when deploying Mezzanine only as an API backend. def get_short_url(self, obj): """ Get short URL of blog post like '/blog/<slug>/' using ``get_absolute_...
Return the head-to-head face-off outcomes between two players. If the matchup didn't happen, ``{ }`` is returned. :param home_num: the number of the home team player :param away_num: the number of the away team player :returns: dict, either ``{ }`` or the following ...
Returns the overall faceoff win/total breakdown for home and away as :returns: dict, ``{ 'home/away': { 'won': won, 'total': total } }`` def team_totals(self): """ Returns the overall faceoff win/total breakdown for home and away as :returns: dict, ``{ 'home/away': { '...
Returns the faceoff win/total breakdown by zone for home and away as .. code:: python { 'home/away': { 'off/def/neut/all': { 'won': won, 'total': total } } } :returns: dict def by_zone(self): """ Retu...
Get the by team overall face-off win %. :returns: dict, ``{ 'home': %, 'away': % }`` def fo_pct(self): """ Get the by team overall face-off win %. :returns: dict, ``{ 'home': %, 'away': % }`` """ tots = self.team_totals return { t: t...
Get the by team face-off win % by zone. Format is :returns: dict ``{ 'home/away': { 'off/def/neut': % } }`` def fo_pct_by_zone(self): """ Get the by team face-off win % by zone. Format is :returns: dict ``{ 'home/away': { 'off/def/neut': % } }`` """ ...
Update the accumulator with the current play :returns: new tally :rtype: dict, ``{ 'period': per, 'time': clock, 'team': cumul, 'play': play }`` def update(self, play): """ Update the accumulator with the current play :returns: new tally :rtype: dict, `...
The Cori-share (% of shot attempts) for each team :returns: dict, ``{ 'home_name': %, 'away_name': % }`` def share(self): """ The Cori-share (% of shot attempts) for each team :returns: dict, ``{ 'home_name': %, 'away_name': % }`` """ tot = sum(self.tot...
Compute the stats defined in ``self.cum_stats``. :returns: collection of all computed :py:class:`.AccumulateStats` :rtype: dict def compute_stats(self): """ Compute the stats defined in ``self.cum_stats``. :returns: collection of all computed :py:class:`.Accumu...
Retrieves the nhl html reports for the specified game and report code def __html_rep(self, game_key, rep_code): """Retrieves the nhl html reports for the specified game and report code""" seas, gt, num = game_key.to_tuple() url = [ self.__domain, "scores/htmlreports/", str(seas-1), str(seas), ...
Transforms the ASCII control character symbols to their real char. Note: If the token is not an ASCII control character symbol, just return the token. Keyword arguments: token -- the token to transform def to_char(token): """Transforms the ASCII control character symbols to their real char. ...
Check that an address address conforms to RFCs 5321, 5322 and others. More specifically, see the follow RFCs: * http://tools.ietf.org/html/rfc5321 * http://tools.ietf.org/html/rfc5322 * http://tools.ietf.org/html/rfc4291#section-2.2 * http://tools.ietf.org/html/r...
Get source node list for a specified freesurfer label. Inputs ------- annot_input : freesurfer annotation label file label_name : freesurfer label name cortex : not used def load_freesurfer_label(annot_input, label_name, cortex=None): """ Get source node list for a specified freesurfer lab...
Print freesurfer label names. def get_freesurfer_label(annot_input, verbose = True): """ Print freesurfer label names. """ labels, color_table, names = nib.freesurfer.read_annot(annot_input) if verbose: print(names) return names
Visualize results on cortical surface using matplotlib. Inputs ------- coords : numpy array of shape (n_nodes,3), each row specifying the x,y,z coordinates of one node of surface mesh faces : numpy array of shape (n_faces, 3), each row specifying the indices of the three nodes b...
Remove medial wall from cortical surface to ensure that shortest paths are only calculated through the cortex. Inputs ------- surf : Tuple containing two numpy arrays of shape (n_nodes,3). Each node of the first array specifies the x, y, z coordinates one node of the surface mesh. Each node of t...
Remove triangles with nodes not contained in the cortex label array def triangles_keep_cortex(triangles, cortex): """ Remove triangles with nodes not contained in the cortex label array """ # for or each face/triangle keep only those that only contain nodes within the list of cortex nodes input_sh...
Convert source nodes to new surface (without medial wall). def translate_src(src, cortex): """ Convert source nodes to new surface (without medial wall). """ src_new = np.array(np.where(np.in1d(cortex, src))[0], dtype=np.int32) return src_new
Return data values to space of full cortex (including medial wall), with medial wall equal to zero. def recort(input_data, surf, cortex): """ Return data values to space of full cortex (including medial wall), with medial wall equal to zero. """ data = np.zeros(len(surf[0])) data[cortex] = input_da...
Thanks to juhuntenburg. Functions taken from https://github.com/juhuntenburg/brainsurfacescripts Finds those points on the complex mesh that correspond best to the simple mesh while forcing a one-to-one mapping. def find_node_match(simple_vertices, complex_vertices): """ Thanks to juhuntenburg. ...
Retreive and parse Event Summary report for the given :py:class:`nhlscrapi.games.game.GameKey` :returns: ``self`` on success, ``None`` otherwise def parse(self): """ Retreive and parse Event Summary report for the given :py:class:`nhlscrapi.games.game.GameKey` :returns...
Parse shot info for home team. :returns: ``self`` on success, ``None`` otherwise def parse_home_shots(self): """ Parse shot info for home team. :returns: ``self`` on success, ``None`` otherwise """ try: self.__set_shot_tables() s...
Parse shot info for away team. :returns: ``self`` on success, ``None`` otherwise def parse_away_shots(self): """ Parse shot info for away team. :returns: ``self`` on success, ``None`` otherwise """ try: self.__set_shot_tables() s...
Parse face-off info for home team. :returns: ``self`` on success, ``None`` otherwise def parse_home_fo(self): """ Parse face-off info for home team. :returns: ``self`` on success, ``None`` otherwise """ try: self.__set_fo_tables() ...
Parse face-off info for away team. :returns: ``self`` on success, ``None`` otherwise def parse_away_fo(self): """ Parse face-off info for away team. :returns: ``self`` on success, ``None`` otherwise """ try: self.__set_fo_tables() ...
Calculate exact geodesic distance along cortical surface from set of source nodes. "dist_type" specifies whether to calculate "min", "mean", "median", or "max" distance values from a region-of-interest. If running only on single node, defaults to "min". def dist_calc(surf, cortex, source_nodes): """ C...
Calculate closest nodes to each source node using exact geodesic distance along the cortical surface. def zone_calc(surf, cortex, src): """ Calculate closest nodes to each source node using exact geodesic distance along the cortical surface. """ cortex_vertices, cortex_triangles = surf_keep_cortex(sur...
Calculate exact geodesic distance along cortical surface from set of source nodes. "labels" specifies the freesurfer label file to use. All values will be used other than those specified in "exceptions" (default: 'Unknown' and 'Medial_Wall'). returns: dist_mat: symmetrical nxn matrix of minimum dista...
Retreive and parse Play by Play data for the given nhlscrapi.GameKey :returns: ``self`` on success, ``None`` otherwise def parse(self): """ Retreive and parse Play by Play data for the given nhlscrapi.GameKey :returns: ``self`` on success, ``None`` otherwise ""...
Parse only the home faceoffs :returns: ``self`` on success, ``None`` otherwise def parse_home_face_offs(self): """ Parse only the home faceoffs :returns: ``self`` on success, ``None`` otherwise """ self.__set_team_docs() self.face_offs['home'] =...
Parse only the away faceoffs :returns: ``self`` on success, ``None`` otherwise def parse_away_face_offs(self): """ Parse only the away faceoffs :returns: ``self`` on success, ``None`` otherwise """ self.__set_team_docs() self.face_offs['away'] =...
Loads a module by filename def load_module(filename): """ Loads a module by filename """ basename = os.path.basename(filename) path = os.path.dirname(filename) sys.path.append(path) # TODO(tlan) need to figure out how to handle errors thrown here return __import__(os.path.splitext(basename)[0])
Convert the machine list argument from a list of names into a mapping of logical names to physical hosts. This is similar to the _parse_configs function but separated to provide the opportunity for extension and additional checking of machine access def make_machine_mapping(machine_list): """ Convert the machi...
Parse a list of configuration properties separated by '=' def parse_config_list(config_list): """ Parse a list of configuration properties separated by '=' """ if config_list is None: return {} else: mapping = {} for pair in config_list: if (constants.CONFIG_SEPARATOR not in pair) or (pair....
Parse a configuration file. Currently only supports .json, .py and properties separated by '=' :param config_file_path: :return: a dict of the configuration properties def parse_config_file(config_file_path): """ Parse a configuration file. Currently only supports .json, .py and properties separated by '=' :...
:param ssh: :param command: :param msg: :param env: :param synch: :return: def exec_with_env(ssh, command, msg='', env={}, **kwargs): """ :param ssh: :param command: :param msg: :param env: :param synch: :return: """ bash_profile_command = "source .bash_profile > /dev/null 2...
Uses paramiko to execute a command but handles failure by raising a ParamikoError if the command fails. Note that unlike paramiko.SSHClient.exec_command this is not asynchronous because we wait until the exit status is known :Parameter ssh: a paramiko SSH Client :Parameter command: the command to execute ...
logs the output from a remote command the input should be an open channel in the case of synchronous better_exec_command otherwise this will not log anything and simply return to the caller :param chan: :return: def log_output(chan): """ logs the output from a remote command the input should be a...
Recursively copy a directory flattens the output into a single directory but prefixes the files with the path from the original input directory :param ftp: :param filename: :param outputdir: :param prefix: :param pattern: a regex pattern for files to match (by default matches everything) :return: ...
:param hostname: :param filename: :return: def open_remote_file(hostname, filename, mode='r', bufsize=-1, username=None, password=None): """ :param hostname: :param filename: :return: """ with get_ssh_client(hostname, username=username, password=password) as ssh: sftp = None f = Non...
Deploys the service to the host. This should at least perform the same actions as install and start but may perform additional tasks as needed. :Parameter unique_id: the name of the process :Parameter configs: a mao of configs the deployer may use to modify the deployment def deploy(self, unique_id, conf...
Undeploys the service. This should at least perform the same actions as stop and uninstall but may perform additional tasks as needed. :Parameter unique_id: the name of the process :Parameter configs: a map of configs the deployer may use def undeploy(self, unique_id, configs=None): """Undeploys the ...
Performs a soft bounce (stop and start) for the specified process :Parameter unique_id: the name of the process def soft_bounce(self, unique_id, configs=None): """ Performs a soft bounce (stop and start) for the specified process :Parameter unique_id: the name of the process """ self.stop(unique_...
Performs a hard bounce (kill and start) for the specified process :Parameter unique_id: the name of the process def hard_bounce(self, unique_id, configs=None): """ Performs a hard bounce (kill and start) for the specified process :Parameter unique_id: the name of the process """ self.kill(unique_...
Pauses the process for the specified delay and then resumes it :Parameter unique_id: the name of the process :Parameter delay: delay time in seconds def sleep(self, unique_id, delay, configs=None): """ Pauses the process for the specified delay and then resumes it :Parameter unique_id: the name of th...
Issues a sigstop for the specified process :Parameter unique_id: the name of the process def pause(self, unique_id, configs=None): """ Issues a sigstop for the specified process :Parameter unique_id: the name of the process """ pids = self.get_pid(unique_id, configs) if pids != constants.PROC...
Issues a signal for the specified process :Parameter unique_id: the name of the process def _send_signal(self, unique_id, signalno, configs): """ Issues a signal for the specified process :Parameter unique_id: the name of the process """ pids = self.get_pid(unique_id, configs) if pids != cons...
Issues a sigcont for the specified process :Parameter unique_id: the name of the process def resume(self, unique_id, configs=None): """ Issues a sigcont for the specified process :Parameter unique_id: the name of the process """ self._send_signal(unique_id, signal.SIGCONT,configs)
Issues a kill -9 to the specified process calls the deployers get_pid function for the process. If no pid_file/pid_keyword is specified a generic grep of ps aux command is executed on remote machine based on process parameters which may not be reliable if more process are running with similar name :Par...
Issues a kill -15 to the specified process :Parameter unique_id: the name of the process def terminate(self, unique_id, configs=None): """ Issues a kill -15 to the specified process :Parameter unique_id: the name of the process """ self._send_signal(unique_id, signal.SIGTERM, configs)
Issue a signal to hangup the specified process :Parameter unique_id: the name of the process def hangup(self, unique_id, configs=None): """ Issue a signal to hangup the specified process :Parameter unique_id: the name of the process """ self._send_signal(unique_id, signal.SIGHUP, configs)
deprecated name for fetch_logs def get_logs(self, unique_id, logs, directory, pattern=constants.FILTER_NAME_ALLOW_NONE): """deprecated name for fetch_logs""" self.fetch_logs(unique_id, logs, directory, pattern)
Copies logs from the remote host that the process is running on to the provided directory :Parameter unique_id the unique_id of the process in question :Parameter logs a list of logs given by absolute path from the remote host :Parameter directory the local directory to store the copied logs :Parameter...
Static method Copies logs from specified host on the specified install path :Parameter hostname the remote host from where we need to fetch the logs :Parameter install_path path where the app is installed :Parameter prefix prefix used to copy logs. Generall the unique_id of process :Parameter logs a li...
Generates the report def generate(self): """ Generates the report """ self._setup() for config_name in self.report_info.config_to_test_names_map.keys(): config_dir = os.path.join(self.report_info.resource_dir, config_name) utils.makedirs(config_dir) testsuite = self._generate_juni...
Copies the executable to the remote machine under install path. Inspects the configs for the possible keys 'hostname': the host to install on 'install_path': the location on the remote host 'executable': the executable to copy 'no_copy': if this config is passed in and true then this method will not cop...
Start the service. If `unique_id` has already been installed the deployer will start the service on that host. Otherwise this will call install with the configs. Within the context of this function, only four configs are considered 'start_command': the command to run (if provided will replace the default) ...
Stop the service. If the deployer has not started a service with`unique_id` the deployer will raise an Exception There are two configs that will be considered: 'terminate_only': if this config is passed in then this method is the same as terminate(unique_id) (this is also the behavior if stop_command is No...
uninstall the service. If the deployer has not started a service with `unique_id` this will raise a DeploymentError. This considers one config: 'additional_directories': a list of directories to remove in addition to those provided in the constructor plus the install path. This will update the directorie...
Gets the pid of the process with `unique_id`. If the deployer does not know of a process with `unique_id` then it should return a value of constants.PROCESS_NOT_RUNNING_PID def get_pid(self, unique_id, configs=None): """Gets the pid of the process with `unique_id`. If the deployer does not know of a process ...
Gets the host of the process with `unique_id`. If the deployer does not know of a process with `unique_id` then it should return a value of SOME_SENTINAL_VALUE :Parameter unique_id: the name of the process :raises NameError if the name is not valid process def get_host(self, unique_id): """Gets the ...
Terminates all the running processes. By default it is set to false. Users can set to true in config once the method to get_pid is done deterministically either using pid_file or an accurate keyword def kill_all_process(self): """ Terminates all the running processes. By default it is set to false. Use...
Converts a string to the corresponding log level def string_to_level(log_level): """ Converts a string to the corresponding log level """ if (log_level.strip().upper() == "DEBUG"): return logging.DEBUG if (log_level.strip().upper() == "INFO"): return logging.INFO if (log_level.strip().upper() == "W...
Parse command line arguments and then run the test suite def main(): """ Parse command line arguments and then run the test suite """ parser = argparse.ArgumentParser(description='A distributed test framework') parser.add_argument('testfile', help='The file that is used to determine the test suite run'...
Clear relevant globals to start fresh :return: def reset_all(): """ Clear relevant globals to start fresh :return: """ global _username global _password global _active_config global _active_tests global _machine_names global _deployers reset_deployers() reset_collector() _username = None ...
gets the config value associated with the config_option or returns an empty string if the config is not found :param config_option: :param default: if not None, will be used :return: value of config. If key is not in config, then default will be used if default is not set to None. Otherwise, KeyError is thrown...
Generates the report def generate(self): """ Generates the report """ self._setup() header_html = self._generate_header() footer_html = self._generate_footer() results_topbar_html = self._generate_topbar("results") summary_topbar_html = self._generate_topbar("summary") logs_topbar_...
for a given file def execute ( self, conn, dataset, dataset_access_type, transaction=False ): """ for a given file """ if not conn: dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/Dataset/UpdateType. Expects db connection from upper layer.", self.logger.exce...
This is a function to check all the input for GET APIs. def inputChecks(**_params_): """ This is a function to check all the input for GET APIs. """ def checkTypes(_func_, _params_ = _params_): log = clog.error_log @wraps(_func_) def wrapped(*args, **kw): arg_names =...
To check if a string has the required format. This is only used for POST APIs. def validateStringInput(input_key,input_data, read=False): """ To check if a string has the required format. This is only used for POST APIs. """ log = clog.error_log func = None if '*' in input_data or '%' in input_...
Lists all primary datasets if pattern is not provided. def execute(self, conn, transaction=False): """ Lists all primary datasets if pattern is not provided. """ sql = self.sql binds = {} cursors = self.dbi.processData(sql, binds, conn, transaction, returnCursor=True) ...
daoinput keys: migration_request_id def execute(self, conn, daoinput, transaction = False): """ daoinput keys: migration_request_id """ if not conn: dbsExceptionHandler("dbsException-failed-connect2host", "Oracle/MigrationRequests/Remove. Expects db connection from upper lay...
JSON streamer decorator def jsonstreamer(func): """JSON streamer decorator""" def wrapper (self, *args, **kwds): gen = func (self, *args, **kwds) yield "[" firstItem = True for item in gen: if not firstItem: yield "," else: ...
lumi_list must be of one of the two following formats: '[[a,b], [c,d],' or [a1, a2, a3] def decodeLumiIntervals(self, lumi_list): """lumi_list must be of one of the two following formats: '[[a,b], [c,d],' or [a1, a2, a3] """ errmessage = "lumi intervals must be of one of the two following formats...
List dataset access types def listDatasetAccessTypes(self, dataset_access_type=""): """ List dataset access types """ if isinstance(dataset_access_type, basestring): try: dataset_access_type = str(dataset_access_type) except: d...
Check the current request and block it if the IP address it's coming from is blacklisted. def block_before(self): """ Check the current request and block it if the IP address it's coming from is blacklisted. """ # To avoid unnecessary database queries, ignore the IP chec...
Return True if the given IP is blacklisted, False otherwise. def matches_ip(self, ip): """Return True if the given IP is blacklisted, False otherwise.""" # Check the cache if caching is enabled if self.cache is not None: matches_ip = self.cache.get(ip) if matches_ip is ...
Lists all primary datasets if pattern is not provided. def execute(self, conn, logical_file_name, block_name, block_id, transaction=False): """ Lists all primary datasets if pattern is not provided. """ binds = {} sql = '' if logical_file_name: if isinstance...
Returns all acquistion eras in dbs def listAcquisitionEras(self, acq=''): """ Returns all acquistion eras in dbs """ try: acq = str(acq) except: dbsExceptionHandler('dbsException-invalid-input', 'acquistion_era_name given is not valid : %s' %acq) ...