idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
250,300 | def get_image_array ( self ) : specials_mask = self . specials_mask ( ) data = self . data . copy ( ) data [ specials_mask ] -= data [ specials_mask ] . min ( ) data [ specials_mask ] *= 255 / data [ specials_mask ] . max ( ) data [ data == self . specials [ 'His' ] ] = 255 data [ data == self . specials [ 'Hrs' ] ] = ... | Create an array for use in making an image . |
250,301 | def check_isis_version ( major , minor = 0 , patch = 0 ) : if ISIS_VERSION and ( major , minor , patch ) <= ISIS_VERISON_TUPLE : return msg = 'Version %s.%s.%s of isis required (%s found).' raise VersionError ( msg % ( major , minor , patch , ISIS_VERSION ) ) | Checks that the current isis version is equal to or above the suplied version . |
250,302 | def require_isis_version ( major , minor = 0 , patch = 0 ) : def decorator ( fn ) : @ wraps ( fn ) def wrapper ( * args , ** kwargs ) : check_isis_version ( major , minor , patch ) return fn ( * args , ** kwargs ) return wrapper return decorator | Decorator that ensures a function is called with a minimum isis version . |
250,303 | def write_file_list ( filename , file_list = [ ] , glob = None ) : if glob : file_list = iglob ( glob ) with open ( filename , 'w' ) as f : for line in file_list : f . write ( line + '\n' ) | Write a list of files to a file . |
250,304 | def file_variations ( filename , extensions ) : ( label , ext ) = splitext ( filename ) return [ label + extention for extention in extensions ] | Create a variation of file names . |
250,305 | def insert ( self , key , value , data = { } ) : if value < self . min_value or value > self . max_value : raise BoundsError ( 'item value out of bounds' ) item = self . Item ( key , value , data ) index = self . get_bin_index ( value ) self . bins [ index ] . append ( item ) | Insert the key into a bin based on the given value . |
250,306 | def iterkeys ( self ) : def _iterkeys ( bin ) : for item in bin : yield item . key for bin in self . bins : yield _iterkeys ( bin ) | An iterator over the keys of each bin . |
250,307 | def file_request ( self ) : response = requests . get ( self . __base_url , headers = self . __headers , stream = True ) return response . raw . read ( ) , response . headers | Request that retrieve a binary file |
250,308 | def get_signatures ( self , limit = 100 , offset = 0 , conditions = { } ) : url = self . SIGNS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection... | Get all signatures |
250,309 | def get_signature ( self , signature_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . SIGNS_ID_URL % signature_id ) return connection . get_request ( ) | Get a concrete Signature |
250,310 | def count_signatures ( self , conditions = { } ) : url = self . SIGNS_COUNT_URL + '?' for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection .... | Count all signatures |
250,311 | def cancel_signature ( self , signature_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . SIGNS_CANCEL_URL % signature_id ) return connection . patch_request ( ) | Cancel a concrete Signature |
250,312 | def send_signature_reminder ( self , signature_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . SIGNS_SEND_REMINDER_URL % signature_id ) return connection . post_request ( ) | Send a reminder email |
250,313 | def get_branding ( self , branding_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . BRANDINGS_ID_URL % branding_id ) return connection . get_request ( ) | Get a concrete branding |
250,314 | def get_brandings ( self ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . BRANDINGS_URL ) return connection . get_request ( ) | Get all account brandings |
250,315 | def create_branding ( self , params ) : connection = Connection ( self . token ) connection . add_header ( 'Content-Type' , 'application/json' ) connection . set_url ( self . production , self . BRANDINGS_URL ) connection . add_params ( params , json_format = True ) return connection . post_request ( ) | Create a new branding |
250,316 | def update_branding ( self , branding_id , params ) : connection = Connection ( self . token ) connection . add_header ( 'Content-Type' , 'application/json' ) connection . set_url ( self . production , self . BRANDINGS_ID_URL % branding_id ) connection . add_params ( params ) return connection . patch_request ( ) | Update a existing branding |
250,317 | def get_templates ( self , limit = 100 , offset = 0 ) : url = self . TEMPLATES_URL + "?limit=%s&offset=%s" % ( limit , offset ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all account templates |
250,318 | def get_emails ( self , limit = 100 , offset = 0 , conditions = { } ) : url = self . EMAILS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . ... | Get all certified emails |
250,319 | def count_emails ( self , conditions = { } ) : url = self . EMAILS_COUNT_URL + "?" for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) connection . set_url (... | Count all certified emails |
250,320 | def get_email ( self , email_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . EMAILS_ID_URL % email_id ) return connection . get_request ( ) | Get a specific email |
250,321 | def count_SMS ( self , conditions = { } ) : url = self . SMS_COUNT_URL + "?" for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) connection . set_url ( self ... | Count all certified sms |
250,322 | def get_SMS ( self , limit = 100 , offset = 0 , conditions = { } ) : url = self . SMS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in conditions . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_ur... | Get all certified sms |
250,323 | def get_single_SMS ( self , sms_id ) : connection = Connection ( self . token ) connection . set_url ( self . production , self . SMS_ID_URL % sms_id ) return connection . get_request ( ) | Get a specific sms |
250,324 | def create_SMS ( self , files , recipients , body , params = { } ) : parameters = { } parser = Parser ( ) documents = { } parser . fill_array ( documents , files , 'files' ) recipients = recipients if isinstance ( recipients , list ) else [ recipients ] index = 0 for recipient in recipients : parser . fill_array ( para... | Create a new certified sms |
250,325 | def get_users ( self , limit = 100 , offset = 0 ) : url = self . TEAM_USERS_URL + "?limit=%s&offset=%s" % ( limit , offset ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all users from your current team |
250,326 | def get_seats ( self , limit = 100 , offset = 0 ) : url = self . TEAM_SEATS_URL + "?limit=%s&offset=%s" % ( limit , offset ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all seats from your current team |
250,327 | def get_groups ( self , limit = 100 , offset = 0 ) : url = self . TEAM_GROUPS_URL + "?limit=%s&offset=%s" % ( limit , offset ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get all groups from your current team |
250,328 | def get_subscriptions ( self , limit = 100 , offset = 0 , params = { } ) : url = self . SUBSCRIPTIONS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in params . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connect... | Get all subscriptions |
250,329 | def count_subscriptions ( self , params = { } ) : url = self . SUBSCRIPTIONS_COUNT_URL + '?' for key , value in params . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connectio... | Count all subscriptions |
250,330 | def get_subscription ( self , subscription_id ) : url = self . SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get single subscription |
250,331 | def delete_subscription ( self , subscription_id ) : url = self . SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . delete_request ( ) | Delete single subscription |
250,332 | def get_contacts ( self , limit = 100 , offset = 0 , params = { } ) : url = self . CONTACTS_URL + "?limit=%s&offset=%s" % ( limit , offset ) for key , value in params . items ( ) : if key is 'ids' : value = "," . join ( value ) url += '&%s=%s' % ( key , value ) connection = Connection ( self . token ) connection . set_... | Get all account contacts |
250,333 | def get_contact ( self , contact_id ) : url = self . CONTACTS_ID_URL % contact_id connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . get_request ( ) | Get single contact |
250,334 | def delete_contact ( self , contact_id ) : url = self . CONTACTS_ID_URL % contact_id connection = Connection ( self . token ) connection . set_url ( self . production , url ) return connection . delete_request ( ) | Delete single contact |
250,335 | def main ( ) : logging . captureWarnings ( True ) logging . basicConfig ( format = ( '%(asctime)s - %(name)s - %(levelname)s - ' + '%(message)s' ) , level = logging . INFO ) args = [ 3 , 5 , 10 , 20 ] intermediate_results = grid_map ( computeFactorial , args , quiet = False , max_processes = 4 , queue = 'all.q' ) print... | execute map example |
250,336 | def main ( ) : logging . captureWarnings ( True ) logging . basicConfig ( format = ( '%(asctime)s - %(name)s - %(levelname)s - ' + '%(message)s' ) , level = logging . INFO ) print ( "=====================================" ) print ( "======== Submit and Wait ========" ) print ( "=====================================... | run a set of jobs on cluster |
250,337 | def execute_cmd ( cmd , ** kwargs ) : yield '$ {}\n' . format ( ' ' . join ( cmd ) ) kwargs [ 'stdout' ] = subprocess . PIPE kwargs [ 'stderr' ] = subprocess . STDOUT proc = subprocess . Popen ( cmd , ** kwargs ) buf = [ ] def flush ( ) : line = b'' . join ( buf ) . decode ( 'utf8' , 'replace' ) buf [ : ] = [ ] return ... | Call given command yielding output line by line |
250,338 | def main ( ) : logging . basicConfig ( format = '[%(asctime)s] %(levelname)s -- %(message)s' , level = logging . DEBUG ) parser = argparse . ArgumentParser ( description = 'Synchronizes a github repository with a local repository.' ) parser . add_argument ( 'git_url' , help = 'Url of the repo to sync' ) parser . add_ar... | Synchronizes a github repository with a local repository . |
250,339 | def pull ( self ) : if not os . path . exists ( self . repo_dir ) : yield from self . initialize_repo ( ) else : yield from self . update ( ) | Pull selected repo from a remote git repository while preserving user changes |
250,340 | def initialize_repo ( self ) : logging . info ( 'Repo {} doesn\'t exist. Cloning...' . format ( self . repo_dir ) ) clone_args = [ 'git' , 'clone' ] if self . depth and self . depth > 0 : clone_args . extend ( [ '--depth' , str ( self . depth ) ] ) clone_args . extend ( [ '--branch' , self . branch_name ] ) clone_args ... | Clones repository & sets up usernames . |
250,341 | def repo_is_dirty ( self ) : try : subprocess . check_call ( [ 'git' , 'diff-files' , '--quiet' ] , cwd = self . repo_dir ) return False except subprocess . CalledProcessError : return True | Return true if repo is dirty |
250,342 | def find_upstream_changed ( self , kind ) : output = subprocess . check_output ( [ 'git' , 'log' , '{}..origin/{}' . format ( self . branch_name , self . branch_name ) , '--oneline' , '--name-status' ] , cwd = self . repo_dir ) . decode ( ) files = [ ] for line in output . split ( '\n' ) : if line . startswith ( kind )... | Return list of files that have been changed upstream belonging to a particular kind of change |
250,343 | def rename_local_untracked ( self ) : new_upstream_files = self . find_upstream_changed ( 'A' ) for f in new_upstream_files : if os . path . exists ( f ) : ts = datetime . datetime . now ( ) . strftime ( '__%Y%m%d%H%M%S' ) path_head , path_tail = os . path . split ( f ) path_tail = ts . join ( os . path . splitext ( pa... | Rename local untracked files that would require pulls |
250,344 | def update ( self ) : yield from self . update_remotes ( ) yield from self . rename_local_untracked ( ) yield from self . reset_deleted_files ( ) if self . repo_is_dirty ( ) : yield from self . ensure_lock ( ) yield from execute_cmd ( [ 'git' , 'commit' , '-am' , 'WIP' , '--allow-empty' ] , cwd = self . repo_dir ) yiel... | Do the pulling if necessary |
250,345 | def _get_footer_size ( file_obj ) : file_obj . seek ( - 8 , 2 ) tup = struct . unpack ( b"<i" , file_obj . read ( 4 ) ) return tup [ 0 ] | Read the footer size in bytes which is serialized as little endian . |
250,346 | def _read_footer ( file_obj ) : footer_size = _get_footer_size ( file_obj ) if logger . isEnabledFor ( logging . DEBUG ) : logger . debug ( "Footer size in bytes: %s" , footer_size ) file_obj . seek ( - ( 8 + footer_size ) , 2 ) tin = TFileTransport ( file_obj ) pin = TCompactProtocolFactory ( ) . get_protocol ( tin ) ... | Read the footer from the given file object and returns a FileMetaData object . |
250,347 | def _read_page_header ( file_obj ) : tin = TFileTransport ( file_obj ) pin = TCompactProtocolFactory ( ) . get_protocol ( tin ) page_header = parquet_thrift . PageHeader ( ) page_header . read ( pin ) return page_header | Read the page_header from the given fo . |
250,348 | def read_footer ( filename ) : with open ( filename , 'rb' ) as file_obj : if not _check_header_magic_bytes ( file_obj ) or not _check_footer_magic_bytes ( file_obj ) : raise ParquetFormatException ( "{0} is not a valid parquet file " "(missing magic bytes)" . format ( filename ) ) return _read_footer ( file_obj ) | Read the footer and return the FileMetaData for the specified filename . |
250,349 | def _get_offset ( cmd ) : dict_offset = cmd . dictionary_page_offset data_offset = cmd . data_page_offset if dict_offset is None or data_offset < dict_offset : return data_offset return dict_offset | Return the offset into the cmd based upon if it s a dictionary page or a data page . |
250,350 | def _read_data ( file_obj , fo_encoding , value_count , bit_width ) : vals = [ ] if fo_encoding == parquet_thrift . Encoding . RLE : seen = 0 while seen < value_count : values = encoding . read_rle_bit_packed_hybrid ( file_obj , bit_width ) if values is None : break vals += values seen += len ( values ) elif fo_encodin... | Read data from the file - object using the given encoding . |
250,351 | def _read_dictionary_page ( file_obj , schema_helper , page_header , column_metadata ) : raw_bytes = _read_page ( file_obj , page_header , column_metadata ) io_obj = io . BytesIO ( raw_bytes ) values = encoding . read_plain ( io_obj , column_metadata . type , page_header . dictionary_page_header . num_values ) schema_e... | Read a page containing dictionary data . |
250,352 | def _dump ( file_obj , options , out = sys . stdout ) : total_count = 0 writer = None keys = None for row in DictReader ( file_obj , options . col ) : if not keys : keys = row . keys ( ) if not writer : writer = csv . DictWriter ( out , keys , delimiter = u'\t' , quotechar = u'\'' , quoting = csv . QUOTE_MINIMAL ) if o... | Dump to fo with given options . |
250,353 | def dump ( filename , options , out = sys . stdout ) : with open ( filename , 'rb' ) as file_obj : return _dump ( file_obj , options = options , out = out ) | Dump parquet file with given filename using options to out . |
250,354 | def writerow ( self , row ) : json_text = json . dumps ( row ) if isinstance ( json_text , bytes ) : json_text = json_text . decode ( 'utf-8' ) self . _out . write ( json_text ) self . _out . write ( u'\n' ) | Write a single row . |
250,355 | def read_plain_boolean ( file_obj , count ) : return read_bitpacked ( file_obj , count << 1 , 1 , logger . isEnabledFor ( logging . DEBUG ) ) | Read count booleans using the plain encoding . |
250,356 | def read_plain_int32 ( file_obj , count ) : length = 4 * count data = file_obj . read ( length ) if len ( data ) != length : raise EOFError ( "Expected {} bytes but got {} bytes" . format ( length , len ( data ) ) ) res = struct . unpack ( "<{}i" . format ( count ) . encode ( "utf-8" ) , data ) return res | Read count 32 - bit ints using the plain encoding . |
250,357 | def read_plain_int64 ( file_obj , count ) : return struct . unpack ( "<{}q" . format ( count ) . encode ( "utf-8" ) , file_obj . read ( 8 * count ) ) | Read count 64 - bit ints using the plain encoding . |
250,358 | def read_plain_int96 ( file_obj , count ) : items = struct . unpack ( b"<" + b"qi" * count , file_obj . read ( 12 * count ) ) return [ q << 32 | i for ( q , i ) in zip ( items [ 0 : : 2 ] , items [ 1 : : 2 ] ) ] | Read count 96 - bit ints using the plain encoding . |
250,359 | def read_plain_float ( file_obj , count ) : return struct . unpack ( "<{}f" . format ( count ) . encode ( "utf-8" ) , file_obj . read ( 4 * count ) ) | Read count 32 - bit floats using the plain encoding . |
250,360 | def read_plain_byte_array ( file_obj , count ) : return [ file_obj . read ( struct . unpack ( b"<i" , file_obj . read ( 4 ) ) [ 0 ] ) for i in range ( count ) ] | Read count byte arrays using the plain encoding . |
250,361 | def read_plain ( file_obj , type_ , count ) : if count == 0 : return [ ] conv = DECODE_PLAIN [ type_ ] return conv ( file_obj , count ) | Read count items type from the fo using the plain encoding . |
250,362 | def read_unsigned_var_int ( file_obj ) : result = 0 shift = 0 while True : byte = struct . unpack ( b"<B" , file_obj . read ( 1 ) ) [ 0 ] result |= ( ( byte & 0x7F ) << shift ) if ( byte & 0x80 ) == 0 : break shift += 7 return result | Read a value using the unsigned variable int encoding . |
250,363 | def read_rle ( file_obj , header , bit_width , debug_logging ) : count = header >> 1 zero_data = b"\x00\x00\x00\x00" width = ( bit_width + 7 ) // 8 data = file_obj . read ( width ) data = data + zero_data [ len ( data ) : ] value = struct . unpack ( b"<i" , data ) [ 0 ] if debug_logging : logger . debug ( "Read RLE gro... | Read a run - length encoded run from the given fo with the given header and bit_width . |
250,364 | def read_bitpacked_deprecated ( file_obj , byte_count , count , width , debug_logging ) : raw_bytes = array . array ( ARRAY_BYTE_STR , file_obj . read ( byte_count ) ) . tolist ( ) mask = _mask_for_bits ( width ) index = 0 res = [ ] word = 0 bits_in_word = 0 while len ( res ) < count and index <= len ( raw_bytes ) : if... | Read count values from fo using the deprecated bitpacking encoding . |
250,365 | def _convert_unsigned ( data , fmt ) : num = len ( data ) return struct . unpack ( "{}{}" . format ( num , fmt . upper ( ) ) . encode ( "utf-8" ) , struct . pack ( "{}{}" . format ( num , fmt ) . encode ( "utf-8" ) , * data ) ) | Convert data from signed to unsigned in bulk . |
250,366 | def convert_column ( data , schemae ) : ctype = schemae . converted_type if ctype == parquet_thrift . ConvertedType . DECIMAL : scale_factor = Decimal ( "10e-{}" . format ( schemae . scale ) ) if schemae . type == parquet_thrift . Type . INT32 or schemae . type == parquet_thrift . Type . INT64 : return [ Decimal ( unsc... | Convert known types from primitive to rich . |
250,367 | def setup_logging ( options = None ) : level = logging . DEBUG if options is not None and options . debug else logging . WARNING console = logging . StreamHandler ( ) console . setLevel ( level ) formatter = logging . Formatter ( '%(name)s: %(levelname)-8s %(message)s' ) console . setFormatter ( formatter ) logging . g... | Configure logging based on options . |
250,368 | def main ( argv = None ) : argv = argv or sys . argv [ 1 : ] parser = argparse . ArgumentParser ( 'parquet' , description = 'Read parquet files' ) parser . add_argument ( '--metadata' , action = 'store_true' , help = 'show metadata on file' ) parser . add_argument ( '--row-group-metadata' , action = 'store_true' , help... | Run parquet utility application . |
250,369 | def is_required ( self , name ) : return self . schema_element ( name ) . repetition_type == parquet_thrift . FieldRepetitionType . REQUIRED | Return true iff the schema element with the given name is required . |
250,370 | def max_repetition_level ( self , path ) : max_level = 0 for part in path : element = self . schema_element ( part ) if element . repetition_type == parquet_thrift . FieldRepetitionType . REQUIRED : max_level += 1 return max_level | Get the max repetition level for the given schema path . |
250,371 | def execute ( self , using = None ) : if not using : using = self . getConnection ( ) insertedEntities = { } for klass in self . orders : number = self . quantities [ klass ] if klass not in insertedEntities : insertedEntities [ klass ] = [ ] for i in range ( 0 , number ) : insertedEntities [ klass ] . append ( self . ... | Populate the database using all the Entity classes previously added . |
250,372 | def getGenerator ( cls , locale = None , providers = None , codename = None ) : codename = codename or cls . getCodename ( locale , providers ) if codename not in cls . generators : from faker import Faker as FakerGenerator cls . generators [ codename ] = FakerGenerator ( locale , providers ) cls . generators [ codenam... | use a codename to cache generators |
250,373 | def _point_in_bbox ( point , bounds ) : return not ( point [ 'coordinates' ] [ 1 ] < bounds [ 0 ] or point [ 'coordinates' ] [ 1 ] > bounds [ 2 ] or point [ 'coordinates' ] [ 0 ] < bounds [ 1 ] or point [ 'coordinates' ] [ 0 ] > bounds [ 3 ] ) | valid whether the point is inside the bounding box |
250,374 | def point_in_polygon ( point , poly ) : coords = [ poly [ 'coordinates' ] ] if poly [ 'type' ] == 'Polygon' else poly [ 'coordinates' ] return _point_in_polygon ( point , coords ) | valid whether the point is located in a polygon |
250,375 | def draw_circle ( radius_in_meters , center_point , steps = 15 ) : steps = steps if steps > 15 else 15 center = [ center_point [ 'coordinates' ] [ 1 ] , center_point [ 'coordinates' ] [ 0 ] ] dist = ( radius_in_meters / 1000 ) / 6371 rad_center = [ number2radius ( center [ 0 ] ) , number2radius ( center [ 1 ] ) ] poly ... | get a circle shape polygon based on centerPoint and radius |
250,376 | def rectangle_centroid ( rectangle ) : bbox = rectangle [ 'coordinates' ] [ 0 ] xmin = bbox [ 0 ] [ 0 ] ymin = bbox [ 0 ] [ 1 ] xmax = bbox [ 2 ] [ 0 ] ymax = bbox [ 2 ] [ 1 ] xwidth = xmax - xmin ywidth = ymax - ymin return { 'type' : 'Point' , 'coordinates' : [ xmin + xwidth / 2 , ymin + ywidth / 2 ] } | get the centroid of the rectangle |
250,377 | def geometry_within_radius ( geometry , center , radius ) : if geometry [ 'type' ] == 'Point' : return point_distance ( geometry , center ) <= radius elif geometry [ 'type' ] == 'LineString' or geometry [ 'type' ] == 'Polygon' : point = { } coordinates = geometry [ 'coordinates' ] [ 0 ] if geometry [ 'type' ] == 'Polyg... | To valid whether point or linestring or polygon is inside a radius around a center |
250,378 | def area ( poly ) : poly_area = 0 points = poly [ 'coordinates' ] [ 0 ] j = len ( points ) - 1 count = len ( points ) for i in range ( 0 , count ) : p1_x = points [ i ] [ 1 ] p1_y = points [ i ] [ 0 ] p2_x = points [ j ] [ 1 ] p2_y = points [ j ] [ 0 ] poly_area += p1_x * p2_y poly_area -= p1_y * p2_x j = i poly_area /... | calculate the area of polygon |
250,379 | def destination_point ( point , brng , dist ) : dist = float ( dist ) / 6371 brng = number2radius ( brng ) lon1 = number2radius ( point [ 'coordinates' ] [ 0 ] ) lat1 = number2radius ( point [ 'coordinates' ] [ 1 ] ) lat2 = math . asin ( math . sin ( lat1 ) * math . cos ( dist ) + math . cos ( lat1 ) * math . sin ( dis... | Calculate a destination Point base on a base point and a distance |
250,380 | def merge_featurecollection ( * jsons ) : features = [ ] for json in jsons : if json [ 'type' ] == 'FeatureCollection' : for feature in json [ 'features' ] : features . append ( feature ) return { "type" : 'FeatureCollection' , "features" : features } | merge features into one featurecollection |
250,381 | def trace_dispatch ( self , frame , event , arg ) : if hasattr ( self , 'vimpdb' ) : return self . vimpdb . trace_dispatch ( frame , event , arg ) else : return self . _orig_trace_dispatch ( frame , event , arg ) | allow to switch to Vimpdb instance |
250,382 | def hook ( klass ) : if not hasattr ( klass , 'do_vim' ) : setupMethod ( klass , trace_dispatch ) klass . __bases__ += ( SwitcherToVimpdb , ) | monkey - patch pdb . Pdb class |
250,383 | def trace_dispatch ( self , frame , event , arg ) : if hasattr ( self , 'pdb' ) : return self . pdb . trace_dispatch ( frame , event , arg ) else : return Pdb . trace_dispatch ( self , frame , event , arg ) | allow to switch to Pdb instance |
250,384 | def get_context_data ( self , ** kwargs ) : data = { } if self . _contextual_vals . current_level == 1 and self . max_levels > 1 : data [ 'sub_menu_template' ] = self . sub_menu_template . template . name data . update ( kwargs ) return super ( ) . get_context_data ( ** data ) | Include the name of the sub menu template in the context . This is purely for backwards compatibility . Any sub menus rendered as part of this menu will call sub_menu_template on the original menu instance to get an actual Template |
250,385 | def render_from_tag ( cls , context , max_levels = None , use_specific = None , apply_active_classes = True , allow_repeating_parents = True , use_absolute_page_urls = False , add_sub_menus_inline = None , template_name = '' , ** kwargs ) : instance = cls . _get_render_prepared_object ( context , max_levels = max_level... | A template tag should call this method to render a menu . The Context instance and option values provided are used to get or create a relevant menu instance prepare it then render it and it s menu items to an appropriate template . |
250,386 | def _create_contextualvals_obj_from_context ( cls , context ) : context_processor_vals = context . get ( 'wagtailmenus_vals' , { } ) return ContextualVals ( context , context [ 'request' ] , get_site_from_request ( context [ 'request' ] ) , context . get ( 'current_level' , 0 ) + 1 , context . get ( 'original_menu_tag'... | Gathers all of the contextual data needed to render a menu instance and returns it in a structure that can be conveniently referenced throughout the process of preparing the menu and menu items and for rendering . |
250,387 | def render_to_template ( self ) : context_data = self . get_context_data ( ) template = self . get_template ( ) context_data [ 'current_template' ] = template . template . name return template . render ( context_data ) | Render the current menu instance to a template and return a string |
250,388 | def get_common_hook_kwargs ( self , ** kwargs ) : opt_vals = self . _option_vals hook_kwargs = self . _contextual_vals . _asdict ( ) hook_kwargs . update ( { 'menu_instance' : self , 'menu_tag' : self . related_templatetag_name , 'parent_page' : None , 'max_levels' : self . max_levels , 'use_specific' : self . use_spec... | Returns a dictionary of common values to be passed as keyword arguments to methods registered as hooks . |
250,389 | def get_page_children_dict ( self , page_qs = None ) : children_dict = defaultdict ( list ) for page in page_qs or self . pages_for_display : children_dict [ page . path [ : - page . steplen ] ] . append ( page ) return children_dict | Returns a dictionary of lists where the keys are path values for pages and the value is a list of children pages for that page . |
250,390 | def get_context_data ( self , ** kwargs ) : ctx_vals = self . _contextual_vals opt_vals = self . _option_vals data = self . create_dict_from_parent_context ( ) data . update ( ctx_vals . _asdict ( ) ) data . update ( { 'apply_active_classes' : opt_vals . apply_active_classes , 'allow_repeating_parents' : opt_vals . all... | Return a dictionary containing all of the values needed to render the menu instance to a template including values that might be used by the sub_menu tag to render any additional levels . |
250,391 | def get_menu_items_for_rendering ( self ) : items = self . get_raw_menu_items ( ) for hook in hooks . get_hooks ( 'menus_modify_raw_menu_items' ) : items = hook ( items , ** self . common_hook_kwargs ) items = self . modify_menu_items ( self . prime_menu_items ( items ) ) if isinstance ( items , GeneratorType ) : items... | Return a list of menu items to be included in the context for rendering the current level of the menu . |
250,392 | def _replace_with_specific_page ( page , menu_item ) : if type ( page ) is Page : page = page . specific if isinstance ( menu_item , MenuItem ) : menu_item . link_page = page else : menu_item = page return page , menu_item | If page is a vanilla Page object replace it with a specific version of itself . Also update menu_item depending on whether it s a MenuItem object or a Page object . |
250,393 | def prime_menu_items ( self , menu_items ) : for item in menu_items : item = self . _prime_menu_item ( item ) if item is not None : yield item | A generator method that takes a list of MenuItem or Page objects and sets a number of additional attributes on each item that are useful in menu templates . |
250,394 | def get_children_for_page ( self , page ) : if self . max_levels == 1 : return self . pages_for_display return super ( ) . get_children_for_page ( page ) | Return a list of relevant child pages for a given page |
250,395 | def get_top_level_items ( self ) : menu_items = self . get_base_menuitem_queryset ( ) page_ids = tuple ( obj . link_page_id for obj in menu_items if obj . link_page_id ) page_dict = { } if page_ids : top_level_pages = self . get_base_page_queryset ( ) . filter ( id__in = page_ids ) if self . use_specific >= constants .... | Return a list of menu items with link_page objects supplemented with specific pages where appropriate . |
250,396 | def get_for_site ( cls , site ) : instance , created = cls . objects . get_or_create ( site = site ) return instance | Return the main menu instance for the provided site |
250,397 | def get_form_kwargs ( self ) : kwargs = super ( ) . get_form_kwargs ( ) if self . request . method == 'POST' : data = copy ( self . request . POST ) i = 0 while ( data . get ( '%s-%s-id' % ( settings . FLAT_MENU_ITEMS_RELATED_NAME , i ) ) ) : data [ '%s-%s-id' % ( settings . FLAT_MENU_ITEMS_RELATED_NAME , i ) ] = None ... | When the form is posted don t pass an instance to the form . It should create a new one out of the posted data . We also need to nullify any IDs posted for inline menu items so that new instances of those are created too . |
250,398 | def modify_submenu_items ( self , menu_items , current_page , current_ancestor_ids , current_site , allow_repeating_parents , apply_active_classes , original_menu_tag , menu_instance = None , request = None , use_absolute_page_urls = False , ) : if ( allow_repeating_parents and menu_items and self . repeat_in_subnav ) ... | Make any necessary modifications to menu_items and return the list back to the calling menu tag to render in templates . Any additional items added should have a text and href attribute as a minimum . |
250,399 | def has_submenu_items ( self , current_page , allow_repeating_parents , original_menu_tag , menu_instance = None , request = None ) : return menu_instance . page_has_children ( self ) | When rendering pages in a menu template a has_children_in_menu attribute is added to each page letting template developers know whether or not the item has a submenu that must be rendered . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.