idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
17,400
def epp_namespace ( node , name = nil , namespaces = { } ) return namespaces [ 'epp' ] if namespaces . has_key? ( 'epp' ) xml_namespace ( node , name , 'urn:ietf:params:xml:ns:epp-1.0' ) end
Creates and returns an instance of the EPP 1 . 0 namespace
17,401
def epp_node ( name , value = nil , namespaces = { } ) value , namespaces = nil , value if value . kind_of? ( Hash ) node = xml_node ( name , value ) node . namespaces . namespace = epp_namespace ( node , nil , namespaces ) node end
Creates and returns a new node in the EPP 1 . 0 namespace
17,402
def xml_namespace ( node , name , uri , namespaces = { } ) XML :: Namespace . new ( node , name , uri ) end
Creates and returns a new XML namespace
17,403
def xml_document ( obj ) case obj when XML :: Document XML :: Document . document ( obj ) else XML :: Document . new ( '1.0' ) end end
Creates and returns a new XML document
17,404
def method_missing ( method_name , * arguments ) klass = REGISTRY . fetch ( method_name ) { super } Evaluator . new ( klass , arguments ) . rules . each do | rule | add ( rule ) end self end
Hook called when method is missing
17,405
def execute ( args = [ ] , ** options ) execute_internal ( args , options ) Executor :: ExitCode . code ( :success ) rescue Cliqr :: Error :: CliqrError => e puts e . message Executor :: ExitCode . code ( e ) end
Execute a command
17,406
def execute_internal ( args = [ ] , ** options ) options = { output : :default , environment : :cli } . merge ( options ) @runner . execute ( args , options ) end
Executes a command without handling error conditions
17,407
def build raise Cliqr :: Error :: ConfigNotFound , 'a valid config should be defined' if @config . nil? unless @config . valid? raise Cliqr :: Error :: ValidationError , "invalid Cliqr interface configuration - [#{@config.errors}]" end Interface . new ( @config ) end
Start building a command line interface
17,408
def execute ( argv , filename = 'Runfile' ) @ignore_settings = ! filename argv = expand_shortcuts argv filename and File . file? ( filename ) or handle_no_runfile argv begin load settings . helper if settings . helper load filename rescue => ex abort "Runfile error:\n#{ex.message}\n#{ex.backtrace[0]}" end run ( * argv ...
Initialize all variables to sensible defaults . Load and execute a Runfile call .
17,409
def add_action ( name , altname = nil , & block ) if @last_usage . nil? @last_usage = altname ? "(#{name}|#{altname})" : name end [ @namespace , @superspace ] . each do | prefix | prefix or next name = "#{prefix}_#{name}" @last_usage = "#{prefix} #{last_usage}" unless @last_usage == false end name = name . to_sym @acti...
Add an action to the
17,410
def add_option ( flag , text , scope = nil ) scope or scope = 'Options' @options [ scope ] ||= { } @options [ scope ] [ flag ] = text end
Add an option flag and its help text .
17,411
def add_param ( name , text , scope = nil ) scope or scope = 'Parameters' @params [ scope ] ||= { } @params [ scope ] [ name ] = text end
Add a patameter and its help text .
17,412
def run ( * argv ) begin docopt_exec argv rescue Docopt :: Exit => ex puts ex . message exit 2 end end
Run the command . This is a wrapper around docopt . It will generate the docopt document on the fly using all the information collected so far .
17,413
def load_remote_errors ( remote_errors , save_cache = false ) if self . class . format == ActiveResource :: Formats :: JsonAPIFormat errors . from_json_api ( remote_errors . response . body , save_cache ) elsif self . class . format == ActiveResource :: Formats [ :json ] super end end
Loads the set of remote errors into the object s Errors based on the content - type of the error - block received .
17,414
def find_from_slug_path ( path ) slug = path . split ( '/' ) . last scope = path [ 0 .. ( - ( slug . size + 1 ) ) ] find_from_slug slug , scope end
Locates a record from a given path that consists of a slug and its scope as would appear in a URL path component .
17,415
def sync serialized_commands = @commands . map { | c | Protocol . build_command ( * c ) } connection . socket . write ( serialized_commands . join ) Array . new ( @commands . size ) { connection . read_response } ensure @commands . clear end
Sends all commands at once and reads responses
17,416
def get_source_path ( path , type ) default_convention_path = convention_path ( @stack_name , type ) return default_convention_path if path . nil? convention_path ( path , type ) end
if existing in params path then use that if it doesnt assume it is a full path and check that else fall back to convention which also eventually gets checked in check_for_errors
17,417
def detect_format formats = Dir . glob ( "#{@project_root}/output/**/*" ) . map { | path | path } . reject { | s | s =~ %r{ } } . map { | path | File . extname ( path ) } . reject { | s | s . empty? } . uniq if formats . size > 1 puts "ERROR: Detected multiple formats: #{formats.join(", ")}" . colorize ( :red ) puts "A...
Returns String with value of yml or json .
17,418
def page ( page_number = nil ) fail ArgumentError , "You must supply a page number." unless page_number . present? fail ArgumentError , "Page number cannot be less than 1." if page_number . to_i < 1 fail ArgumentError , "Page number cannot be greater than the last page number." if page_number . to_i > last_page_number ...
Returns the + page_number + page of data .
17,419
def make_runfile ( name = nil ) name = 'Runfile' if name . nil? template = File . expand_path ( "../templates/Runfile" , __FILE__ ) name += ".runfile" unless name == 'Runfile' dest = "#{Dir.pwd}/#{name}" begin File . write ( dest , File . read ( template ) ) puts "#{name} created." rescue => e abort "Failed creating #{...
Create a new runfile in the current directory . We can either create a standard Runfile or a named . runfile .
17,420
def show_make_help ( runfiles , compact = false ) say "!txtpur!Runfile engine v#{Runfile::VERSION}" unless compact if runfiles . size < 3 and ! compact say "\nTip: Type '!txtblu!run new!txtrst!' or '!txtblu!run new name!txtrst!' to create a runfile.\nFor global access, place !txtblu!named.runfiles!txtrst! in ~/runfile/...
Show some helpful tips and a list of available runfiles
17,421
def say_runfile_list ( runfiles ) runfile_paths = runfiles . map { | f | File . dirname f } max = runfile_paths . max_by ( & :length ) . size width = detect_terminal_size [ 0 ] runfiles . each do | f | f [ / \/ / ] command = "run #{$1}" spacer_size = width - max - command . size - 6 spacer_size = [ 1 , spacer_size ] . ...
Output the list of available runfiles
17,422
def say_runfile_usage ( runfiles ) runfiles_as_columns = get_runfiles_as_columns runfiles say "#{settings.intro}\n" if settings . intro say "Usage: run <file>" say runfiles_as_columns show_shortcuts if settings . shortcuts end
Output the list of available runfiles without filename
17,423
def show_shortcuts say "\nShortcuts:" max = settings . shortcuts . keys . max_by ( & :length ) . length settings . shortcuts . each_pair do | shortcut , command | say " #{shortcut.rjust max} : #{command}" end end
Prints a friendly output of the shortcut list
17,424
def get_runfiles_as_columns ( runfiles ) namelist = runfile_names runfiles width = detect_terminal_size [ 0 ] max = namelist . max_by ( & :length ) . length message = " " + namelist . map { | f | f . ljust max + 1 } . join ( ' ' ) word_wrap message , width end
Returns the list of runfiles organized as columns based on the current terminal width
17,425
def serializable_hash ( * ) h = attributes . extract! ( 'included' ) h [ 'data' ] = { 'type' => self . class . to_s . underscore . sub ( 'esp/' , '' ) . pluralize , 'attributes' => changed_attributes . except ( 'id' , 'type' , 'created_at' , 'updated_at' , 'relationships' ) } h [ 'data' ] [ 'id' ] = id if id . present?...
Pass a json api compliant hash to the api .
17,426
def with conn = @pool . checkout session = Session . new ( conn ) yield ( session ) ensure if conn session . discard if conn . in_transaction? @pool . checkin end end
Initialize connection pool
17,427
def docopt_usage doc = [ "\nUsage:" ] ; @actions . each do | _name , action | doc << " run #{action.usage}" unless action . usage == false end basic_flags = @version ? "(-h|--help|--version)" : "(-h|--help)" if @superspace doc << " run #{@superspace} #{basic_flags}\n" else doc << " run #{basic_flags}\n" end doc end
Return all docopt lines for the Usage section
17,428
def docopt_commands ( width ) doc = [ ] caption_printed = false @actions . each do | _name , action | action . help or next doc << "Commands:" unless caption_printed caption_printed = true helpline = " #{action.help}" wrapped = word_wrap helpline , width doc << " #{action.usage}\n#{wrapped}\n" unless action . usa...
Return all docopt lines for the Commands section
17,429
def docopt_examples ( width ) return [ ] if @examples . empty? doc = [ "Examples:" ] base_command = @superspace ? "run #{@superspace}" : "run" @examples . each do | command | helpline = " #{base_command} #{command}" wrapped = word_wrap helpline , width doc << "#{wrapped}" end doc end
Return all docopt lines for the Examples section
17,430
def hint ( hint_text , options = { } ) css_class = "hint #{options.delete(:class)}" content_tag ( :p , content_tag ( :span , hint_text . chomp ) , class : css_class , ** options ) end
Returns a p . hint used to explain a nearby form field containing the given hint_text .
17,431
def image_association_select ( method , collection , value_method , text_method , preview_url_method , options = { } ) render ( partial : "admin/shared/forms/image_association_select" , locals : { f : self , method : method , collection : collection , value_method : value_method , text_method : text_method , preview_ur...
Creates a searchable_select that also shows a dynamic image preview of the selected record . Useful for previewing images or avatars chosen by name . preview_url_method should be a method name to call on the associated model instance that returns a fully - qualified URL to the image preview .
17,432
def markdown_composer ( method , options = { } ) render ( partial : "admin/shared/forms/markdown_composer" , locals : { f : self , method : method , options : options , } ) end
Renders a Markdown composer element for editing method with fullscreen previewing and some text assistance tools . Requires that you set Tolaria . config . markdown_renderer . Options are forwarded to text_area .
17,433
def attachment_field ( method , options = { } ) render ( partial : "admin/shared/forms/attachment_field" , locals : { f : self , method : method , options : options , } ) end
Returns a file upload field with a more pleasant interface than browser file inputs . Changes messaging if the method already exists . Options are forwarded to the hidden file_field .
17,434
def image_field ( method , options = { } ) render ( partial : "admin/shared/forms/image_field" , locals : { f : self , method : method , options : options , preview_url : options [ :preview_url ] } ) end
Returns an image upload field with a more pleasant interface than browser file inputs . Changes messaging if the method already exists .
17,435
def timestamp_field ( method , options = { } ) render ( partial : "admin/shared/forms/timestamp_field" , locals : { f : self , method : method , options : options , } ) end
Returns a text field that allows the user to input a date and time . Automatically validates itself and recovers to a template if blanked out . This field uses moment . js to parse the date and set the values on a set of hidden Rails datetime_select fields . Options are forwarded to the hidden datetime_select group .
17,436
def slug_field ( method , options = { } ) pattern = options . delete ( :pattern ) preview_value = self . object . send ( method ) . try ( :parameterize ) . presence || "*" render ( partial : "admin/shared/forms/slug_field" , locals : { f : self , method : method , options : options , preview_value : preview_value , pat...
Returns a text field that parameterizes its input as users type and renders it into the given preview template . Useful for demonstrating the value of a URL or other sluggified text .
17,437
def swatch_field ( method , options = { } ) render ( partial : "admin/shared/forms/swatch_field" , locals : { f : self , method : method , options : options , } ) end
Returns a text field that expects to be given a 3 or 6 - digit hexadecimal color value . A preview block near the field demonstrates the provided color to the user . Options are forwarded to text_field .
17,438
def gets ( separator , timeout = @timeout ) while ( crlf = @buffer . index ( separator ) ) . nil? @buffer << readpartial ( 1024 , timeout ) end @buffer . slice! ( 0 , crlf + separator . bytesize ) end
Read until separator
17,439
def write ( data , timeout = @timeout ) full_size = data . bytesize while data . bytesize > 0 written = socket . write_nonblock ( data , exception : false ) if written == :wait_writable socket . wait_writable ( timeout ) or fail_with_timeout! else data = data . byteslice ( written .. - 1 ) end end full_size end
Write data to socket
17,440
def instance_action_module @instance_action_module ||= Module . new do def client ( & block ) self . class . client ( & block ) end private def merged_default_body ( body = { } ) default = self . respond_to? ( :default_body ) ? self . default_body : nil ( default || { } ) . merge ( body || { } ) end end . tap { | mod |...
Instance methods .
17,441
def violations validator . rules . each_with_object ( Set . new ) do | rule , violations | violations . merge ( rule . violations ( resource ) ) end end
Return violations for resource
17,442
def run ( signals = Signal . list . keys ) if mounted? begin traps = trap_signals ( * signals ) self . loop ( ) ensure traps . each { | t | Signal . trap ( t , "DEFAULT" ) } unmount ( ) end end end
Convenience method to run a mounted filesystem to completion .
17,443
def loop ( ) raise RFuse :: Error , "Already running!" if @running raise RFuse :: Error , "FUSE not mounted" unless mounted? @running = true while @running do begin ready , ignore , errors = IO . select ( [ @fuse_io , @pr ] , [ ] , [ @fuse_io ] ) if ready . include? ( @pr ) signo = @pr . read_nonblock ( 1 ) . unpack ( ...
Main processing loop
17,444
def debug = ( value ) value = value ? true : false if @debug && ! value $stderr . puts "=== #{ self }.debug=false" elsif ! @debug && value $stderr . puts "=== #{ self }.debug=true" end @debug = value end
Set debugging on or off
17,445
def dom_changed? ( delay : 1.1 ) element_call do begin driver . manage . timeouts . script_timeout = delay + 1 driver . execute_async_script ( DOM_WAIT_JS , wd , delay ) rescue Selenium :: WebDriver :: Error :: JavascriptError => error retry if error . message . include? ( 'document unloaded while waiting for result' )...
Returns true if DOM is changed within the element .
17,446
def run! ( arguments = { } ) result = run ( arguments ) return result if result . is_a? ( ActiveResource :: Collection ) result . message = result . errors . full_messages . join ( ' ' ) fail ( ActiveResource :: ResourceInvalid . new ( result ) ) end
Run this signature . Returns a collection of alerts . Throws an error if not successful .
17,447
def run ( arguments = { } ) arguments = arguments . with_indifferent_access attributes [ 'external_account_id' ] ||= arguments [ :external_account_id ] attributes [ 'region' ] ||= arguments [ :region ] response = connection . post ( "#{self.class.prefix}signatures/#{id}/run.json" , to_json ) ESP :: Alert . send ( :inst...
Run this signature . Returns a collection of alerts . If not successful returns a Signature object with the errors object populated .
17,448
def suppress ( arguments = { } ) arguments = arguments . with_indifferent_access ESP :: Suppression :: Signature . create ( signature_ids : [ id ] , regions : Array ( arguments [ :regions ] ) , external_account_ids : Array ( arguments [ :external_account_ids ] ) , reason : arguments [ :reason ] ) end
Create a suppression for this signature .
17,449
def csv_data case when google_key || url then Curl :: Easy . perform ( uri ) . body_str when file then File . open ( uri ) . read end end
The csv_data for the table fu instance is loaded either from the remote source or from a local file depending on the keys present in the yaml file .
17,450
def updated_at csv_time = google_key . nil? ? modification_time ( uri ) : google_modification_time ( csv_time > yaml_time ? csv_time : yaml_time ) . to_s end
The real + updated_at + of a Table instance is the newer modification time of the csv file or the yaml file . Updates to either resource should break the cache .
17,451
def paginate! ( curr_page ) return if ! hard_paginate? @page = curr_page . to_i raise ArgumentError if @page < 1 || @page > total_pages adj_page = @page - 1 > 0 ? @page - 1 : 0 @prev_page = adj_page > 0 ? adj_page : nil @next_page = page < total_pages ? ( @page + 1 ) : nil @data . only! ( adj_page * per_page .. ( @page...
paginate uses TableFu s only! method to batch the table . It also computes the page attributes which are nil and meaningless otherwise .
17,452
def sort_array if @data . sorted_by @data . sorted_by . inject ( [ ] ) do | memo , ( key , value ) | memo << [ @data . columns . index ( key ) , value == 'descending' ? 1 : 0 ] end end end
A convienence method to return the sort array for table setter .
17,453
def web_modification_time ( local_url ) resp = nil Net :: HTTP . start ( local_url . host , 80 ) do | http | resp = http . head ( local_url . path ) end resp [ 'Last-Modified' ] . nil? ? Time . at ( 0 ) : Time . parse ( resp [ 'Last-Modified' ] ) end
Returns the last - modified time from the remote server . Assumes the remote server knows how to do this . Returns the epoch if the remote is dense .
17,454
def modification_time ( path ) is_uri = URI . parse ( path ) if ! is_uri . host . nil? return web_modification_time is_uri end File . new ( path ) . mtime end
Dispatches to web_modification_time if we re dealing with a url otherwise just stats the local file .
17,455
def to_xml doc = XML :: Document . new ( '1.0' ) doc . root = XML :: Node . new ( 'epp' ) root = doc . root epp_ns = XML :: Namespace . new ( root , nil , 'urn:ietf:params:xml:ns:epp-1.0' ) root . namespaces . namespace = epp_ns xsi_ns = XML :: Namespace . new ( root , 'xsi' , 'http://www.w3.org/2001/XMLSchema-instance...
Receiver in XML form
17,456
def extension @extension ||= begin list = @xml . find ( '/e:epp/e:response/e:extension/node()' ) . reject { | n | n . empty? } list . size > 1 ? list : list [ 0 ] end end
Response extension block
17,457
def render ( context ) site = context . registers [ :site ] converter = site . getConverterImpl ( :: Jekyll :: Converters :: Markdown ) converter . convert ( render_block ( context ) ) end
Uses the default Jekyll markdown parser to parse the contents of this block
17,458
def watch_socket_for_read ( fd , low_water = nil , & callback ) Watcher :: SocketReadWrite . new ( self , fd , :read , low_water , callback ) end
Watches a socket and produces an event when there s data available to read .
17,459
def watch_file ( path , * flags , & callback ) Watcher :: File . new ( self , path , flags , callback ) end
Watches a file or directory for changes . The flags parameter specifies which changes will fire events .
17,460
def watch_process ( pid , * flags , & callback ) Watcher :: Process . new ( self , pid , flags , callback ) end
Watches a process for changes . The flags parameter specifies which changes will fire events .
17,461
def common_team_roster ( team_id , season , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: CommonTeamRoster . new ( get ( COMMON_TEAM_ROSTER_PATH , { :Season => season , :LeagueID => league_id , :TeamID => team_id } ) ) end
Calls the commonteamroster API and returns a CommonTeamRoster resource .
17,462
def build_name ( * args ) args . extend ( DeepFlattening ) args = args . deep_flatten name = args . shift . to_s name + args . map { | piece | "[#{piece}]" } . join end
Converts an array or hash of names to a name for an input form .
17,463
def box_score_advanced ( game_id , range_type = 0 , start_period = 0 , end_period = 0 , start_range = 0 , end_range = 0 ) NbaStats :: Resources :: BoxScoreAdvanced . new ( get ( BOX_SCORE_ADVANCED_PATH , { :GameID => game_id , :RangeType => range_type , :StartPeriod => start_period , :EndPeriod => end_period , :StartRa...
Calls the boxscoreadvanced API and returns a BoxScoreAdvanced resource .
17,464
def common_all_players ( season , is_only_current_season = 0 , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: CommonAllPlayers . new ( get ( COMMON_ALL_PLAYERS_PATH , { :LeagueID => league_id , :Season => season , :IsOnlyCurrentSeason => is_only_current_season } ) ) end
Calls the commonallplayers API and returns a CommonAllPlayers resource .
17,465
def team_info_common ( team_id , season , season_type = NbaStats :: Constants :: SEASON_TYPE_REGULAR , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: TeamInfoCommon . new ( get ( TEAM_INFO_COMMON_PATH , { :Season => season , :SeasonType => season_type , :LeagueID => league_id , :TeamID =>...
Calls the teaminfocommon API and returns a TeamInfoCommon resource .
17,466
def team_year_by_year_stats ( team_id , season , per_mode = NbaStats :: Constants :: PER_MODE_TOTALS , season_type = NbaStats :: Constants :: SEASON_TYPE_REGULAR , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: TeamYearByYearStats . new ( get ( TEAM_YEAR_BY_YEAR_STATS_PATH , { :LeagueID =...
Calls the teamyearbyyearstats API and returns a TeamYearByYearStats resource .
17,467
def box_score_usage ( game_id , range_type = 0 , start_period = 0 , end_period = 0 , start_range = 0 , end_range = 0 ) NbaStats :: Resources :: BoxScoreUsage . new ( get ( BOX_SCORE_USAGE_PATH , { :GameID => game_id , :RangeType => range_type , :StartPeriod => start_period , :EndPeriod => end_period , :StartRange => st...
Calls the boxscoreusage API and returns a BoxScoreUsage resource .
17,468
def draft_combine_player_anthro ( season_year , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: DraftCombinePlayerAnthro . new ( get ( DRAFT_COMBINE_PLAYER_ANTHRO_PATH , { :LeagueID => league_id , :SeasonYear => season_year } ) ) end
Calls the draftcombineplayeranthro API and returns a DraftCombinePlayerAnthro resource .
17,469
def available return @available if defined? ( @available ) @available = [ ] load_available_specs . each do | spec | if prev = @available . find { | w | w . name == spec . name } if prev . version < spec . version @available . delete ( prev ) @available << spec end else @available << spec end end @available end
Most recent gem specifications of all wagons available in GEM_HOME .
17,470
def wagonfile_update ( specs ) wagonfile_edit ( specs ) do | spec , content | declaration = "gem '#{spec.name}'" declaration += ", '#{spec.version}'" if include_version_in_wagonfile unless content . sub! ( gem_declaration_regexp ( spec . name ) , declaration ) content += "\n#{declaration}" end content end end
Update the Wagonfile with the given gem specifications .
17,471
def wagonfile_remove ( specs ) wagonfile_edit ( specs ) do | spec , content | content . sub ( gem_declaration_regexp ( spec . name ) , '' ) end end
Remove the given gem specifications from the Wagonfile .
17,472
def check_dependencies ( specs ) missing = check_app_requirement ( specs ) present = exclude_specs ( installed , specs ) future = present + specs check_all_dependencies ( specs , future , missing ) end
Check if all wagon dependencies of the given gem specifications are met by the installed wagons . Returns nil if everything is fine or a string with error messages .
17,473
def check_app_requirement ( specs ) missing = [ ] specs . each do | spec | if wagon = wagon_class ( spec ) unless wagon . app_requirement . satisfied_by? ( Wagons . app_version ) missing << "#{spec} requires application version #{wagon.app_requirement}" end end end missing end
Check if the app requirement of the given gem specifications are met by the current app version . Returns nil if everything is fine or a array with error messages .
17,474
def check_protected ( specs ) protected = [ ] specs . each do | spec | msg = Wagons . find ( spec . name ) . protect? protected << msg if msg . is_a? ( String ) end protected . join ( "\n" ) . presence end
Checks if the wagons for given gem specifications are protected . Returns nil if everything is fine or a string with error messages .
17,475
def specs_from_names ( names ) names . map do | name | spec = available_spec ( name ) fail "#{name} was not found" if spec . nil? spec end end
List of available gem specifications with the given names . Raises an error if a name cannot be found .
17,476
def exclude_specs ( full , to_be_excluded ) full . clone . delete_if { | s | to_be_excluded . find { | d | s . name == d . name } } end
Removes all gem specifications with the same name in to_be_excluded from full . Versions are ignored .
17,477
def wagon_class ( spec ) @wagon_classes ||= { } return @wagon_classes [ spec ] if @wagon_classes . key? ( spec ) clazz = nil file = File . join ( spec . gem_dir , 'lib' , spec . name , 'wagon.rb' ) if File . exist? ( file ) require file clazz = "#{spec.name.camelize}::Wagon" . constantize else fail "#{spec.name} wagon ...
The wagon class of the given spec .
17,478
def common_player_info ( player_id , season_type = NbaStats :: Constants :: SEASON_TYPE_REGULAR , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: CommonPlayerInfo . new ( get ( COMMON_PLAYER_INFO_PATH , { :PlayerID => player_id , :SeasonType => season_type , :LeagueID => league_id } ) ) en...
Calls the commonplayerinfo API and returns a CommonPlayerInfo resource .
17,479
def franchise_history ( league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: FranchiseHistory . new ( get ( FRANCHISE_HISTORY_PATH , { :LeagueID => league_id } ) ) end
Calls the franchisehistory API and returns a FranchiseHistory resource .
17,480
def league_dash_lineups ( season , group_quantity = 5 , measure_type = NbaStats :: Constants :: MEASURE_TYPE_BASE , per_mode = NbaStats :: Constants :: PER_MODE_GAME , plus_minus = NbaStats :: Constants :: NO , pace_adjust = NbaStats :: Constants :: NO , rank = NbaStats :: Constants :: NO , outcome = '' , location = ''...
Calls the leaguedashlineups API and returns a LeagueDashLineups resource .
17,481
def ordered_railties_with_wagons @ordered_railties ||= ordered_railties_without_wagons . tap do | ordered | flat = Gem :: Version . new ( Rails :: VERSION :: STRING ) < Gem :: Version . new ( '4.1.6' ) Wagons . all . each do | w | if flat ordered . push ( ordered . delete ( w ) ) else ordered . unshift ( array_deep_del...
Append wagons at the end of all railties even after the application .
17,482
def home_page_leaders ( season , game_scope = NbaStats :: Constants :: GAME_SCOPE_SEASON , stat_category = NbaStats :: Constants :: STAT_CATEGORY_POINTS , player_scope = NbaStats :: Constants :: PLAYER_SCOPE_ALL_PLAYERS , player_or_team = NbaStats :: Constants :: PLAYER_OR_TEAM_PLAYER , season_type = NbaStats :: Consta...
Calls the homepageleaders API and returns a HomePageLeaders resource .
17,483
def team_game_log ( team_id , season , season_type = NbaStats :: Constants :: SEASON_TYPE_REGULAR , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: TeamGameLog . new ( get ( TEAM_GAME_LOG_PATH , { :Season => season , :SeasonType => season_type , :LeagueID => league_id , :TeamID => team_id ...
Calls the teamgamelog API and returns a TeamGameLog resource .
17,484
def box_score_scoring ( game_id , range_type = 0 , start_period = 0 , end_period = 0 , start_range = 0 , end_range = 0 ) NbaStats :: Resources :: BoxScoreScoring . new ( get ( BOX_SCORE_SCORING_PATH , { :GameID => game_id , :RangeType => range_type , :StartPeriod => start_period , :EndPeriod => end_period , :StartRange...
Calls the boxscorescoring API and returns a BoxScoreScoring resource .
17,485
def draft_combine_spot_shooting ( season_year , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: DraftCombineSpotShooting . new ( get ( DRAFT_COMBINE_SPOT_SHOOTING_PATH , { :LeagueID => league_id , :SeasonYear => season_year } ) ) end
Calls the draftcombinespotshooting API and returns a DraftCombineSpotShooting resource .
17,486
def common_team_years ( league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: CommonTeamYears . new ( get ( COMMON_TEAM_YEARS_PATH , { :LeagueID => league_id } ) ) end
Calls the commonteamyears API and returns a CommonTeamYears resource .
17,487
def request ( method , path , params = { } , & block ) connection . send ( method , path , params , & block ) rescue Faraday :: Error :: ClientError => err raise DeskApi :: Error :: ClientError . new ( err ) rescue JSON :: ParserError => err raise DeskApi :: Error :: ParserError . new ( err ) end
Hands off the request to Faraday for further processing
17,488
def shot_chart_detail ( season , team_id , player_id , game_id = nil , outcome = nil , location = nil , month = 0 , season_segment = nil , date_from = nil , date_to = nil , opponent_team_id = 0 , vs_conference = nil , vs_division = nil , position = nil , rookie_year = nil , game_segment = nil , period = 0 , last_n_game...
Calls the shotchartdetail API and returns a ShotChartDetail resource .
17,489
def middleware @middleware ||= proc do | builder | builder . request ( :desk_encode_dates ) builder . request ( :desk_encode_json ) builder . request ( * authorize_request ) builder . request ( :desk_retry ) builder . response ( :desk_parse_dates ) builder . response ( :desk_follow_redirects ) builder . response ( :des...
Returns the middleware proc to be used by Faraday
17,490
def reset! DeskApi :: Configuration . keys . each do | key | send ( "#{key}=" , DeskApi :: Default . options [ key ] ) end self end
Resets the client to the default settings .
17,491
def validate_credentials! fail ( DeskApi :: Error :: ConfigurationError , 'Invalid credentials: ' 'Either username/password or OAuth credentials must be specified.' ) unless credentials? validate_oauth! if oauth . values . all? validate_basic_auth! if basic_auth . values . all? end
Raises an error if credentials are not set or of the wrong type .
17,492
def pivot ( args = { } ) args = { column : nil , row : nil , value : nil , fill_value : Float :: NAN } . merge ( args ) raise ArgumentError unless [ :column , :row , :value ] . all? { | sym | args [ sym ] . is_a? ( Symbol ) } column = self [ args [ :column ] ] . factors index = self [ args [ :row ] ] . factors source =...
Experimental Implementation . DO NOT USE THIS METHOD
17,493
def translate_keyword_tokens ( token ) keywords = [ "__LINE__" , "__ENCODING__" , "__FILE__" , "BEGIN" , "END" , "alias" , "and" , "begin" , "break" , "case" , "class" , "def" , "defined?" , "do" , "else" , "elsif" , "end" , "ensure" , "false" , "for" , "if" , "in" , "module" , "next" , "nil" , "not" , "or" , "redo" , ...
Takes an identifier token and tranforms its type to match Ruby keywords where the identifier is actually a keyword . Reserved words are defined in S . 8 . 5 . 1 of the Ruby spec .
17,494
def get ( path = '/' , params = { } ) uri = Addressable :: URI . new uri . query_values = params full_path = "#{path}?#{uri.query.gsub(/%20/,'+')}" request ( :get , full_path ) end
Perform a HTTP GET request
17,495
def request ( method , path ) resource [ path ] . send ( method . to_sym , request_headers ) { | response , request , result , & block | case response . code when 200 response when 400 if response . include? ' is required' raise ArgumentError . new ( response ) else raise BadRequestError . new ( response ) end else res...
Send the HTTP request
17,496
def draft_combine_stats ( season_year , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA ) NbaStats :: Resources :: DraftCombineStats . new ( get ( DRAFT_COMBINE_STATS_PATH , { :LeagueID => league_id , :SeasonYear => season_year } ) ) end
Calls the draftcombinestats API and returns a DraftCombineStats resource .
17,497
def player_dashboard_by_general_splits ( season , player_id , date_from = nil , date_to = nil , game_segment = nil , last_n_games = 0 , league_id = NbaStats :: Constants :: LEAGUE_ID_NBA , location = nil , measure_type = NbaStats :: Constants :: MEASURE_TYPE_USAGE , month = 0 , opponent_team_id = 0 , outcome = nil , pa...
Calls the playerdashboardbygeneralsplits API and returns a PlayerDashboardByGeneralSplits resource .
17,498
def make_sentence ( * strings ) options = strings . last . is_a? ( Hash ) ? strings . pop : { } strings = strings . flatten . map ( & :to_s ) . reject ( & :empty? ) conjunction = options [ :conjunction ] || "and" case strings . count when 0 "" when 1 strings . first else last = strings . pop puncuation = strings . coun...
Joins multiple strings into a sentence with punctuation and conjunctions .
17,499
def method_missing ( method , * args , & block ) return super unless delegatable? ( method ) self . class . delegate method send ( method , * args , & block ) end
Delegates missing instance methods to the source object .