idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
34,500 | def from_backend ( self , dagobah_id ) : logger . debug ( 'Reconstructing Dagobah instance from backend with ID {0}' . format ( dagobah_id ) ) rec = self . backend . get_dagobah_json ( dagobah_id ) if not rec : raise DagobahError ( 'dagobah with id %s does not exist ' 'in backend' % dagobah_id ) self . _construct_from_... | Reconstruct this Dagobah instance from the backend . |
34,501 | def _construct_from_json ( self , rec ) : self . delete ( ) for required_key in [ 'dagobah_id' , 'created_jobs' ] : setattr ( self , required_key , rec [ required_key ] ) for job_json in rec . get ( 'jobs' , [ ] ) : self . _add_job_from_spec ( job_json ) self . commit ( cascade = True ) | Construct this Dagobah instance from a JSON document . |
34,502 | def add_job_from_json ( self , job_json , destructive = False ) : logger . debug ( 'Importing job from JSON document: {0}' . format ( job_json ) ) rec = self . backend . decode_import_json ( job_json ) if destructive : try : self . delete_job ( rec [ 'name' ] ) except DagobahError : pass self . _add_job_from_spec ( rec... | Construct a new Job from an imported JSON spec . |
34,503 | def _add_job_from_spec ( self , job_json , use_job_id = True ) : job_id = ( job_json [ 'job_id' ] if use_job_id else self . backend . get_new_job_id ( ) ) self . add_job ( str ( job_json [ 'name' ] ) , job_id ) job = self . get_job ( job_json [ 'name' ] ) if job_json . get ( 'cron_schedule' , None ) : job . schedule ( ... | Add a single job to the Dagobah from a spec . |
34,504 | def commit ( self , cascade = False ) : logger . debug ( 'Committing Dagobah instance with cascade={0}' . format ( cascade ) ) self . backend . commit_dagobah ( self . _serialize ( ) ) if cascade : [ job . commit ( ) for job in self . jobs ] | Commit this Dagobah instance to the backend . |
34,505 | def delete ( self ) : logger . debug ( 'Deleting Dagobah instance with ID {0}' . format ( self . dagobah_id ) ) self . jobs = [ ] self . created_jobs = 0 self . backend . delete_dagobah ( self . dagobah_id ) | Delete this Dagobah instance from the Backend . |
34,506 | def add_job ( self , job_name , job_id = None ) : logger . debug ( 'Creating a new job named {0}' . format ( job_name ) ) if not self . _name_is_available ( job_name ) : raise DagobahError ( 'name %s is not available' % job_name ) if not job_id : job_id = self . backend . get_new_job_id ( ) self . created_jobs += 1 sel... | Create a new empty Job . |
34,507 | def get_host ( self , hostname ) : if hostname in self . get_hosts ( ) : return self . load_ssh_conf ( ) . lookup ( hostname ) logger . warn ( 'Tried to find host with name {0}, but host not found' . format ( hostname ) ) return None | Returns a Host dict with config options or None if none exists |
34,508 | def get_job ( self , job_name ) : for job in self . jobs : if job . name == job_name : return job logger . warn ( 'Tried to find job with name {0}, but job not found' . format ( job_name ) ) return None | Returns a Job by name or None if none exists . |
34,509 | def delete_job ( self , job_name ) : logger . debug ( 'Deleting job {0}' . format ( job_name ) ) for idx , job in enumerate ( self . jobs ) : if job . name == job_name : self . backend . delete_job ( job . job_id ) del self . jobs [ idx ] self . commit ( ) return raise DagobahError ( 'no job with name %s exists' % job_... | Delete a job by name or error out if no such job exists . |
34,510 | def add_task_to_job ( self , job_or_job_name , task_command , task_name = None , ** kwargs ) : if isinstance ( job_or_job_name , Job ) : job = job_or_job_name else : job = self . get_job ( job_or_job_name ) if not job : raise DagobahError ( 'job %s does not exist' % job_or_job_name ) logger . debug ( 'Adding task with ... | Add a task to a job owned by the Dagobah instance . |
34,511 | def _name_is_available ( self , job_name ) : return ( False if [ job for job in self . jobs if job . name == job_name ] else True ) | Returns Boolean of whether the specified name is already in use . |
34,512 | def _serialize ( self , include_run_logs = False , strict_json = False ) : result = { 'dagobah_id' : self . dagobah_id , 'created_jobs' : self . created_jobs , 'jobs' : [ job . _serialize ( include_run_logs = include_run_logs , strict_json = strict_json ) for job in self . jobs ] } if strict_json : result = json . load... | Serialize a representation of this Dagobah object to JSON . |
34,513 | def commit ( self ) : logger . debug ( 'Committing job {0}' . format ( self . name ) ) self . backend . commit_job ( self . _serialize ( ) ) self . parent . commit ( ) | Store metadata on this Job to the backend . |
34,514 | def add_task ( self , command , name = None , ** kwargs ) : logger . debug ( 'Adding task with command {0} to job {1}' . format ( command , self . name ) ) if not self . state . allow_change_graph : raise DagobahError ( "job's graph is immutable in its current state: %s" % self . state . status ) if name is None : name... | Adds a new Task to the graph with no edges . |
34,515 | def add_dependency ( self , from_task_name , to_task_name ) : logger . debug ( 'Adding dependency from {0} to {1}' . format ( from_task_name , to_task_name ) ) if not self . state . allow_change_graph : raise DagobahError ( "job's graph is immutable in its current state: %s" % self . state . status ) self . add_edge ( ... | Add a dependency between two tasks . |
34,516 | def delete_task ( self , task_name ) : logger . debug ( 'Deleting task {0}' . format ( task_name ) ) if not self . state . allow_change_graph : raise DagobahError ( "job's graph is immutable in its current state: %s" % self . state . status ) if task_name not in self . tasks : raise DagobahError ( 'task %s does not exi... | Deletes the named Task in this Job . |
34,517 | def delete_dependency ( self , from_task_name , to_task_name ) : logger . debug ( 'Deleting dependency from {0} to {1}' . format ( from_task_name , to_task_name ) ) if not self . state . allow_change_graph : raise DagobahError ( "job's graph is immutable in its current state: %s" % self . state . status ) self . delete... | Delete a dependency between two tasks . |
34,518 | def schedule ( self , cron_schedule , base_datetime = None ) : logger . debug ( 'Scheduling job {0} with cron schedule {1}' . format ( self . name , cron_schedule ) ) if not self . state . allow_change_schedule : raise DagobahError ( "job's schedule cannot be changed in state: %s" % self . state . status ) if cron_sche... | Schedules the job to run periodically using Cron syntax . |
34,519 | def start ( self ) : logger . info ( 'Job {0} starting job run' . format ( self . name ) ) if not self . state . allow_start : raise DagobahError ( 'job cannot be started in its current state; ' + 'it is probably already running' ) self . initialize_snapshot ( ) if self . cron_iter and datetime . utcnow ( ) > self . ne... | Begins the job by kicking off all tasks with no dependencies . |
34,520 | def retry ( self ) : logger . info ( 'Job {0} retrying all failed tasks' . format ( self . name ) ) self . initialize_snapshot ( ) failed_task_names = [ ] for task_name , log in self . run_log [ 'tasks' ] . items ( ) : if log . get ( 'success' , True ) == False : failed_task_names . append ( task_name ) if len ( failed... | Restarts failed tasks of a job . |
34,521 | def terminate_all ( self ) : logger . info ( 'Job {0} terminating all currently running tasks' . format ( self . name ) ) for task in self . tasks . itervalues ( ) : if task . started_at and not task . completed_at : task . terminate ( ) | Terminate all currently running tasks . |
34,522 | def kill_all ( self ) : logger . info ( 'Job {0} killing all currently running tasks' . format ( self . name ) ) for task in self . tasks . itervalues ( ) : if task . started_at and not task . completed_at : task . kill ( ) | Kill all currently running jobs . |
34,523 | def edit ( self , ** kwargs ) : logger . debug ( 'Job {0} changing name to {1}' . format ( self . name , kwargs . get ( 'name' ) ) ) if not self . state . allow_edit_job : raise DagobahError ( 'job cannot be edited in its current state' ) if 'name' in kwargs and isinstance ( kwargs [ 'name' ] , str ) : if not self . pa... | Change this Job s name . |
34,524 | def edit_task ( self , task_name , ** kwargs ) : logger . debug ( 'Job {0} editing task {1}' . format ( self . name , task_name ) ) if not self . state . allow_edit_task : raise DagobahError ( "tasks cannot be edited in this job's " + "current state" ) if task_name not in self . tasks : raise DagobahError ( 'task %s no... | Change the name of a Task owned by this Job . |
34,525 | def _complete_task ( self , task_name , ** kwargs ) : logger . debug ( 'Job {0} marking task {1} as completed' . format ( self . name , task_name ) ) self . run_log [ 'tasks' ] [ task_name ] = kwargs for node in self . downstream ( task_name , self . snapshot ) : self . _start_if_ready ( node ) try : self . backend . a... | Marks this task as completed . Kwargs are stored in the run log . |
34,526 | def _put_task_in_run_log ( self , task_name ) : logger . debug ( 'Job {0} initializing run log entry for task {1}' . format ( self . name , task_name ) ) data = { 'start_time' : datetime . utcnow ( ) , 'command' : self . tasks [ task_name ] . command } self . run_log [ 'tasks' ] [ task_name ] = data | Initializes the run log task entry for this task . |
34,527 | def _on_completion ( self ) : logger . debug ( 'Job {0} running _on_completion check' . format ( self . name ) ) if self . state . status != 'running' or ( not self . _is_complete ( ) ) : return for job , results in self . run_log [ 'tasks' ] . iteritems ( ) : if results . get ( 'success' , False ) == False : self . _s... | Checks to see if the Job has completed and cleans up if it has . |
34,528 | def _start_if_ready ( self , task_name ) : logger . debug ( 'Job {0} running _start_if_ready for task {1}' . format ( self . name , task_name ) ) task = self . tasks [ task_name ] dependencies = self . _dependencies ( task_name , self . snapshot ) for dependency in dependencies : if self . run_log [ 'tasks' ] . get ( d... | Start this task if all its dependencies finished successfully . |
34,529 | def _commit_run_log ( self ) : logger . debug ( 'Committing run log for job {0}' . format ( self . name ) ) self . backend . commit_log ( self . run_log ) | Commit the current run log to the backend . |
34,530 | def _serialize ( self , include_run_logs = False , strict_json = False ) : try : topo_sorted = self . topological_sort ( ) t = [ self . tasks [ task ] . _serialize ( include_run_logs = include_run_logs , strict_json = strict_json ) for task in topo_sorted ] except : t = [ task . _serialize ( include_run_logs = include_... | Serialize a representation of this Job to a Python dict object . |
34,531 | def initialize_snapshot ( self ) : logger . debug ( 'Initializing DAG snapshot for job {0}' . format ( self . name ) ) if self . snapshot is not None : logging . warn ( "Attempting to initialize DAG snapshot without " + "first destroying old snapshot." ) snapshot_to_validate = deepcopy ( self . graph ) is_valid , reaso... | Copy the DAG and validate |
34,532 | def reset ( self ) : logger . debug ( 'Resetting task {0}' . format ( self . name ) ) self . stdout_file = os . tmpfile ( ) self . stderr_file = os . tmpfile ( ) self . stdout = "" self . stderr = "" self . started_at = None self . completed_at = None self . successful = None self . terminate_sent = False self . kill_s... | Reset this Task to a clean state prior to execution . |
34,533 | def start ( self ) : logger . info ( 'Starting task {0}' . format ( self . name ) ) self . reset ( ) if self . hostname : host = self . parent_job . parent . get_host ( self . hostname ) if host : self . remote_ssh ( host ) else : self . remote_failure = True else : self . process = subprocess . Popen ( self . command ... | Begin execution of this task . |
34,534 | def remote_ssh ( self , host ) : logger . info ( 'Starting remote execution of task {0} on host {1}' . format ( self . name , host [ 'hostname' ] ) ) try : self . remote_client = paramiko . SSHClient ( ) self . remote_client . load_system_host_keys ( ) self . remote_client . set_missing_host_key_policy ( paramiko . Aut... | Execute a command on SSH . Takes a paramiko host dict |
34,535 | def check_complete ( self ) : logger . debug ( 'Running check_complete for task {0}' . format ( self . name ) ) if self . remote_not_complete ( ) or self . local_not_complete ( ) : self . _start_check_timer ( ) return return_code = self . completed_task ( ) if self . terminate_sent : self . stderr += '\nDAGOBAH SENT SI... | Runs completion flow for this task if it s finished . |
34,536 | def remote_not_complete ( self ) : if self . remote_channel and not self . remote_channel . exit_status_ready ( ) : self . _timeout_check ( ) if self . remote_channel . recv_ready ( ) : self . stdout += self . remote_channel . recv ( 1024 ) if self . remote_channel . recv_stderr_ready ( ) : self . stderr += self . remo... | Returns True if this task is on a remote channel and on a remote machine False if it is either not remote or not completed |
34,537 | def local_not_complete ( self ) : if self . process and self . process . poll ( ) is None : self . _timeout_check ( ) return True return False | Returns True if task is local and not completed |
34,538 | def completed_task ( self ) : if self . remote_channel and self . remote_channel . exit_status_ready ( ) : while self . remote_channel . recv_ready ( ) : self . stdout += self . remote_channel . recv ( 1024 ) while self . remote_channel . recv_stderr_ready ( ) : self . stderr += self . remote_channel . recv_stderr ( 10... | Handle wrapping up a completed task local or remote |
34,539 | def terminate ( self ) : logger . info ( 'Sending SIGTERM to task {0}' . format ( self . name ) ) if hasattr ( self , 'remote_client' ) and self . remote_client is not None : self . terminate_sent = True self . remote_client . close ( ) return if not self . process : raise DagobahError ( 'task does not have a running p... | Send SIGTERM to the task s process . |
34,540 | def kill ( self ) : logger . info ( 'Sending SIGKILL to task {0}' . format ( self . name ) ) if hasattr ( self , 'remote_client' ) and self . remote_client is not None : self . kill_sent = True self . remote_client . close ( ) return if not self . process : raise DagobahError ( 'task does not have a running process' ) ... | Send SIGKILL to the task s process . |
34,541 | def _start_check_timer ( self ) : if self . timer : self . timer . cancel ( ) self . timer = threading . Timer ( 2.5 , self . check_complete ) self . timer . daemon = True self . timer . start ( ) | Periodically checks to see if the task has completed . |
34,542 | def _head_temp_file ( self , temp_file , num_lines ) : if not isinstance ( num_lines , int ) : raise DagobahError ( 'num_lines must be an integer' ) temp_file . seek ( 0 ) result , curr_line = [ ] , 0 for line in temp_file : curr_line += 1 result . append ( line . strip ( ) ) if curr_line >= num_lines : break return re... | Returns a list of the first num_lines lines from a temp file . |
34,543 | def _tail_temp_file ( self , temp_file , num_lines , seek_offset = 10000 ) : if not isinstance ( num_lines , int ) : raise DagobahError ( 'num_lines must be an integer' ) temp_file . seek ( 0 , os . SEEK_END ) size = temp_file . tell ( ) temp_file . seek ( - 1 * min ( size , seek_offset ) , os . SEEK_END ) result = [ ]... | Returns a list of the last num_lines lines from a temp file . |
34,544 | def _task_complete ( self , ** kwargs ) : logger . debug ( 'Running _task_complete for task {0}' . format ( self . name ) ) with self . parent_job . completion_lock : self . completed_at = datetime . utcnow ( ) self . successful = kwargs . get ( 'success' , None ) self . parent_job . _complete_task ( self . name , ** k... | Performs cleanup tasks and notifies Job that the Task finished . |
34,545 | def _serialize ( self , include_run_logs = False , strict_json = False ) : result = { 'command' : self . command , 'name' : self . name , 'started_at' : self . started_at , 'completed_at' : self . completed_at , 'success' : self . successful , 'soft_timeout' : self . soft_timeout , 'hard_timeout' : self . hard_timeout ... | Serialize a representation of this Task to a Python dict . |
34,546 | def do_login ( ) : dt_filter = lambda x : x >= datetime . utcnow ( ) - timedelta ( seconds = 60 ) app . config [ 'AUTH_ATTEMPTS' ] = filter ( dt_filter , app . config [ 'AUTH_ATTEMPTS' ] ) if len ( app . config [ 'AUTH_ATTEMPTS' ] ) > app . config [ 'AUTH_RATE_LIMIT' ] : return redirect ( url_for ( 'login' , alert = "R... | Attempt to auth using single login . Rate limited at the site level . |
34,547 | def return_standard_conf ( ) : result = resource_string ( __name__ , 'daemon/dagobahd.yml' ) result = result % { 'app_secret' : os . urandom ( 24 ) . encode ( 'hex' ) } return result | Return the sample config file . |
34,548 | def job_detail ( job_id = None ) : jobs = [ job for job in get_jobs ( ) if str ( job [ 'job_id' ] ) == job_id ] if not jobs : abort ( 404 ) return render_template ( 'job_detail.html' , job = jobs [ 0 ] , hosts = dagobah . get_hosts ( ) ) | Show a detailed description of a Job s status . |
34,549 | def task_detail ( job_id = None , task_name = None ) : jobs = get_jobs ( ) job = [ job for job in jobs if str ( job [ 'job_id' ] ) == job_id ] [ 0 ] return render_template ( 'task_detail.html' , job = job , task_name = task_name , task = [ task for task in job [ 'tasks' ] if task [ 'name' ] == task_name ] [ 0 ] ) | Show a detailed description of a specific task . |
34,550 | def log_detail ( job_id = None , task_name = None , log_id = None ) : jobs = get_jobs ( ) job = [ job for job in jobs if str ( job [ 'job_id' ] ) == job_id ] [ 0 ] return render_template ( 'log_detail.html' , job = job , task_name = task_name , task = [ task for task in job [ 'tasks' ] if task [ 'name' ] == task_name ]... | Show a detailed description of a specific log . |
34,551 | def _task_to_text ( self , task ) : started = self . _format_date ( task . get ( 'started_at' , None ) ) completed = self . _format_date ( task . get ( 'completed_at' , None ) ) success = task . get ( 'success' , None ) success_lu = { None : 'Not executed' , True : 'Success' , False : 'Failed' } run_log = task . get ( ... | Return a standard formatting of a Task serialization . |
34,552 | def _job_to_text ( self , job ) : next_run = self . _format_date ( job . get ( 'next_run' , None ) ) tasks = '' for task in job . get ( 'tasks' , [ ] ) : tasks += self . _task_to_text ( task ) tasks += '\n\n' return '\n' . join ( [ 'Job name: %s' % job . get ( 'name' , None ) , 'Cron schedule: %s' % job . get ( 'cron_s... | Return a standard formatting of a Job serialization . |
34,553 | def _get_template ( self , template_name , template_file ) : template = os . path . join ( self . location , 'templates' , template_name , template_file ) return jinja2 . Template ( open ( template ) . read ( ) ) | Returns a Jinja2 template of the specified file . |
34,554 | def replace_nones ( dict_or_list ) : def replace_none_in_value ( value ) : if isinstance ( value , basestring ) and value . lower ( ) == "none" : return None return value items = dict_or_list . iteritems ( ) if isinstance ( dict_or_list , dict ) else enumerate ( dict_or_list ) for accessor , value in items : if isinsta... | Update a dict or list in place to replace none string values with Python None . |
34,555 | def get_config_file ( ) : new_config_path = os . path . expanduser ( '~/.dagobahd.yml' ) config_dirs = [ '/etc' , os . path . expanduser ( '~' ) ] config_filenames = [ 'dagobahd.yml' , 'dagobahd.yaml' , '.dagobahd.yml' , '.dagobahd.yaml' ] for directory in config_dirs : for filename in config_filenames : try : if os . ... | Return the loaded config file if one exists . |
34,556 | def configure_event_hooks ( config ) : def print_event_info ( ** kwargs ) : print kwargs . get ( 'event_params' , { } ) def job_complete_email ( email_handler , ** kwargs ) : email_handler . send_job_completed ( kwargs [ 'event_params' ] ) def job_failed_email ( email_handler , ** kwargs ) : email_handler . send_job_fa... | Returns an EventHandler instance with registered hooks . |
34,557 | def init_core_logger ( location , config ) : logger = logging . getLogger ( 'dagobah' ) formatter = logging . Formatter ( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) if get_conf ( config , 'Logging.Core.enabled' , False ) == False : logger . addHandler ( NullHandler ( ) ) return config_filepath = get_conf ... | Initialize the logger with settings from config . |
34,558 | def get_backend ( config ) : backend_string = get_conf ( config , 'Dagobahd.backend' , None ) if backend_string is None : from . . backend . base import BaseBackend return BaseBackend ( ) elif backend_string . lower ( ) == 'mongo' : backend_kwargs = { } for conf_kwarg in [ 'host' , 'port' , 'db' , 'dagobah_collection' ... | Returns a backend instance based on the Daemon config file . |
34,559 | def api_call ( fn ) : @ wraps ( fn ) def wrapper ( * args , ** kwargs ) : try : result = fn ( * args , ** kwargs ) except ( DagobahError , DAGValidationError ) as e : if request and request . endpoint == fn . __name__ : return jsonify ( error_type = type ( e ) . __name__ , message = e . message ) , 400 raise e except E... | Returns function result in API format if requested from an API endpoint |
34,560 | def validate_dict ( in_dict , ** kwargs ) : if not isinstance ( in_dict , dict ) : raise ValueError ( 'requires a dictionary' ) for key , value in kwargs . iteritems ( ) : if key == 'required' : for required_key in value : if required_key not in in_dict : return False elif key not in in_dict : continue elif value == bo... | Returns Boolean of whether given dict conforms to type specifications given in kwargs . |
34,561 | def delete_dagobah ( self , dagobah_id ) : rec = self . dagobah_coll . find_one ( { '_id' : dagobah_id } ) for job in rec . get ( 'jobs' , [ ] ) : if 'job_id' in job : self . delete_job ( job [ 'job_id' ] ) self . log_coll . remove ( { 'parent_id' : dagobah_id } ) self . dagobah_coll . remove ( { '_id' : dagobah_id } ) | Deletes the Dagobah and all child Jobs from the database . |
34,562 | def commit_log ( self , log_json ) : log_json [ '_id' ] = log_json [ 'log_id' ] append = { 'save_date' : datetime . utcnow ( ) } for task_name , values in log_json . get ( 'tasks' , { } ) . items ( ) : for key , size in TRUNCATE_LOG_SIZES_CHAR . iteritems ( ) : if isinstance ( values . get ( key , None ) , str ) : if l... | Commits a run log to the Mongo backend . |
34,563 | def decode_import_json ( self , json_doc , transformers = None ) : def custom_decoder ( dct ) : def transform ( o ) : if not transformers : return o for conditionals , transformer in transformers : conditions_met = True for conditional in conditionals : try : condition_met = conditional ( o ) except : condition_met = F... | Decode a JSON string based on a list of transformers . |
34,564 | def publish ( self , data , type = None , id = None , retry = None , channel = 'sse' ) : message = Message ( data , type = type , id = id , retry = retry ) msg_json = json . dumps ( message . to_dict ( ) ) return self . redis . publish ( channel = channel , message = msg_json ) | Publish data as a server - sent event . |
34,565 | def cast ( cls , value , cast = str , subcast = None ) : if cast is bool : value = value . lower ( ) in cls . BOOLEAN_TRUE_STRINGS elif cast is float : float_str = re . sub ( r'[^\d,\.]' , '' , value ) parts = re . split ( r'[,\.]' , float_str ) if len ( parts ) == 1 : float_str = parts [ 0 ] else : float_str = "{0}.{1... | Parse and cast provided value . |
34,566 | def reload_list ( self ) : self . leetcode . load ( ) if self . leetcode . quizzes and len ( self . leetcode . quizzes ) > 0 : self . home_view = self . make_listview ( self . leetcode . quizzes ) self . view_stack = [ ] self . goto_view ( self . home_view ) | Press R in home view to retrieve quiz list |
34,567 | def simplices ( self ) : return [ Simplex ( [ self . points [ i ] for i in v ] ) for v in self . vertices ] | Returns the simplices of the triangulation . |
34,568 | def qhull_cmd ( cmd , options , points ) : prep_str = [ str ( len ( points [ 0 ] ) ) , str ( len ( points ) ) ] prep_str . extend ( [ ' ' . join ( map ( repr , row ) ) for row in points ] ) output = getattr ( hull , cmd ) ( options , "\n" . join ( prep_str ) ) return list ( map ( str . strip , output . strip ( ) . spli... | Generalized helper method to perform a qhull based command . |
34,569 | def qhalf ( options , halfspaces , interior_point ) : points = [ list ( h . normal ) + [ h . offset ] for h in halfspaces ] data = [ [ len ( interior_point ) , 1 ] ] data . append ( map ( repr , interior_point ) ) data . append ( [ len ( points [ 0 ] ) ] ) data . append ( [ len ( points ) ] ) data . extend ( [ map ( re... | Similar to qvoronoi command in command - line qhull . |
34,570 | def from_hyperplane ( basis , origin , point , internal = True ) : basis = np . array ( basis ) assert basis . shape [ 0 ] + 1 == basis . shape [ 1 ] big_basis = np . zeros ( ( basis . shape [ 1 ] , basis . shape [ 1 ] ) ) big_basis [ : basis . shape [ 0 ] , : basis . shape [ 1 ] ] = basis u , s , vh = np . linalg . sv... | Returns a Halfspace defined by a list of vectors parallel to the bounding hyperplane . |
34,571 | def vertices ( self ) : if self . _v_out is None : output = qhalf ( 'Fp' , self . halfspaces , self . interior_point ) pts = [ ] for l in output [ 2 : ] : pt = [ ] for c in l . split ( ) : c = float ( c ) if c != 10.101 and c != - 10.101 : pt . append ( c ) else : pt . append ( np . inf ) pts . append ( pt ) self . _v_... | Returns the vertices of the halfspace intersection |
34,572 | def _extract_player_stats ( self , table , player_dict , home_or_away ) : for row in table ( 'tbody tr' ) . items ( ) : player_id = self . _find_player_id ( row ) if not player_id : continue name = self . _find_player_name ( row ) try : player_dict [ player_id ] [ 'data' ] += str ( row ) . strip ( ) except KeyError : p... | Combine all player stats into a single object . |
34,573 | def _instantiate_players ( self , player_dict ) : home_players = [ ] away_players = [ ] for player_id , details in player_dict . items ( ) : player = BoxscorePlayer ( player_id , details [ 'name' ] , details [ 'data' ] ) if details [ 'team' ] == HOME : home_players . append ( player ) else : away_players . append ( pla... | Create a list of player instances for both the home and away teams . |
34,574 | def winning_name ( self ) : if self . winner == HOME : return self . _home_name . text ( ) return self . _away_name . text ( ) | Returns a string of the winning team s name such as Houston Astros . |
34,575 | def winning_abbr ( self ) : if self . winner == HOME : return utils . _parse_abbreviation ( self . _home_name ) return utils . _parse_abbreviation ( self . _away_name ) | Returns a string of the winning team s abbreviation such as HOU for the Houston Astros . |
34,576 | def losing_name ( self ) : if self . winner == HOME : return self . _away_name . text ( ) return self . _home_name . text ( ) | Returns a string of the losing team s name such as Los Angeles Dodgers . |
34,577 | def losing_abbr ( self ) : if self . winner == HOME : return utils . _parse_abbreviation ( self . _away_name ) return utils . _parse_abbreviation ( self . _home_name ) | Returns a string of the losing team s abbreviation such as LAD for the Los Angeles Dodgers . |
34,578 | def _create_url ( self , date ) : return BOXSCORES_URL % ( date . year , date . month , date . day ) | Build the URL based on the passed datetime object . |
34,579 | def _get_score ( self , score_link ) : score = score_link . replace ( '<td class="right">' , '' ) score = score . replace ( '</td>' , '' ) return int ( score ) | Find a team s final score . |
34,580 | def _get_team_results ( self , team_result_html ) : link = [ i for i in team_result_html ( 'td a' ) . items ( ) ] if len ( link ) < 1 : return None name , abbreviation = self . _get_name ( link [ 0 ] ) return name , abbreviation | Extract the winning or losing team s name and abbreviation . |
34,581 | def _find_games ( self , date , end_date ) : if not end_date or date > end_date : end_date = date date_step = date while date_step <= end_date : url = self . _create_url ( date_step ) page = self . _get_requested_page ( url ) games = page ( 'table[class="teams"]' ) . items ( ) boxscores = self . _extract_game_info ( ga... | Retrieve all major games played on a given day . |
34,582 | def _parse_season ( self , row ) : season = utils . _parse_field ( PLAYER_SCHEME , row , 'season' ) return season . replace ( '*' , '' ) . replace ( '+' , '' ) | Parse the season string from the table . |
34,583 | def _combine_season_stats ( self , table_rows , career_stats , all_stats_dict ) : most_recent_season = self . _most_recent_season if not table_rows : table_rows = [ ] for row in table_rows : season = self . _parse_season ( row ) try : all_stats_dict [ season ] [ 'data' ] += str ( row ) except KeyError : all_stats_dict ... | Combine all stats for each season . |
34,584 | def _parse_player_information ( self , player_info ) : for field in [ '_height' , '_weight' , '_name' ] : short_field = str ( field ) [ 1 : ] value = utils . _parse_field ( PLAYER_SCHEME , player_info , short_field ) setattr ( self , field , value ) | Parse general player information . |
34,585 | def dataframe ( self ) : temp_index = self . _index rows = [ ] indices = [ ] if not self . _season : return None for season in self . _season : self . _index = self . _season . index ( season ) rows . append ( self . _dataframe_fields ( ) ) indices . append ( season ) self . _index = temp_index return pd . DataFrame ( ... | Returns a pandas DataFrame containing all other relevant class properties and values where each index is a different season plus the career stats . |
34,586 | def _find_year_for_season ( league ) : today = _todays_date ( ) if league not in SEASON_START_MONTH : raise ValueError ( '"%s" league cannot be found!' ) start = SEASON_START_MONTH [ league ] [ 'start' ] wrap = SEASON_START_MONTH [ league ] [ 'wrap' ] if wrap and start - 1 <= today . month <= 12 : return today . year +... | Return the necessary seaons s year based on the current date . |
34,587 | def _parse_abbreviation ( uri_link ) : abbr = re . sub ( r'/[0-9]+\..*htm.*' , '' , uri_link ( 'a' ) . attr ( 'href' ) ) abbr = re . sub ( r'/.*/schools/' , '' , abbr ) abbr = re . sub ( r'/teams/' , '' , abbr ) return abbr . upper ( ) | Returns a team s abbreviation . |
34,588 | def _parse_field ( parsing_scheme , html_data , field , index = 0 ) : if field == 'abbreviation' : return _parse_abbreviation ( html_data ) scheme = parsing_scheme [ field ] items = [ i . text ( ) for i in html_data ( scheme ) . items ( ) ] if len ( items ) == 0 : return None try : return items [ index ] except IndexEr... | Parse an HTML table to find the requested field s value . |
34,589 | def _get_stats_table ( html_page , div , footer = False ) : stats_html = html_page ( div ) try : stats_table = pq ( _remove_html_comment_tags ( stats_html ) ) except ( ParserError , XMLSyntaxError ) : return None if footer : teams_list = stats_table ( 'tfoot tr' ) . items ( ) else : teams_list = stats_table ( 'tbody tr... | Returns a generator of all rows in a requested table . |
34,590 | def dataframes ( self ) : frames = [ ] for team in self . __iter__ ( ) : frames . append ( team . dataframe ) return pd . concat ( frames ) | Returns a pandas DataFrame where each row is a representation of the Team class . Rows are indexed by the team abbreviation . |
34,591 | def _get_team ( self , team ) : name_tag = team ( 'td[data-stat="school_name"]' ) abbreviation = re . sub ( r'.*/cfb/schools/' , '' , str ( name_tag ( 'a' ) ) ) abbreviation = re . sub ( r'/.*' , '' , abbreviation ) name = team ( 'td[data-stat="school_name"] a' ) . text ( ) return abbreviation , name | Retrieve team s name and abbreviation . |
34,592 | def _find_rankings ( self , year ) : if not year : year = utils . _find_year_for_season ( 'ncaaf' ) page = self . _pull_rankings_page ( year ) if not page : output = ( "Can't pull rankings page. Ensure the following URL " "exists: %s" % RANKINGS_URL ) raise ValueError ( output ) rankings = page ( 'table#ap tbody tr' ) ... | Retrieve the rankings for each week . |
34,593 | def current ( self ) : rankings_dict = { } for team in self . current_extended : rankings_dict [ team [ 'abbreviation' ] ] = team [ 'rank' ] return rankings_dict | Returns a dictionary of the most recent rankings from the Associated Press where each key is a string of the team s abbreviation and each value is an int of the team s rank for the current week . |
34,594 | def _retrieve_html_page ( self , uri ) : url = BOXSCORE_URL % uri try : url_data = pq ( url ) except HTTPError : return None if '404 error' in str ( url_data ) : return None return pq ( utils . _remove_html_comment_tags ( url_data ) ) | Download the requested HTML page . |
34,595 | def dataframe ( self ) : if self . _away_points is None and self . _home_points is None : return None fields_to_include = { 'attendance' : self . attendance , 'away_first_downs' : self . away_first_downs , 'away_fourth_down_attempts' : self . away_fourth_down_attempts , 'away_fourth_down_conversions' : self . away_four... | Returns a pandas DataFrame containing all other class properties and values . The index for the DataFrame is the string URI that is used to instantiate the class such as 201802040nwe . |
34,596 | def away_abbreviation ( self ) : abbr = re . sub ( r'.*/teams/' , '' , str ( self . _away_name ) ) abbr = re . sub ( r'/.*' , '' , abbr ) return abbr | Returns a string of the away team s abbreviation such as NWE . |
34,597 | def home_abbreviation ( self ) : abbr = re . sub ( r'.*/teams/' , '' , str ( self . _home_name ) ) abbr = re . sub ( r'/.*' , '' , abbr ) return abbr | Returns a string of the home team s abbreviation such as KAN . |
34,598 | def _find_games ( self , week , year , end_week ) : if not end_week or week > end_week : end_week = week while week <= end_week : url = self . _create_url ( week , year ) page = self . _get_requested_page ( url ) games = page ( 'table[class="teams"]' ) . items ( ) boxscores = self . _extract_game_info ( games ) timesta... | Retrieve all major games played for a given week . |
34,599 | def result ( self ) : if self . _result . lower ( ) == 'w' : return WIN if self . _result . lower ( ) == 'l' and self . overtime != 0 : return OVERTIME_LOSS return LOSS | Returns a string constant to indicate whether the team lost in regulation lost in overtime or won . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.