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 ( url , headers = headers , params = params ) response . raise_for_status ( ) results . extend ( response . json ( ) ) if 'next' in response . links : url = response . links [ 'next' ] [ 'url' ] else : break return results | 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 ) return pages | 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 = name , size = len ( filedata ) , description = description ) ) response = requests . post ( url , data = payload , headers = make_auth_header ( ) ) response . raise_for_status ( ) reply = json . loads ( response . content ) s3_url = reply [ 's3_url' ] fields = dict ( key = reply [ 'path' ] , acl = reply [ 'acl' ] , success_action_status = 201 , Filename = reply [ 'name' ] , AWSAccessKeyId = reply [ 'accesskeyid' ] , Policy = reply [ 'policy' ] , Signature = reply [ 'signature' ] , file = ( reply [ 'name' ] , filedata ) , ) fields [ 'Content-Type' ] = reply [ 'mime_type' ] data , content_type = encode_multipart_formdata ( fields ) s3r = requests . post ( s3_url , data = data , headers = { 'Content-Type' : content_type } ) return s3r | 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 ( matlab_bin , "mexext" ) ) extension = subprocess . check_output ( extcmd , shell = use_shell ) extension = extension . decode ( 'utf-8' ) . rstrip ( '\r\n' ) mex = esc ( os . path . join ( matlab_bin , "mex" ) ) paths = "-L%(zmq_lib)s -I%(zmq_inc)s" % cfg make_cmd = '%s -O %s -lzmq ./src/messenger.c' % ( mex , paths ) if static : make_cmd += ' -DZMQ_STATIC' do_build ( make_cmd , 'messenger.%s' % extension ) | 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 = repr ( selector ) ) ) if selector is identity : return self return self . _create ( imap ( selector , self ) ) | 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 ( repr ( selector ) ) ) if not is_callable ( transform ) : raise TypeError ( "select_with_index() parameter item_selector={0} is " "not callable" . format ( repr ( selector ) ) ) return self . _create ( itertools . starmap ( selector , enumerate ( imap ( transform , iter ( self ) ) ) ) ) | 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 callable" . format ( repr ( selector ) ) ) if not is_callable ( result_selector ) : raise TypeError ( "select_with_correspondence() parameter result_selector={0} is " "not callable" . format ( repr ( result_selector ) ) ) return self . _create ( result_selector ( elem , selector ( elem ) ) for elem in iter ( self ) ) | 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" . format ( repr ( collection_selector ) ) ) if not is_callable ( result_selector ) : raise TypeError ( "select_many() parameter selector={selector} is " " not callable" . format ( selector = repr ( result_selector ) ) ) sequences = self . select ( collection_selector ) chained_sequence = itertools . chain . from_iterable ( sequences ) return self . _create ( chained_sequence ) . select ( result_selector ) | 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 ) : raise TypeError ( "select_many_with_index() parameter " "projector={0} is not callable" . format ( repr ( collection_selector ) ) ) if not is_callable ( result_selector ) : raise TypeError ( "select_many_with_index() parameter " "selector={0} is not callable" . format ( repr ( result_selector ) ) ) return self . _create ( self . _generate_select_many_with_index ( collection_selector , result_selector ) ) | 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_correspondence() parameter " "projector={0} is not callable" . format ( repr ( collection_selector ) ) ) if not is_callable ( result_selector ) : raise TypeError ( "select_many_with_correspondence() parameter " "selector={0} is not callable" . format ( repr ( result_selector ) ) ) return self . _create ( self . _generate_select_many_with_correspondence ( collection_selector , result_selector ) ) | 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_selector={0} is not " "callable" . format ( repr ( key_selector ) ) ) if not is_callable ( element_selector ) : raise TypeError ( "group_by() parameter element_selector={0} is not " "callable" . format ( repr ( element_selector ) ) ) if not is_callable ( result_selector ) : raise TypeError ( "group_by() parameter result_selector={0} is not " "callable" . format ( repr ( result_selector ) ) ) return self . _create ( self . _generate_group_by_result ( key_selector , element_selector , result_selector ) ) | 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 ( predicate , self ) ) | 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 ) ) return self . where ( lambda x : isinstance ( x , 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 ) ) ) return self . _create_ordered ( iter ( self ) , - 1 , 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 . _generate_take_while_result ( predicate ) ) | 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_skip_result ( count , stop ) ) except TypeError : pass return self . _create ( self . _generate_skip_result ( count ) ) | 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 . dropwhile ( predicate , self ) ) | 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 ] ) ) return self . _create ( itertools . chain ( self , second_iterable ) ) | 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." ) except TypeError : pass for i , item in enumerate ( self ) : if i == index : return item raise OutOfRangeError ( "element_at(index) out of range." ) | 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 ( predicate ) ) ) for item in self . select ( predicate ) : if item : return True return False | 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 . select ( selector ) : total += item count += 1 if count == 0 : raise ValueError ( "Cannot compute average() of an empty sequence." ) return total / count | 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_comparer ) ) ) if equality_comparer is operator . eq : return value in self . _iterable for item in self : if equality_comparer ( value , item ) : return True return False | 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 . _generate_distinct_result ( selector ) ) | 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 ( second_iterable ) ) [ 7 : - 2 ] ) ) if not is_callable ( selector ) : raise TypeError ( "difference() parameter selector={0} is " "not callable" . format ( repr ( selector ) ) ) return self . _create ( self . _generate_difference_result ( second_iterable , selector ) ) | 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 ( second_iterable ) ) [ 7 : - 1 ] ) ) if not is_callable ( selector ) : raise TypeError ( "intersect() parameter selector={0} is " "not callable" . format ( repr ( selector ) ) ) return self . _create ( self . _generate_intersect_result ( second_iterable , selector ) ) | 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_iterable ) ) [ 7 : - 1 ] ) ) return self . _create ( itertools . chain ( self , second_iterable ) ) . distinct ( selector ) | 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 compute join() with inner_iterable of " "non-iterable {0}" . format ( str ( type ( inner_iterable ) ) [ 7 : - 1 ] ) ) if not is_callable ( outer_key_selector ) : raise TypeError ( "join() parameter outer_key_selector={0} is not " "callable" . format ( repr ( outer_key_selector ) ) ) if not is_callable ( inner_key_selector ) : raise TypeError ( "join() parameter inner_key_selector={0} is not " "callable" . format ( repr ( inner_key_selector ) ) ) if not is_callable ( result_selector ) : raise TypeError ( "join() parameter result_selector={0} is not " "callable" . format ( repr ( result_selector ) ) ) return self . _create ( self . _generate_join_result ( inner_iterable , outer_key_selector , inner_key_selector , result_selector ) ) | 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 ( "Cannot compute group_join() with inner_iterable of non-iterable {type}" . format ( type = str ( type ( inner_iterable ) ) [ 7 : - 1 ] ) ) if not is_callable ( outer_key_selector ) : raise TypeError ( "group_join() parameter outer_key_selector={outer_key_selector} is not callable" . format ( outer_key_selector = repr ( outer_key_selector ) ) ) if not is_callable ( inner_key_selector ) : raise TypeError ( "group_join() parameter inner_key_selector={inner_key_selector} is not callable" . format ( inner_key_selector = repr ( inner_key_selector ) ) ) if not is_callable ( result_selector ) : raise TypeError ( "group_join() parameter result_selector={result_selector} is not callable" . format ( result_selector = repr ( result_selector ) ) ) return self . _create ( self . _generate_group_join_result ( inner_iterable , outer_key_selector , inner_key_selector , result_selector ) ) | 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 ) ) ) if not is_callable ( result_selector ) : raise TypeError ( "aggregate() parameter result_selector={0} is " "not callable" . format ( repr ( result_selector ) ) ) if seed is default : try : return result_selector ( fold ( reducer , self ) ) except TypeError as e : if 'empty sequence' in str ( e ) : raise ValueError ( "Cannot aggregate() empty sequence with " "no seed value" ) return result_selector ( fold ( reducer , self , seed ) ) | 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 ( second_iterable ) ) [ 7 : - 1 ] ) ) if not is_callable ( result_selector ) : raise TypeError ( "zip() parameter result_selector={0} is " "not callable" . format ( repr ( result_selector ) ) ) return self . _create ( result_selector ( * t ) for t in izip ( self , second_iterable ) ) | 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 ( repr ( item ) ) ) s . add ( item ) return s | 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_selector = repr ( key_selector ) ) ) if not is_callable ( value_selector ) : raise TypeError ( "to_lookup() parameter value_selector={value_selector} is not callable" . format ( value_selector = repr ( value_selector ) ) ) key_value_pairs = self . select ( lambda item : ( key_selector ( item ) , value_selector ( item ) ) ) lookup = Lookup ( key_value_pairs ) return lookup | 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}" . format ( type = str ( type ( second_iterable ) ) [ 7 : - 1 ] ) ) if not is_callable ( equality_comparer ) : raise TypeError ( "aggregate() parameter equality_comparer={equality_comparer} is not callable" . format ( equality_comparer = repr ( equality_comparer ) ) ) try : if len ( self . _iterable ) != len ( second_iterable ) : return False except TypeError : pass sentinel = object ( ) for first , second in izip_longest ( self , second_iterable , fillvalue = sentinel ) : if first is sentinel or second is sentinel : return False if not equality_comparer ( first , second ) : return False return True | 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 self . _create ( self . _generate_lazy_log_result ( logger , label ) ) | 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 ( func ) ) | 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 . _generate_pre_scan_result ( func , seed ) ) | 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_selector ) ) ) self . _funcs . append ( ( - 1 , key_selector ) ) return self | 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 ( iterable ) run_count += 1 if run_count >= run_length : partition_size *= 2 run_count = 0 if partition_size > ceiling : partition_size = ceiling except StopIteration : pass | 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 ) ) for v in headers ] plain_rows = [ row for row in [ strip_ansi ( six . text_type ( v ) ) for v in rows ] ] plain_headers = [ ] column_widths = [ ] for k , v in enumerate ( headers ) : v = six . text_type ( v ) plain = strip_ansi ( v ) plain_headers . append ( plain ) column_widths . append ( len ( plain ) ) if len ( v ) == len ( plain ) : v = click . style ( v , bold = True ) headers [ k ] = v plain_rows = [ ] for row in rows : plain_row = [ ] for k , v in enumerate ( row ) : v = six . text_type ( v ) plain = strip_ansi ( v ) plain_row . append ( plain ) column_widths [ k ] = max ( column_widths [ k ] , len ( plain ) ) plain_rows . append ( plain_row ) return Table ( headers = headers , plain_headers = plain_headers , rows = rows , plain_rows = plain_rows , column_widths = column_widths , ) | 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 . isclass ( args [ 0 ] ) and callable ( args [ 1 ] ) : return func ( args [ 0 ] , ** kwargs ) ( args [ 1 ] ) else : return func ( * args , ** kwargs ) return inner | 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 , ** kwargs ) cls . commands [ name or func . __name__ ] = _cmd_wrapper return _cmd_wrapper return decorator | 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 . id self . ws = websocket . WebSocketApp ( res . body [ 'url' ] , on_message = self . _on_message , on_error = self . _on_error , on_close = self . _on_close , on_open = self . _on_open ) self . prepare_connection ( self . config ) self . ws . run_forever ( ) | 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_identifiers : if text . startswith ( identifier ) : self . log . debug ( "sent to me:\n%s" , pprint . pformat ( message ) ) return identifier return None | 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_text = "page: %(page)s/%(page_total)s, page size: %(page_size)s" % { "page" : click . style ( str ( page_info . page ) , bold = True ) , "page_size" : click . style ( str ( page_info . page_size ) , bold = True ) , "page_total" : click . style ( str ( page_info . page_total ) , bold = True ) , } range_results_text = "%(from)s-%(to)s (%(num_results)s) of %(total)s" % { "num_results" : num_results_text , "from" : click . style ( str ( page_range [ 0 ] ) , fg = num_results_fg ) , "to" : click . style ( str ( page_range [ 1 ] ) , fg = num_results_fg ) , "total" : click . style ( str ( page_info . count ) , fg = num_results_fg ) , } else : page_info_text = "" range_results_text = num_results_text click . secho ( "Results: %(range_results)s %(suffix)s%(page_info)s" % { "range_results" : range_results_text , "page_info" : " (%s)" % page_info_text if page_info_text else "" , "suffix" : suffix or "item(s)" , } ) | 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 k , row in enumerate ( table . rows ) : pretty_print_row ( row , table . plain_rows [ k ] ) | 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 seconds ... " % { "throttle" : click . style ( six . text_type ( rate_info . interval ) , reverse = True ) } , err = True , reset = False , ) | 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 . output == "pretty_json" : dump = json . dumps ( root , indent = 4 , sort_keys = True ) else : dump = json . dumps ( root , sort_keys = True ) click . echo ( dump ) return True | 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 click . confirm ( prompt , err = err ) : return True click . echo ( err = err ) click . secho ( "OK, phew! Close call. :-)" , fg = "green" , err = err ) return False | 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 . confirm ( "No default config file(s) found, do you want to create them?" ) click . echo ( ) if not create : click . secho ( "For reference here are your default config file locations:" , fg = "yellow" ) else : click . secho ( "Great! Let me just create your default configs for you now ..." , fg = "green" ) configs = ( ConfigValues ( reader = config_reader , present = has_config , mode = None , data = { } ) , ConfigValues ( reader = creds_reader , present = has_creds , mode = stat . S_IRUSR | stat . S_IWUSR | stat . S_IRGRP | stat . S_IWGRP , data = { "api_key" : api_key } , ) , ) has_errors = False for config in configs : click . echo ( "%(name)s config file: %(filepath)s ... " % { "name" : click . style ( config . reader . config_name . capitalize ( ) , bold = True ) , "filepath" : click . style ( config . reader . get_default_filepath ( ) , fg = "magenta" ) , } , nl = False , ) if not config . present and create : try : ok = config . reader . create_default_file ( data = config . data , mode = config . mode ) except ( OSError , IOError ) as exc : ok = False error_message = exc . strerror has_errors = True if ok : click . secho ( "CREATED" , fg = "green" ) else : click . secho ( "ERROR" , fg = "red" ) click . secho ( "The following error occurred while trying to " "create the file: %(message)s" % { "message" : click . style ( error_message , fg = "red" ) } ) continue click . secho ( "EXISTS" if config . present else "NOT CREATED" , fg = "yellow" ) return create , has_errors | 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 ) , } , nl = False , ) context_msg = "Failed to get status of package!" with handle_api_exceptions ( ctx , opts = opts , context_msg = context_msg ) : with maybe_spinner ( opts ) : res = get_package_status ( owner , repo , slug ) ok , failed , _ , status_str , stage_str , reason = res click . secho ( "OK" , fg = "green" ) if not stage_str : package_status = status_str else : package_status = "%(status)s / %(stage)s" % { "status" : status_str , "stage" : stage_str , } if ok : status_colour = "green" elif failed : status_colour = "red" else : status_colour = "magenta" click . secho ( "The package status is: %(status)s" % { "status" : click . style ( package_status , fg = status_colour ) } ) if reason : click . secho ( "Reason given: %(reason)s" % { "reason" : click . style ( reason , fg = "yellow" ) } , fg = status_colour , ) | 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 = [ name for name in self . __attributes__ . keys ( ) if name [ 0 ] != '_' or name == '__name__' ] [ : len ( args ) ] duplicates = set ( kw . keys ( ) ) & set ( names ) if duplicates : raise TypeError ( '{0} got multiple values for keyword argument{1}: {2}' . format ( self . __class__ . __name__ , '' if len ( duplicates ) == 1 else 's' , ', ' . join ( duplicates ) ) ) def field_values ( args , kw ) : for i , arg in enumerate ( self . __attributes__ . keys ( ) ) : if len ( args ) : yield arg , args . popleft ( ) if arg in kw : yield arg , kw . pop ( arg ) result = odict ( field_values ( deque ( args ) , dict ( kw ) ) ) unknown = set ( kw . keys ( ) ) - set ( result . keys ( ) ) if unknown : raise TypeError ( '{0} got unexpected keyword argument{1}: {2}' . format ( self . __class__ . __name__ , '' if len ( unknown ) == 1 else 's' , ', ' . join ( unknown ) ) ) return result | 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 ( "Unable to convert {0!r} to a boolean value." , value ) | 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 . use ] return self . falsy [ self . use ] | 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 sinT = np . sqrt ( 1 - z ** 2 ) x = np . cos ( phi ) * sinT y = np . sin ( phi ) * sinT perturbed = rand_vec * x + cross_vector * y + q * z return perturbed | 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 before " "exiting." , ) @ click . option ( "-I" , "--wait-interval" , default = 5.0 , type = float , show_default = True , help = "The time in seconds to wait between checking synchronisation." , ) @ click . option ( "--sync-attempts" , default = 3 , type = int , help = "Number of times to attempt package synchronisation. If the " "package fails the first time, the client will attempt to " "automatically resynchronise it." , ) @ click . pass_context @ functools . wraps ( f ) def wrapper ( ctx , * args , ** kwargs ) : return ctx . invoke ( f , * args , ** kwargs ) return wrapper | 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 = "CLOUDSMITH_CREDENTIALS_FILE" , type = click . Path ( dir_okay = True , exists = True , writable = False , resolve_path = True ) , help = "The path to your credentials.ini file." , ) @ click . option ( "-P" , "--profile" , default = None , envvar = "CLOUDSMITH_PROFILE" , help = "The name of the profile to use for configuration." , ) @ click . pass_context @ functools . wraps ( f ) def wrapper ( ctx , * args , ** kwargs ) : opts = config . get_or_create_options ( ctx ) profile = kwargs . pop ( "profile" ) config_file = kwargs . pop ( "config_file" ) creds_file = kwargs . pop ( "credentials_file" ) opts . load_config_file ( path = config_file , profile = profile ) opts . load_creds_file ( path = creds_file , profile = profile ) kwargs [ "opts" ] = opts return ctx . invoke ( f , * args , ** kwargs ) return wrapper | 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 output is formatted. This is only supported by a " "subset of the commands at the moment (e.g. list)." , ) @ click . option ( "-v" , "--verbose" , is_flag = True , default = False , help = "Produce more output during processing." , ) @ click . pass_context @ functools . wraps ( f ) def wrapper ( ctx , * args , ** kwargs ) : opts = config . get_or_create_options ( ctx ) opts . debug = kwargs . pop ( "debug" ) opts . output = kwargs . pop ( "output_format" ) opts . verbose = kwargs . pop ( "verbose" ) kwargs [ "opts" ] = opts return ctx . invoke ( f , * args , ** kwargs ) return wrapper | 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 page for lists." , callback = validators . validate_page_size , ) @ click . pass_context @ functools . wraps ( f ) def wrapper ( ctx , * args , ** kwargs ) : opts = config . get_or_create_options ( ctx ) kwargs [ "opts" ] = opts return ctx . invoke ( f , * args , ** kwargs ) return wrapper | 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 ( ctx ) opts . api_key = kwargs . pop ( "api_key" ) kwargs [ "opts" ] = opts return ctx . invoke ( f , * args , ** kwargs ) return wrapper | 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 . maybe_rate_limit ( client , headers ) page_info = PageInfo . from_headers ( headers ) entitlements = [ ent . to_dict ( ) for ent in data ] return entitlements , page_info | 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 = owner , repo = repo , data = data , show_tokens = show_tokens ) ratelimits . maybe_rate_limit ( client , headers ) return data . to_dict ( ) | 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_with_http_info ( owner = owner , repo = repo , identifier = identifier , data = data , show_tokens = show_tokens , ) ratelimits . maybe_rate_limit ( client , headers ) return data . to_dict ( ) | 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 config . host = host if host else config . host config . proxy = proxy if proxy else config . proxy config . user_agent = user_agent config . headers = headers config . rate_limit = rate_limit config . rate_limit_callback = rate_limit_callback config . error_retry_max = error_retry_max config . error_retry_backoff = error_retry_backoff config . error_retry_codes = error_retry_codes if headers : if "Authorization" in config . headers : encoded = config . headers [ "Authorization" ] . split ( " " ) [ 1 ] decoded = base64 . b64decode ( encoded ) values = decoded . decode ( "utf-8" ) config . username , config . password = values . split ( ":" ) set_api_key ( config , key ) return config | 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 = MultipartEncoderMonitor ( encoder , callback = callback ) config = cloudsmith_api . Configuration ( ) if config . proxy : proxies = { "http" : config . proxy , "https" : config . proxy } else : proxies = None headers = { "content-type" : monitor . content_type } client = get_files_api ( ) headers [ "user-agent" ] = client . api_client . user_agent session = create_requests_session ( ) resp = session . post ( upload_url , data = monitor , headers = headers , proxies = proxies ) try : resp . raise_for_status ( ) except requests . RequestException as exc : raise ApiException ( resp . status_code , headers = exc . response . headers , body = exc . response . content ) | 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 ) else : click . secho ( "ERROR" , fg = "red" , err = use_stderr ) context_msg = context_msg or "Failed to perform operation!" click . secho ( "%(context)s (status: %(code)s - %(code_text)s)" % { "context" : context_msg , "code" : exc . status , "code_text" : exc . status_description , } , fg = "red" , err = use_stderr , ) detail , fields = get_details ( exc ) if detail or fields : click . echo ( err = use_stderr ) if detail : click . secho ( "Detail: %(detail)s" % { "detail" : click . style ( detail , fg = "red" , bold = False ) } , bold = True , err = use_stderr , ) if fields : for k , v in six . iteritems ( fields ) : field = "%s Field" % k . capitalize ( ) click . secho ( "%(field)s: %(message)s" % { "field" : click . style ( field , bold = True ) , "message" : click . style ( v , fg = "red" ) , } , err = use_stderr , ) hint = get_error_hint ( ctx , opts , exc ) if hint : click . echo ( "Hint: %(hint)s" % { "hint" : click . style ( hint , fg = "yellow" ) } , err = use_stderr , ) if opts . verbose and not opts . debug : if exc . headers : click . echo ( err = use_stderr ) click . echo ( "Headers in Reply:" , err = use_stderr ) for k , v in six . iteritems ( exc . headers ) : click . echo ( "%(key)s = %(value)s" % { "key" : k , "value" : v } , err = use_stderr ) if reraise_on_error : six . reraise ( * sys . exc_info ( ) ) if exit_on_error : ctx . exit ( exc . status or 1 ) | 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 ) ) : field_detail = " " . join ( field_detail ) if k == "non_field_errors" : if detail : detail += " " + field_detail else : detail = field_detail continue fields [ k ] = field_detail return detail , fields | 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 = config . error_retry_max if backoff_factor is None : if config . error_retry_backoff is None : backoff_factor = 0.23 else : backoff_factor = config . error_retry_backoff if status_forcelist is None : if config . error_retry_codes is None : status_forcelist = [ 500 , 502 , 503 , 504 ] else : status_forcelist = config . error_retry_codes if ssl_verify is None : ssl_verify = config . verify_ssl if ssl_cert is None : if config . cert_file and config . key_file : ssl_cert = ( config . cert_file , config . key_file ) elif config . cert_file : ssl_cert = config . cert_file if proxy is None : proxy = Configuration ( ) . proxy session = session or requests . Session ( ) session . verify = ssl_verify session . cert = ssl_cert if proxy : session . proxies = { "http" : proxy , "https" : proxy } retry = Retry ( backoff_factor = backoff_factor , connect = retries , method_whitelist = False , read = retries , status_forcelist = tuple ( status_forcelist ) , total = retries , ) adapter = HTTPAdapter ( max_retries = retry , pool_connections = pools_size , pool_maxsize = maxsize , pool_block = True , ) session . mount ( "http://" , adapter ) session . mount ( "https://" , adapter ) return session | 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 [ 2 , 1 ] = - sin_a rot_mat [ 2 , 2 ] = cos_a else : print ( "Unknown input. 'r' or 'c' for row/column notation." ) return 1 return 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.