idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
48,100 | def get_pull_request_files ( project , num , auth = False ) : url = "https://api.github.com/repos/{project}/pulls/{num}/files" . format ( project = project , num = num ) if auth : header = make_auth_header ( ) else : header = None return get_paged_request ( url , headers = header ) | get list of files in a pull request |
48,101 | def get_paged_request ( url , headers = None , ** params ) : results = [ ] params . setdefault ( "per_page" , 100 ) while True : if '?' in url : params = None print ( "fetching %s" % url , file = sys . stderr ) else : print ( "fetching %s with %s" % ( url , params ) , file = sys . stderr ) response = requests . get ( u... | get a full list handling APIv3 s paging |
48,102 | def get_pulls_list ( project , auth = False , ** params ) : params . setdefault ( "state" , "closed" ) url = "https://api.github.com/repos/{project}/pulls" . format ( project = project ) if auth : headers = make_auth_header ( ) else : headers = None pages = get_paged_request ( url , headers = headers , ** params ) retu... | get pull request list |
48,103 | def post_download ( project , filename , name = None , description = "" ) : if name is None : name = os . path . basename ( filename ) with open ( filename , 'rb' ) as f : filedata = f . read ( ) url = "https://api.github.com/repos/{project}/downloads" . format ( project = project ) payload = json . dumps ( dict ( name... | Upload a file to the GitHub downloads area |
48,104 | def build_matlab ( static = False ) : cfg = get_config ( ) if 'matlab_bin' in cfg and cfg [ 'matlab_bin' ] != '.' : matlab_bin = cfg [ 'matlab_bin' ] . strip ( '"' ) else : matlab_bin = which_matlab ( ) if matlab_bin is None : raise ValueError ( "specify 'matlab_bin' in cfg file" ) extcmd = esc ( os . path . join ( mat... | build the messenger mex for MATLAB |
48,105 | def select ( self , selector ) : if self . closed ( ) : raise ValueError ( "Attempt to call select() on a closed Queryable." ) try : selector = make_selector ( selector ) except ValueError : raise TypeError ( "select() parameter selector={selector} cannot be" "converted into a callable " "selector" . format ( selector ... | Transforms each element of a sequence into a new form . |
48,106 | def select_with_index ( self , selector = IndexedElement , transform = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call select_with_index() on a " "closed Queryable." ) if not is_callable ( selector ) : raise TypeError ( "select_with_index() parameter selector={0} is " "not callable" . format ( r... | Transforms each element of a sequence into a new form incorporating the index of the element . |
48,107 | def select_with_correspondence ( self , selector , result_selector = KeyedElement ) : if self . closed ( ) : raise ValueError ( "Attempt to call select_with_correspondence() on a " "closed Queryable." ) if not is_callable ( selector ) : raise TypeError ( "select_with_correspondence() parameter selector={0} is " "not ca... | Apply a callable to each element in an input sequence generating a new sequence of 2 - tuples where the first element is the input value and the second is the transformed input value . |
48,108 | def select_many ( self , collection_selector = identity , result_selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call select_many() on a closed " "Queryable." ) if not is_callable ( collection_selector ) : raise TypeError ( "select_many() parameter projector={0} is not " "callable" . forma... | Projects each element of a sequence to an intermediate new sequence flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a selector function . |
48,109 | def select_many_with_index ( self , collection_selector = IndexedElement , result_selector = lambda source_element , collection_element : collection_element ) : if self . closed ( ) : raise ValueError ( "Attempt to call select_many_with_index() on a " "closed Queryable." ) if not is_callable ( collection_selector ) : r... | Projects each element of a sequence to an intermediate new sequence incorporating the index of the element flattens the resulting sequence into one sequence and optionally transforms the flattened sequence using a selector function . |
48,110 | def select_many_with_correspondence ( self , collection_selector = identity , result_selector = KeyedElement ) : if self . closed ( ) : raise ValueError ( "Attempt to call " "select_many_with_correspondence() on a closed Queryable." ) if not is_callable ( collection_selector ) : raise TypeError ( "select_many_with_corr... | Projects each element of a sequence to an intermediate new sequence and flattens the resulting sequence into one sequence and uses a selector function to incorporate the corresponding source for each item in the result sequence . |
48,111 | def group_by ( self , key_selector = identity , element_selector = identity , result_selector = lambda key , grouping : grouping ) : if self . closed ( ) : raise ValueError ( "Attempt to call group_by() on a closed " "Queryable." ) if not is_callable ( key_selector ) : raise TypeError ( "group_by() parameter key_select... | Groups the elements according to the value of a key extracted by a selector function . |
48,112 | def where ( self , predicate ) : if self . closed ( ) : raise ValueError ( "Attempt to call where() on a closed Queryable." ) if not is_callable ( predicate ) : raise TypeError ( "where() parameter predicate={predicate} is not " "callable" . format ( predicate = repr ( predicate ) ) ) return self . _create ( ifilter ( ... | Filters elements according to whether they match a predicate . |
48,113 | def of_type ( self , classinfo ) : if self . closed ( ) : raise ValueError ( "Attempt to call of_type() on a closed " "Queryable." ) if not is_type ( classinfo ) : raise TypeError ( "of_type() parameter classinfo={0} is not a class " "object or a type objector a tuple of class or " "type objects." . format ( classinfo ... | Filters elements according to whether they are of a certain type . |
48,114 | def order_by ( self , key_selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call order_by() on a " "closed Queryable." ) if not is_callable ( key_selector ) : raise TypeError ( "order_by() parameter key_selector={key_selector} " "is not callable" . format ( key_selector = repr ( key_selector... | Sorts by a key in ascending order . |
48,115 | def take ( self , count = 1 ) : if self . closed ( ) : raise ValueError ( "Attempt to call take() on a closed Queryable." ) count = max ( 0 , count ) return self . _create ( itertools . islice ( self , count ) ) | Returns a specified number of elements from the start of a sequence . |
48,116 | def take_while ( self , predicate ) : if self . closed ( ) : raise ValueError ( "Attempt to call take_while() on a closed " "Queryable." ) if not is_callable ( predicate ) : raise TypeError ( "take_while() parameter predicate={0} is " "not callable" . format ( repr ( predicate ) ) ) return self . _create ( self . _gene... | Returns elements from the start while the predicate is True . |
48,117 | def skip ( self , count = 1 ) : if self . closed ( ) : raise ValueError ( "Attempt to call skip() on a closed Queryable." ) count = max ( 0 , count ) if count == 0 : return self if hasattr ( self . _iterable , "__getitem__" ) : try : stop = len ( self . _iterable ) return self . _create ( self . _generate_optimized_ski... | Skip the first count contiguous elements of the source sequence . |
48,118 | def skip_while ( self , predicate ) : if self . closed ( ) : raise ValueError ( "Attempt to call take_while() on a " "closed Queryable." ) if not is_callable ( predicate ) : raise TypeError ( "skip_while() parameter predicate={0} is " "not callable" . format ( repr ( predicate ) ) ) return self . _create ( itertools . ... | Omit elements from the start for which a predicate is True . |
48,119 | def concat ( self , second_iterable ) : if self . closed ( ) : raise ValueError ( "Attempt to call concat() on a closed Queryable." ) if not is_iterable ( second_iterable ) : raise TypeError ( "Cannot compute concat() with second_iterable of " "non-iterable {0}" . format ( str ( type ( second_iterable ) ) [ 7 : - 1 ] )... | Concatenates two sequences . |
48,120 | def reverse ( self ) : if self . closed ( ) : raise ValueError ( "Attempt to call reverse() on a " "closed Queryable." ) try : r = reversed ( self . _iterable ) return self . _create ( r ) except TypeError : pass return self . _create ( self . _generate_reverse_result ( ) ) | Returns the sequence reversed . |
48,121 | def element_at ( self , index ) : if self . closed ( ) : raise ValueError ( "Attempt to call element_at() on a " "closed Queryable." ) if index < 0 : raise OutOfRangeError ( "Attempt to use negative index." ) try : return self . _iterable [ index ] except IndexError : raise OutOfRangeError ( "Index out of range." ) exc... | Return the element at ordinal index . |
48,122 | def any ( self , predicate = None ) : if self . closed ( ) : raise ValueError ( "Attempt to call any() on a closed Queryable." ) if predicate is None : predicate = lambda x : True if not is_callable ( predicate ) : raise TypeError ( "any() parameter predicate={predicate} is not callable" . format ( predicate = repr ( p... | Determine if the source sequence contains any elements which satisfy the predicate . |
48,123 | def all ( self , predicate = bool ) : if self . closed ( ) : raise ValueError ( "Attempt to call all() on a closed Queryable." ) if not is_callable ( predicate ) : raise TypeError ( "all() parameter predicate={0} is " "not callable" . format ( repr ( predicate ) ) ) return all ( self . select ( predicate ) ) | Determine if all elements in the source sequence satisfy a condition . |
48,124 | def sum ( self , selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call sum() on a closed Queryable." ) if not is_callable ( selector ) : raise TypeError ( "sum() parameter selector={0} is " "not callable" . format ( repr ( selector ) ) ) return sum ( self . select ( selector ) ) | Return the arithmetic sum of the values in the sequence .. |
48,125 | def average ( self , selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call average() on a " "closed Queryable." ) if not is_callable ( selector ) : raise TypeError ( "average() parameter selector={0} is " "not callable" . format ( repr ( selector ) ) ) total = 0 count = 0 for item in self .... | Return the arithmetic mean of the values in the sequence .. |
48,126 | def contains ( self , value , equality_comparer = operator . eq ) : if self . closed ( ) : raise ValueError ( "Attempt to call contains() on a " "closed Queryable." ) if not is_callable ( equality_comparer ) : raise TypeError ( "contains() parameter equality_comparer={0} is " "not callable" . format ( repr ( equality_c... | Determines whether the sequence contains a particular value . |
48,127 | def default_if_empty ( self , default ) : if self . closed ( ) : raise ValueError ( "Attempt to call default_if_empty() on a " "closed Queryable." ) return self . _create ( self . _generate_default_if_empty_result ( default ) ) | If the source sequence is empty return a single element sequence containing the supplied default value otherwise return the source sequence unchanged . |
48,128 | def distinct ( self , selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call distinct() on a " "closed Queryable." ) if not is_callable ( selector ) : raise TypeError ( "distinct() parameter selector={0} is " "not callable" . format ( repr ( selector ) ) ) return self . _create ( self . _gen... | Eliminate duplicate elements from a sequence . |
48,129 | def difference ( self , second_iterable , selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call difference() on a " "closed Queryable." ) if not is_iterable ( second_iterable ) : raise TypeError ( "Cannot compute difference() with second_iterable" "of non-iterable {0}" . format ( str ( type... | Returns those elements which are in the source sequence which are not in the second_iterable . |
48,130 | def intersect ( self , second_iterable , selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call intersect() on a " "closed Queryable." ) if not is_iterable ( second_iterable ) : raise TypeError ( "Cannot compute intersect() with second_iterable " "of non-iterable {0}" . format ( str ( type (... | Returns those elements which are both in the source sequence and in the second_iterable . |
48,131 | def union ( self , second_iterable , selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call union() on a closed Queryable." ) if not is_iterable ( second_iterable ) : raise TypeError ( "Cannot compute union() with second_iterable of " "non-iterable {0}" . format ( str ( type ( second_iterabl... | Returns those elements which are either in the source sequence or in the second_iterable or in both . |
48,132 | def join ( self , inner_iterable , outer_key_selector = identity , inner_key_selector = identity , result_selector = lambda outer , inner : ( outer , inner ) ) : if self . closed ( ) : raise ValueError ( "Attempt to call join() on a closed Queryable." ) if not is_iterable ( inner_iterable ) : raise TypeError ( "Cannot ... | Perform an inner join with a second sequence using selected keys . |
48,133 | def group_join ( self , inner_iterable , outer_key_selector = identity , inner_key_selector = identity , result_selector = lambda outer , grouping : grouping ) : if self . closed ( ) : raise ValueError ( "Attempt to call group_join() on a closed Queryable." ) if not is_iterable ( inner_iterable ) : raise TypeError ( "C... | Match elements of two sequences using keys and group the results . |
48,134 | def aggregate ( self , reducer , seed = default , result_selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call aggregate() on a " "closed Queryable." ) if not is_callable ( reducer ) : raise TypeError ( "aggregate() parameter reducer={0} is " "not callable" . format ( repr ( reducer ) ) ) i... | Apply a function over a sequence to produce a single result . |
48,135 | def zip ( self , second_iterable , result_selector = lambda x , y : ( x , y ) ) : if self . closed ( ) : raise ValueError ( "Attempt to call zip() on a closed Queryable." ) if not is_iterable ( second_iterable ) : raise TypeError ( "Cannot compute zip() with second_iterable of " "non-iterable {0}" . format ( str ( type... | Elementwise combination of two sequences . |
48,136 | def to_list ( self ) : if self . closed ( ) : raise ValueError ( "Attempt to call to_list() on a closed Queryable." ) if isinstance ( self . _iterable , list ) : return self . _iterable lst = list ( self ) return lst | Convert the source sequence to a list . |
48,137 | def to_tuple ( self ) : if self . closed ( ) : raise ValueError ( "Attempt to call to_tuple() on a closed Queryable." ) if isinstance ( self . _iterable , tuple ) : return self . _iterable tup = tuple ( self ) return tup | Convert the source sequence to a tuple . |
48,138 | def to_set ( self ) : if self . closed ( ) : raise ValueError ( "Attempt to call to_set() on a closed Queryable." ) if isinstance ( self . _iterable , set ) : return self . _iterable s = set ( ) for item in self : if item in s : raise ValueError ( "Duplicate item value {0} in sequence " "during to_set()" . format ( rep... | Convert the source sequence to a set . |
48,139 | def to_lookup ( self , key_selector = identity , value_selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call to_lookup() on a closed Queryable." ) if not is_callable ( key_selector ) : raise TypeError ( "to_lookup() parameter key_selector={key_selector} is not callable" . format ( key_selec... | Returns a Lookup object using the provided selector to generate a key for each item . |
48,140 | def to_str ( self , separator = '' ) : if self . closed ( ) : raise ValueError ( "Attempt to call to_str() on a closed Queryable." ) return str ( separator ) . join ( self . select ( str ) ) | Build a string from the source sequence . |
48,141 | def sequence_equal ( self , second_iterable , equality_comparer = operator . eq ) : if self . closed ( ) : raise ValueError ( "Attempt to call to_tuple() on a closed Queryable." ) if not is_iterable ( second_iterable ) : raise TypeError ( "Cannot compute sequence_equal() with second_iterable of non-iterable {type}" . f... | Determine whether two sequences are equal by elementwise comparison . |
48,142 | def log ( self , logger = None , label = None , eager = False ) : if self . closed ( ) : raise ValueError ( "Attempt to call log() on a closed Queryable." ) if logger is None : return self if label is None : label = repr ( self ) if eager : return self . _create ( self . _eager_log_result ( logger , label ) ) return se... | Log query result consumption details to a logger . |
48,143 | def scan ( self , func = operator . add ) : if self . closed ( ) : raise ValueError ( "Attempt to call scan() on a " "closed Queryable." ) if not is_callable ( func ) : raise TypeError ( "scan() parameter func={0} is " "not callable" . format ( repr ( func ) ) ) return self . _create ( self . _generate_scan_result ( fu... | An inclusive prefix sum which returns the cumulative application of the supplied function up to an including the current element . |
48,144 | def pre_scan ( self , func = operator . add , seed = 0 ) : if self . closed ( ) : raise ValueError ( "Attempt to call pre_scan() on a " "closed Queryable." ) if not is_callable ( func ) : raise TypeError ( "pre_scan() parameter func={0} is " "not callable" . format ( repr ( func ) ) ) return self . _create ( self . _ge... | An exclusive prefix sum which returns the cumulative application of the supplied function up to but excluding the current element . |
48,145 | def then_by ( self , key_selector = identity ) : if self . closed ( ) : raise ValueError ( "Attempt to call then_by() on a " "closed OrderedQueryable." ) if not is_callable ( key_selector ) : raise TypeError ( "then_by() parameter key_selector={key_selector} " "is not callable" . format ( key_selector = repr ( key_sele... | Introduce subsequent ordering to the sequence with an optional key . |
48,146 | def geometric_partitions ( iterable , floor = 1 , ceiling = 32768 ) : partition_size = floor run_length = multiprocessing . cpu_count ( ) run_count = 0 try : while True : partition , iterable = itertools . tee ( iterable ) yield Queryable ( partition ) . take ( partition_size ) for i in range ( partition_size ) : next ... | Partition an iterable into chunks . Returns an iterator over partitions . |
48,147 | def adc ( self , other : 'BitVector' , carry : Bit ) -> tp . Tuple [ 'BitVector' , Bit ] : T = type ( self ) other = _coerce ( T , other ) carry = _coerce ( T . unsized_t [ 1 ] , carry ) a = self . zext ( 1 ) b = other . zext ( 1 ) c = carry . zext ( T . size ) res = a + b + c return res [ 0 : - 1 ] , res [ - 1 ] | add with carry |
48,148 | def make_table ( headers = None , rows = None ) : if callable ( headers ) : headers = headers ( ) if callable ( rows ) : rows = rows ( ) assert isinstance ( headers , list ) assert isinstance ( rows , list ) assert all ( len ( row ) == len ( headers ) for row in rows ) plain_headers = [ strip_ansi ( six . text_type ( v... | Make a table from headers and rows . |
48,149 | def _dual_decorator ( func ) : @ functools . wraps ( func ) def inner ( * args , ** kwargs ) : if ( ( len ( args ) == 1 and not kwargs and callable ( args [ 0 ] ) and not ( type ( args [ 0 ] ) == type and issubclass ( args [ 0 ] , BaseException ) ) ) ) : return func ( ) ( args [ 0 ] ) elif len ( args ) == 2 and inspect... | This is a decorator that converts a paramaterized decorator for no - param use . |
48,150 | def command ( cls , name = None ) : def decorator ( func ) : @ functools . wraps ( func ) def _cmd_wrapper ( rest , * args , ** kwargs ) : try : usage = _cmd_wrapper . __doc__ . partition ( '\n' ) [ 0 ] opts = docopt ( usage , rest ) except ( SystemExit , DocoptExit ) as e : return str ( e ) return func ( opts , * args... | A decorator to convert a function to a command . |
48,151 | def help_text ( cls ) : docs = [ cmd_func . __doc__ for cmd_func in cls . commands . values ( ) ] usage_lines = [ doc . partition ( '\n' ) [ 0 ] for doc in docs ] terse_lines = [ line [ len ( 'Usage: ' ) : ] for line in usage_lines ] terse_lines . sort ( ) return '\n' . join ( [ 'Available commands:\n' ] + terse_lines ... | Return a slack - formatted list of commands with their usage . |
48,152 | def run_forever ( self ) : res = self . slack . rtm . start ( ) self . log . info ( "current channels: %s" , ',' . join ( c [ 'name' ] for c in res . body [ 'channels' ] if c [ 'is_member' ] ) ) self . id = res . body [ 'self' ] [ 'id' ] self . name = res . body [ 'self' ] [ 'name' ] self . my_mention = "<@%s>" % self ... | Run the bot blocking forever . |
48,153 | def _bot_identifier ( self , message ) : text = message [ 'text' ] formatters = [ lambda identifier : "%s " % identifier , lambda identifier : "%s:" % identifier , ] my_identifiers = [ formatter ( identifier ) for identifier in [ self . name , self . my_mention ] for formatter in formatters ] for identifier in my_ident... | Return the identifier used to address this bot in this message . If one is not found return None . |
48,154 | def _send_rtm_message ( self , channel_id , text ) : message = { 'id' : self . _current_message_id , 'type' : 'message' , 'channel' : channel_id , 'text' : text , } self . ws . send ( json . dumps ( message ) ) self . _current_message_id += 1 | Send a Slack message to a channel over RTM . |
48,155 | def _send_api_message ( self , message ) : self . slack . chat . post_message ( ** message ) self . log . debug ( "sent api message %r" , message ) | Send a Slack message via the chat . postMessage api . |
48,156 | def _validators ( self ) : for validator in self . __validators__ . values ( ) : yield validator if self . validators : for validator in self . validators : yield validator | Iterate across the complete set of child validators . |
48,157 | def make_user_agent ( prefix = None ) : prefix = ( prefix or platform . platform ( terse = 1 ) ) . strip ( ) . lower ( ) return "cloudsmith-cli/%(prefix)s cli:%(version)s api:%(api_version)s" % { "version" : get_cli_version ( ) , "api_version" : get_api_version ( ) , "prefix" : prefix , } | Get a suitable user agent for identifying the CLI process . |
48,158 | def pretty_print_list_info ( num_results , page_info = None , suffix = None ) : num_results_fg = "green" if num_results else "red" num_results_text = click . style ( str ( num_results ) , fg = num_results_fg ) if page_info and page_info . is_valid : page_range = page_info . calculate_range ( num_results ) page_info_tex... | Pretty print list info with pagination for user display . |
48,159 | def pretty_print_table ( headers , rows ) : table = make_table ( headers = headers , rows = rows ) pretty_print_table_instance ( table ) | Pretty print a table from headers and rows . |
48,160 | def pretty_print_table_instance ( table ) : assert isinstance ( table , Table ) def pretty_print_row ( styled , plain ) : click . secho ( " | " . join ( v + " " * ( table . column_widths [ k ] - len ( plain [ k ] ) ) for k , v in enumerate ( styled ) ) ) pretty_print_row ( table . headers , table . plain_headers ) for ... | Pretty print a table instance . |
48,161 | def print_rate_limit_info ( opts , rate_info , atexit = False ) : if not rate_info : return show_info = ( opts . always_show_rate_limit or atexit or rate_info . interval > opts . rate_limit_warning ) if not show_info : return click . echo ( err = True ) click . secho ( "Throttling (rate limited) for: %(throttle)s secon... | Tell the user when we re being rate limited . |
48,162 | def maybe_print_as_json ( opts , data , page_info = None ) : if opts . output not in ( "json" , "pretty_json" ) : return False root = { "data" : data } if page_info is not None and page_info . is_valid : meta = root [ "meta" ] = { } meta [ "pagination" ] = page_info . as_dict ( num_results = len ( data ) ) if opts . ou... | Maybe print data as JSON . |
48,163 | def confirm_operation ( prompt , prefix = None , assume_yes = False , err = False ) : if assume_yes : return True prefix = prefix or click . style ( "Are you %s certain you want to" % ( click . style ( "absolutely" , bold = True ) ) ) prompt = "%(prefix)s %(prompt)s?" % { "prefix" : prefix , "prompt" : prompt } if clic... | Prompt the user for confirmation for dangerous actions . |
48,164 | def validate_login ( ctx , param , value ) : value = value . strip ( ) if not value : raise click . BadParameter ( "The value cannot be blank." , param = param ) return value | Ensure that login is not blank . |
48,165 | def create_config_files ( ctx , opts , api_key ) : config_reader = opts . get_config_reader ( ) creds_reader = opts . get_creds_reader ( ) has_config = config_reader . has_default_file ( ) has_creds = creds_reader . has_default_file ( ) if has_config and has_creds : create = False else : click . echo ( ) create = click... | Create default config files . |
48,166 | def status ( ctx , opts , owner_repo_package ) : owner , repo , slug = owner_repo_package click . echo ( "Getting status of %(package)s in %(owner)s/%(repo)s ... " % { "owner" : click . style ( owner , bold = True ) , "repo" : click . style ( repo , bold = True ) , "package" : click . style ( slug , bold = True ) , } ,... | Get the synchronisation status for a package . |
48,167 | def _process_arguments ( self , args , kw ) : if len ( args ) > len ( self . __attributes__ ) : raise TypeError ( '{0} takes no more than {1} argument{2} ({3} given)' . format ( self . __class__ . __name__ , len ( self . __attributes__ ) , '' if len ( self . __attributes__ ) == 1 else 's' , len ( args ) ) ) names = [ n... | Map positional to keyword arguments identify invalid assignments and return the result . This is likely generic enough to be useful as a standalone utility function and goes to a fair amount of effort to ensure raised exceptions are as Python - like as possible . |
48,168 | def native ( self , value , context = None ) : value = super ( ) . native ( value , context ) if self . none and ( value is None ) : return None try : value = value . lower ( ) except AttributeError : return bool ( value ) if value in self . truthy : return True if value in self . falsy : return False raise Concern ( "... | Convert a foreign value to a native boolean . |
48,169 | def foreign ( self , value , context = None ) : if self . none and value is None : return '' try : value = self . native ( value , context ) except Concern : value = bool ( value . strip ( ) if self . strip and hasattr ( value , 'strip' ) else value ) if value in self . truthy or value : return self . truthy [ self . u... | Convert a native value to a textual boolean . |
48,170 | def get_root_path ( ) : root_path = __file__ return os . path . dirname ( os . path . realpath ( root_path ) ) | Get the root path for the application . |
48,171 | def rand ( n , ** kwargs ) : rvec = np . random . randn ( 3 ) rvec = rvec / np . linalg . norm ( rvec ) return rvec | Random vector from the n - Sphere |
48,172 | def tan_rand ( q , seed = 9 ) : rs = np . random . RandomState ( seed ) rvec = rs . rand ( q . shape [ 0 ] ) qd = np . cross ( rvec , q ) qd = qd / np . linalg . norm ( qd ) while np . dot ( q , qd ) > 1e-6 : rvec = rs . rand ( q . shape [ 0 ] ) qd = np . cross ( rvec , q ) qd = qd / np . linalg . norm ( qd ) return qd | Find a random vector in the tangent space of the n sphere |
48,173 | def perturb_vec ( q , cone_half_angle = 2 ) : r rand_vec = tan_rand ( q ) cross_vector = attitude . unit_vector ( np . cross ( q , rand_vec ) ) s = np . random . uniform ( 0 , 1 , 1 ) r = np . random . uniform ( 0 , 1 , 1 ) h = np . cos ( np . deg2rad ( cone_half_angle ) ) phi = 2 * np . pi * s z = h + ( 1 - h ) * r si... | r Perturb a vector randomly |
48,174 | def common_package_action_options ( f ) : @ click . option ( "-s" , "--skip-errors" , default = False , is_flag = True , help = "Skip/ignore errors when copying packages." , ) @ click . option ( "-W" , "--no-wait-for-sync" , default = False , is_flag = True , help = "Don't wait for package synchronisation to complete b... | Add common options for package actions . |
48,175 | def common_cli_config_options ( f ) : @ click . option ( "-C" , "--config-file" , envvar = "CLOUDSMITH_CONFIG_FILE" , type = click . Path ( dir_okay = True , exists = True , writable = False , resolve_path = True ) , help = "The path to your config.ini file." , ) @ click . option ( "--credentials-file" , envvar = "CLOU... | Add common CLI config options to commands . |
48,176 | def common_cli_output_options ( f ) : @ click . option ( "-d" , "--debug" , default = False , is_flag = True , help = "Produce debug output during processing." , ) @ click . option ( "-F" , "--output-format" , default = "pretty" , type = click . Choice ( [ "pretty" , "json" , "pretty_json" ] ) , help = "Determines how ... | Add common CLI output options to commands . |
48,177 | def common_cli_list_options ( f ) : @ click . option ( "-p" , "--page" , default = 1 , type = int , help = "The page to view for lists, where 1 is the first page" , callback = validators . validate_page , ) @ click . option ( "-l" , "--page-size" , default = 30 , type = int , help = "The amount of items to view per pag... | Add common list options to commands . |
48,178 | def common_api_auth_options ( f ) : @ click . option ( "-k" , "--api-key" , hide_input = True , envvar = "CLOUDSMITH_API_KEY" , help = "The API key for authenticating with the API." , ) @ click . pass_context @ functools . wraps ( f ) def wrapper ( ctx , * args , ** kwargs ) : opts = config . get_or_create_options ( ct... | Add common API authentication options to commands . |
48,179 | def list_entitlements ( owner , repo , page , page_size , show_tokens ) : client = get_entitlements_api ( ) with catch_raise_api_exception ( ) : data , _ , headers = client . entitlements_list_with_http_info ( owner = owner , repo = repo , page = page , page_size = page_size , show_tokens = show_tokens , ) ratelimits .... | Get a list of entitlements on a repository . |
48,180 | def create_entitlement ( owner , repo , name , token , show_tokens ) : client = get_entitlements_api ( ) data = { } if name is not None : data [ "name" ] = name if token is not None : data [ "token" ] = token with catch_raise_api_exception ( ) : data , _ , headers = client . entitlements_create_with_http_info ( owner =... | Create an entitlement in a repository . |
48,181 | def update_entitlement ( owner , repo , identifier , name , token , show_tokens ) : client = get_entitlements_api ( ) data = { } if name is not None : data [ "name" ] = name if token is not None : data [ "token" ] = token with catch_raise_api_exception ( ) : data , _ , headers = client . entitlements_partial_update_wit... | Update an entitlement in a repository . |
48,182 | def initialise_api ( debug = False , host = None , key = None , proxy = None , user_agent = None , headers = None , rate_limit = True , rate_limit_callback = None , error_retry_max = None , error_retry_backoff = None , error_retry_codes = None , ) : config = cloudsmith_api . Configuration ( ) config . debug = debug con... | Initialise the API . |
48,183 | def set_api_key ( config , key ) : if not key and "X-Api-Key" in config . api_key : del config . api_key [ "X-Api-Key" ] else : config . api_key [ "X-Api-Key" ] = key | Configure a new API key . |
48,184 | def upload_file ( upload_url , upload_fields , filepath , callback = None ) : upload_fields = list ( six . iteritems ( upload_fields ) ) upload_fields . append ( ( "file" , ( os . path . basename ( filepath ) , click . open_file ( filepath , "rb" ) ) ) ) encoder = MultipartEncoder ( upload_fields ) monitor = MultipartE... | Upload a pre - signed file to Cloudsmith . |
48,185 | def handle_api_exceptions ( ctx , opts , context_msg = None , nl = False , exit_on_error = True , reraise_on_error = False ) : use_stderr = opts . output != "pretty" try : yield except ApiException as exc : if nl : click . echo ( err = use_stderr ) click . secho ( "ERROR: " , fg = "red" , nl = False , err = use_stderr ... | Context manager that handles API exceptions . |
48,186 | def get_details ( exc ) : detail = None fields = collections . OrderedDict ( ) if exc . detail : detail = exc . detail if exc . fields : for k , v in six . iteritems ( exc . fields ) : try : field_detail = v [ "detail" ] except ( TypeError , KeyError ) : field_detail = v if isinstance ( field_detail , ( list , tuple ) ... | Get the details from the exception . |
48,187 | def make_env_key ( app_name , key ) : key = key . replace ( '-' , '_' ) . replace ( ' ' , '_' ) return str ( "_" . join ( ( x . upper ( ) for x in ( app_name , key ) ) ) ) | Creates an environment key - equivalent for the given key |
48,188 | def unset_env ( self , key ) : os . environ . pop ( make_env_key ( self . appname , key ) , None ) self . _registered_env_keys . discard ( key ) self . _clear_memoization ( ) | Removes an environment variable using the prepended app_name convention with key . |
48,189 | def _reload ( self , force = False ) : self . _config_map = dict ( ) self . _registered_env_keys = set ( ) self . __reload_sources ( force ) self . __load_environment_keys ( ) self . verify ( ) self . _clear_memoization ( ) | Reloads the configuration from the file and environment variables . Useful if using os . environ instead of this class set_env method or if the underlying configuration file is changed externally . |
48,190 | def create_requests_session ( retries = None , backoff_factor = None , status_forcelist = None , pools_size = 4 , maxsize = 4 , ssl_verify = None , ssl_cert = None , proxy = None , session = None , ) : config = Configuration ( ) if retries is None : if config . error_retry_max is None : retries = 5 else : retries = con... | Create a requests session that retries some errors . |
48,191 | def getheader ( self , name , default = None ) : return self . response . headers . get ( name , default ) | Return a given response header . |
48,192 | def get_root_path ( ) : return os . path . realpath ( os . path . join ( os . path . dirname ( __file__ ) , os . pardir ) ) | Get the root directory for the application . |
48,193 | def calculate_file_md5 ( filepath , blocksize = 2 ** 20 ) : checksum = hashlib . md5 ( ) with click . open_file ( filepath , "rb" ) as f : def update_chunk ( ) : buf = f . read ( blocksize ) if buf : checksum . update ( buf ) return bool ( buf ) while update_chunk ( ) : pass return checksum . hexdigest ( ) | Calculate an MD5 hash for a file . |
48,194 | def _get_version_from_git_tag ( path ) : m = GIT_DESCRIBE_REGEX . match ( _git_describe_tags ( path ) or '' ) if m is None : return None version , post_commit , hash = m . groups ( ) return version if post_commit == '0' else "{0}.post{1}+{2}" . format ( version , post_commit , hash ) | Return a PEP440 - compliant version derived from the git status . If that fails for any reason return the changeset hash . |
48,195 | def get_version ( dunder_file ) : path = abspath ( expanduser ( dirname ( dunder_file ) ) ) try : return _get_version_from_version_file ( path ) or _get_version_from_git_tag ( path ) except CalledProcessError as e : log . warn ( repr ( e ) ) return None except Exception as e : log . exception ( e ) return None | Returns a version string for the current package derived either from git or from a . version file . |
48,196 | def rot1 ( angle , form = 'c' ) : cos_a = np . cos ( angle ) sin_a = np . sin ( angle ) rot_mat = np . identity ( 3 ) if form == 'c' : rot_mat [ 1 , 1 ] = cos_a rot_mat [ 1 , 2 ] = - sin_a rot_mat [ 2 , 1 ] = sin_a rot_mat [ 2 , 2 ] = cos_a elif form == 'r' : rot_mat [ 1 , 1 ] = cos_a rot_mat [ 1 , 2 ] = sin_a rot_mat ... | Euler rotation about first axis |
48,197 | def dcm2body313 ( dcm ) : theta = np . zeros ( 3 ) theta [ 0 ] = np . arctan2 ( dcm [ 2 , 0 ] , dcm [ 2 , 1 ] ) theta [ 1 ] = np . arccos ( dcm [ 2 , 2 ] ) theta [ 2 ] = np . arctan2 ( dcm [ 0 , 2 ] , - dcm [ 1 , 2 ] ) return theta | Convert DCM to body Euler 3 - 1 - 3 angles |
48,198 | def vee_map ( skew ) : vec = 1 / 2 * np . array ( [ skew [ 2 , 1 ] - skew [ 1 , 2 ] , skew [ 0 , 2 ] - skew [ 2 , 0 ] , skew [ 1 , 0 ] - skew [ 0 , 1 ] ] ) return vec | Return the vee map of a vector |
48,199 | def dcmtoquat ( dcm ) : quat = np . zeros ( 4 ) quat [ - 1 ] = 1 / 2 * np . sqrt ( np . trace ( dcm ) + 1 ) quat [ 0 : 3 ] = 1 / 4 / quat [ - 1 ] * vee_map ( dcm - dcm . T ) return quat | Convert DCM to quaternion This function will convert a rotation matrix also called a direction cosine matrix into the equivalent quaternion . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.