idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
13,200 | def get_tileset_from_gid ( self , gid ) : try : tiled_gid = self . tiledgidmap [ gid ] except KeyError : raise ValueError for tileset in sorted ( self . tilesets , key = attrgetter ( 'firstgid' ) , reverse = True ) : if tiled_gid >= tileset . firstgid : return tileset raise ValueError | Return tileset that owns the gid |
13,201 | def visible_tile_layers ( self ) : return ( i for ( i , l ) in enumerate ( self . layers ) if l . visible and isinstance ( l , TiledTileLayer ) ) | Return iterator of layer indexes that are set visible |
13,202 | def visible_object_groups ( self ) : return ( i for ( i , l ) in enumerate ( self . layers ) if l . visible and isinstance ( l , TiledObjectGroup ) ) | Return iterator of object group indexes that are set visible |
13,203 | def register_gid ( self , tiled_gid , flags = None ) : if flags is None : flags = TileFlags ( 0 , 0 , 0 ) if tiled_gid : try : return self . imagemap [ ( tiled_gid , flags ) ] [ 0 ] except KeyError : gid = self . maxgid self . maxgid += 1 self . imagemap [ ( tiled_gid , flags ) ] = ( gid , flags ) self . gidmap [ tiled_gid ] . append ( ( gid , flags ) ) self . tiledgidmap [ gid ] = tiled_gid return gid else : return 0 | Used to manage the mapping of GIDs between the tmx and pytmx |
13,204 | def map_gid ( self , tiled_gid ) : try : return self . gidmap [ int ( tiled_gid ) ] except KeyError : return None except TypeError : msg = "GIDs must be an integer" logger . debug ( msg ) raise TypeError | Used to lookup a GID read from a TMX file s data |
13,205 | def map_gid2 ( self , tiled_gid ) : tiled_gid = int ( tiled_gid ) if tiled_gid in self . gidmap : return self . gidmap [ tiled_gid ] else : gid = self . register_gid ( tiled_gid ) return [ ( gid , None ) ] | WIP . need to refactor the gid code |
13,206 | def iter_data ( self ) : for y , row in enumerate ( self . data ) : for x , gid in enumerate ( row ) : yield x , y , gid | Iterate over layer data |
13,207 | def tiles ( self ) : images = self . parent . images for x , y , gid in [ i for i in self . iter_data ( ) if i [ 2 ] ] : yield x , y , images [ gid ] | Iterate over tile images of this layer |
13,208 | def parse_xml ( self , node ) : import struct import array self . _set_properties ( node ) data = None next_gid = None data_node = node . find ( 'data' ) encoding = data_node . get ( 'encoding' , None ) if encoding == 'base64' : from base64 import b64decode data = b64decode ( data_node . text . strip ( ) ) elif encoding == 'csv' : next_gid = map ( int , "" . join ( line . strip ( ) for line in data_node . text . strip ( ) ) . split ( "," ) ) elif encoding : msg = 'TMX encoding type: {0} is not supported.' logger . error ( msg . format ( encoding ) ) raise Exception compression = data_node . get ( 'compression' , None ) if compression == 'gzip' : import gzip with gzip . GzipFile ( fileobj = six . BytesIO ( data ) ) as fh : data = fh . read ( ) elif compression == 'zlib' : import zlib data = zlib . decompress ( data ) elif compression : msg = 'TMX compression type: {0} is not supported.' logger . error ( msg . format ( compression ) ) raise Exception if encoding == next_gid is None : def get_children ( parent ) : for child in parent . findall ( 'tile' ) : yield int ( child . get ( 'gid' ) ) next_gid = get_children ( data_node ) elif data : if type ( data ) == bytes : fmt = struct . Struct ( '<L' ) iterator = ( data [ i : i + 4 ] for i in range ( 0 , len ( data ) , 4 ) ) next_gid = ( fmt . unpack ( i ) [ 0 ] for i in iterator ) else : msg = 'layer data not in expected format ({})' logger . error ( msg . format ( type ( data ) ) ) raise Exception init = lambda : [ 0 ] * self . width reg = self . parent . register_gid self . data = tuple ( array . array ( 'H' , init ( ) ) for i in range ( self . height ) ) for ( y , x ) in product ( range ( self . height ) , range ( self . width ) ) : self . data [ y ] [ x ] = reg ( * decode_gid ( next ( next_gid ) ) ) return self | Parse a Tile Layer from ElementTree xml node |
13,209 | def parse_xml ( self , node ) : self . _set_properties ( node ) self . extend ( TiledObject ( self . parent , child ) for child in node . findall ( 'object' ) ) return self | Parse an Object Group from ElementTree xml node |
13,210 | def parse_xml ( self , node ) : def read_points ( text ) : return tuple ( tuple ( map ( float , i . split ( ',' ) ) ) for i in text . split ( ) ) self . _set_properties ( node ) if self . gid : self . gid = self . parent . register_gid ( self . gid ) points = None polygon = node . find ( 'polygon' ) if polygon is not None : points = read_points ( polygon . get ( 'points' ) ) self . closed = True polyline = node . find ( 'polyline' ) if polyline is not None : points = read_points ( polyline . get ( 'points' ) ) self . closed = False if points : x1 = x2 = y1 = y2 = 0 for x , y in points : if x < x1 : x1 = x if x > x2 : x2 = x if y < y1 : y1 = y if y > y2 : y2 = y self . width = abs ( x1 ) + abs ( x2 ) self . height = abs ( y1 ) + abs ( y2 ) self . points = tuple ( [ ( i [ 0 ] + self . x , i [ 1 ] + self . y ) for i in points ] ) return self | Parse an Object from ElementTree xml node |
13,211 | def parse_xml ( self , node ) : self . _set_properties ( node ) self . name = node . get ( 'name' , None ) self . opacity = node . get ( 'opacity' , self . opacity ) self . visible = node . get ( 'visible' , self . visible ) image_node = node . find ( 'image' ) self . source = image_node . get ( 'source' , None ) self . trans = image_node . get ( 'trans' , None ) return self | Parse an Image Layer from ElementTree xml node |
13,212 | def smart_convert ( original , colorkey , pixelalpha ) : tile_size = original . get_size ( ) threshold = 127 try : px = pygame . mask . from_surface ( original , threshold ) . count ( ) except : return original . convert_alpha ( ) if px == tile_size [ 0 ] * tile_size [ 1 ] : tile = original . convert ( ) elif colorkey : tile = original . convert ( ) tile . set_colorkey ( colorkey , pygame . RLEACCEL ) elif pixelalpha : tile = original . convert_alpha ( ) else : tile = original . convert ( ) return tile | this method does several tests on a surface to determine the optimal flags and pixel format for each tile surface . |
13,213 | def pygame_image_loader ( filename , colorkey , ** kwargs ) : if colorkey : colorkey = pygame . Color ( '#{0}' . format ( colorkey ) ) pixelalpha = kwargs . get ( 'pixelalpha' , True ) image = pygame . image . load ( filename ) def load_image ( rect = None , flags = None ) : if rect : try : tile = image . subsurface ( rect ) except ValueError : logger . error ( 'Tile bounds outside bounds of tileset image' ) raise else : tile = image . copy ( ) if flags : tile = handle_transformation ( tile , flags ) tile = smart_convert ( tile , colorkey , pixelalpha ) return tile return load_image | pytmx image loader for pygame |
13,214 | def load_pygame ( filename , * args , ** kwargs ) : kwargs [ 'image_loader' ] = pygame_image_loader return pytmx . TiledMap ( filename , * args , ** kwargs ) | Load a TMX file images and return a TiledMap class |
13,215 | def build_rects ( tmxmap , layer , tileset = None , real_gid = None ) : if isinstance ( tileset , int ) : try : tileset = tmxmap . tilesets [ tileset ] except IndexError : msg = "Tileset #{0} not found in map {1}." logger . debug ( msg . format ( tileset , tmxmap ) ) raise IndexError elif isinstance ( tileset , str ) : try : tileset = [ t for t in tmxmap . tilesets if t . name == tileset ] . pop ( ) except IndexError : msg = "Tileset \"{0}\" not found in map {1}." logger . debug ( msg . format ( tileset , tmxmap ) ) raise ValueError elif tileset : msg = "Tileset must be either a int or string. got: {0}" logger . debug ( msg . format ( type ( tileset ) ) ) raise TypeError gid = None if real_gid : try : gid , flags = tmxmap . map_gid ( real_gid ) [ 0 ] except IndexError : msg = "GID #{0} not found" logger . debug ( msg . format ( real_gid ) ) raise ValueError if isinstance ( layer , int ) : layer_data = tmxmap . get_layer_data ( layer ) elif isinstance ( layer , str ) : try : layer = [ l for l in tmxmap . layers if l . name == layer ] . pop ( ) layer_data = layer . data except IndexError : msg = "Layer \"{0}\" not found in map {1}." logger . debug ( msg . format ( layer , tmxmap ) ) raise ValueError p = itertools . product ( range ( tmxmap . width ) , range ( tmxmap . height ) ) if gid : points = [ ( x , y ) for ( x , y ) in p if layer_data [ y ] [ x ] == gid ] else : points = [ ( x , y ) for ( x , y ) in p if layer_data [ y ] [ x ] ] rects = simplify ( points , tmxmap . tilewidth , tmxmap . tileheight ) return rects | generate a set of non - overlapping rects that represents the distribution of the specified gid . |
13,216 | def pyglet_image_loader ( filename , colorkey , ** kwargs ) : if colorkey : logger . debug ( 'colorkey not implemented' ) image = pyglet . image . load ( filename ) def load_image ( rect = None , flags = None ) : if rect : try : x , y , w , h = rect y = image . height - y - h tile = image . get_region ( x , y , w , h ) except : logger . error ( 'cannot get region %s of image' , rect ) raise else : tile = image if flags : logger . error ( 'tile flags are not implemented' ) return tile return load_image | basic image loading with pyglet |
13,217 | def reduce_wind_speed ( wind_speed , wind_efficiency_curve_name = 'dena_mean' ) : r wind_efficiency_curve = get_wind_efficiency_curve ( curve_name = wind_efficiency_curve_name ) reduced_wind_speed = wind_speed * np . interp ( wind_speed , wind_efficiency_curve [ 'wind_speed' ] , wind_efficiency_curve [ 'efficiency' ] ) return reduced_wind_speed | r Reduces wind speed by a wind efficiency curve . |
13,218 | def get_weather_data ( filename = 'weather.csv' , ** kwargs ) : r if 'datapath' not in kwargs : kwargs [ 'datapath' ] = os . path . join ( os . path . split ( os . path . dirname ( __file__ ) ) [ 0 ] , 'example' ) file = os . path . join ( kwargs [ 'datapath' ] , filename ) weather_df = pd . read_csv ( file , index_col = 0 , header = [ 0 , 1 ] , date_parser = lambda idx : pd . to_datetime ( idx , utc = True ) ) weather_df . index = pd . to_datetime ( weather_df . index ) . tz_convert ( 'Europe/Berlin' ) weather_df . columns = [ weather_df . axes [ 1 ] . levels [ 0 ] [ weather_df . axes [ 1 ] . codes [ 0 ] ] , weather_df . axes [ 1 ] . levels [ 1 ] [ weather_df . axes [ 1 ] . codes [ 1 ] ] . astype ( int ) ] return weather_df | r Imports weather data from a file . |
13,219 | def run_example ( ) : r weather = get_weather_data ( 'weather.csv' ) my_turbine , e126 , dummy_turbine = initialize_wind_turbines ( ) calculate_power_output ( weather , my_turbine , e126 , dummy_turbine ) plot_or_print ( my_turbine , e126 , dummy_turbine ) | r Runs the basic example . |
13,220 | def mean_hub_height ( self ) : r self . hub_height = np . exp ( sum ( np . log ( wind_dict [ 'wind_turbine' ] . hub_height ) * wind_dict [ 'wind_turbine' ] . nominal_power * wind_dict [ 'number_of_turbines' ] for wind_dict in self . wind_turbine_fleet ) / self . get_installed_power ( ) ) return self | r Calculates the mean hub height of the wind farm . |
13,221 | def logarithmic_profile ( wind_speed , wind_speed_height , hub_height , roughness_length , obstacle_height = 0.0 ) : r if 0.7 * obstacle_height > wind_speed_height : raise ValueError ( "To take an obstacle height of {0} m " . format ( obstacle_height ) + "into consideration, wind " + "speed data of a greater height is needed." ) if ( isinstance ( wind_speed , np . ndarray ) and isinstance ( roughness_length , pd . Series ) ) : roughness_length = np . array ( roughness_length ) return ( wind_speed * np . log ( ( hub_height - 0.7 * obstacle_height ) / roughness_length ) / np . log ( ( wind_speed_height - 0.7 * obstacle_height ) / roughness_length ) ) | r Calculates the wind speed at hub height using a logarithmic wind profile . |
13,222 | def hellman ( wind_speed , wind_speed_height , hub_height , roughness_length = None , hellman_exponent = None ) : r if hellman_exponent is None : if roughness_length is not None : if ( isinstance ( wind_speed , np . ndarray ) and isinstance ( roughness_length , pd . Series ) ) : roughness_length = np . array ( roughness_length ) hellman_exponent = 1 / np . log ( hub_height / roughness_length ) else : hellman_exponent = 1 / 7 return wind_speed * ( hub_height / wind_speed_height ) ** hellman_exponent | r Calculates the wind speed at hub height using the hellman equation . |
13,223 | def smooth_power_curve ( power_curve_wind_speeds , power_curve_values , block_width = 0.5 , wind_speed_range = 15.0 , standard_deviation_method = 'turbulence_intensity' , mean_gauss = 0 , ** kwargs ) : r if standard_deviation_method == 'turbulence_intensity' : if ( 'turbulence_intensity' in kwargs and kwargs [ 'turbulence_intensity' ] is not np . nan ) : normalized_standard_deviation = kwargs [ 'turbulence_intensity' ] else : raise ValueError ( "Turbulence intensity must be defined for " + "using 'turbulence_intensity' as " + "`standard_deviation_method`" ) elif standard_deviation_method == 'Staffell_Pfenninger' : normalized_standard_deviation = 0.2 else : raise ValueError ( "{} is no valid `standard_deviation_method`. Valid " + "options are 'turbulence_intensity', or " + "'Staffell_Pfenninger'" . format ( standard_deviation_method ) ) smoothed_power_curve_values = [ ] maximum_value = power_curve_wind_speeds . values [ - 1 ] + wind_speed_range while power_curve_wind_speeds . values [ - 1 ] < maximum_value : power_curve_wind_speeds = power_curve_wind_speeds . append ( pd . Series ( power_curve_wind_speeds . iloc [ - 1 ] + 0.5 , index = [ power_curve_wind_speeds . index [ - 1 ] + 1 ] ) ) power_curve_values = power_curve_values . append ( pd . Series ( 0.0 , index = [ power_curve_values . index [ - 1 ] + 1 ] ) ) for power_curve_wind_speed in power_curve_wind_speeds : wind_speeds_block = ( np . arange ( - wind_speed_range , wind_speed_range + block_width , block_width ) + power_curve_wind_speed ) standard_deviation = ( ( power_curve_wind_speed * normalized_standard_deviation + 0.6 ) if standard_deviation_method is 'Staffell_Pfenninger' else power_curve_wind_speed * normalized_standard_deviation ) if standard_deviation == 0.0 : smoothed_value = 0.0 else : smoothed_value = sum ( block_width * np . interp ( wind_speed , power_curve_wind_speeds , power_curve_values , left = 0 , right = 0 ) * tools . gauss_distribution ( power_curve_wind_speed - wind_speed , standard_deviation , mean_gauss ) for wind_speed in wind_speeds_block ) smoothed_power_curve_values . append ( smoothed_value ) smoothed_power_curve_df = pd . DataFrame ( data = [ list ( power_curve_wind_speeds . values ) , smoothed_power_curve_values ] ) . transpose ( ) smoothed_power_curve_df . columns = [ 'wind_speed' , 'value' ] return smoothed_power_curve_df | r Smooths the input power curve values by using a Gauss distribution . |
13,224 | def temperature_hub ( self , weather_df ) : r if self . power_plant . hub_height in weather_df [ 'temperature' ] : temperature_hub = weather_df [ 'temperature' ] [ self . power_plant . hub_height ] elif self . temperature_model == 'linear_gradient' : logging . debug ( 'Calculating temperature using temperature ' 'gradient.' ) closest_height = weather_df [ 'temperature' ] . columns [ min ( range ( len ( weather_df [ 'temperature' ] . columns ) ) , key = lambda i : abs ( weather_df [ 'temperature' ] . columns [ i ] - self . power_plant . hub_height ) ) ] temperature_hub = temperature . linear_gradient ( weather_df [ 'temperature' ] [ closest_height ] , closest_height , self . power_plant . hub_height ) elif self . temperature_model == 'interpolation_extrapolation' : logging . debug ( 'Calculating temperature using linear inter- or ' 'extrapolation.' ) temperature_hub = tools . linear_interpolation_extrapolation ( weather_df [ 'temperature' ] , self . power_plant . hub_height ) else : raise ValueError ( "'{0}' is an invalid value. " . format ( self . temperature_model ) + "`temperature_model` must be " "'linear_gradient' or 'interpolation_extrapolation'." ) return temperature_hub | r Calculates the temperature of air at hub height . |
13,225 | def density_hub ( self , weather_df ) : r if self . density_model != 'interpolation_extrapolation' : temperature_hub = self . temperature_hub ( weather_df ) if self . density_model == 'barometric' : logging . debug ( 'Calculating density using barometric height ' 'equation.' ) closest_height = weather_df [ 'pressure' ] . columns [ min ( range ( len ( weather_df [ 'pressure' ] . columns ) ) , key = lambda i : abs ( weather_df [ 'pressure' ] . columns [ i ] - self . power_plant . hub_height ) ) ] density_hub = density . barometric ( weather_df [ 'pressure' ] [ closest_height ] , closest_height , self . power_plant . hub_height , temperature_hub ) elif self . density_model == 'ideal_gas' : logging . debug ( 'Calculating density using ideal gas equation.' ) closest_height = weather_df [ 'pressure' ] . columns [ min ( range ( len ( weather_df [ 'pressure' ] . columns ) ) , key = lambda i : abs ( weather_df [ 'pressure' ] . columns [ i ] - self . power_plant . hub_height ) ) ] density_hub = density . ideal_gas ( weather_df [ 'pressure' ] [ closest_height ] , closest_height , self . power_plant . hub_height , temperature_hub ) elif self . density_model == 'interpolation_extrapolation' : logging . debug ( 'Calculating density using linear inter- or ' 'extrapolation.' ) density_hub = tools . linear_interpolation_extrapolation ( weather_df [ 'density' ] , self . power_plant . hub_height ) else : raise ValueError ( "'{0}' is an invalid value. " . format ( self . density_model ) + "`density_model` " + "must be 'barometric', 'ideal_gas' or " + "'interpolation_extrapolation'." ) return density_hub | r Calculates the density of air at hub height . |
13,226 | def wind_speed_hub ( self , weather_df ) : r if self . power_plant . hub_height in weather_df [ 'wind_speed' ] : wind_speed_hub = weather_df [ 'wind_speed' ] [ self . power_plant . hub_height ] elif self . wind_speed_model == 'logarithmic' : logging . debug ( 'Calculating wind speed using logarithmic wind ' 'profile.' ) closest_height = weather_df [ 'wind_speed' ] . columns [ min ( range ( len ( weather_df [ 'wind_speed' ] . columns ) ) , key = lambda i : abs ( weather_df [ 'wind_speed' ] . columns [ i ] - self . power_plant . hub_height ) ) ] wind_speed_hub = wind_speed . logarithmic_profile ( weather_df [ 'wind_speed' ] [ closest_height ] , closest_height , self . power_plant . hub_height , weather_df [ 'roughness_length' ] . iloc [ : , 0 ] , self . obstacle_height ) elif self . wind_speed_model == 'hellman' : logging . debug ( 'Calculating wind speed using hellman equation.' ) closest_height = weather_df [ 'wind_speed' ] . columns [ min ( range ( len ( weather_df [ 'wind_speed' ] . columns ) ) , key = lambda i : abs ( weather_df [ 'wind_speed' ] . columns [ i ] - self . power_plant . hub_height ) ) ] wind_speed_hub = wind_speed . hellman ( weather_df [ 'wind_speed' ] [ closest_height ] , closest_height , self . power_plant . hub_height , weather_df [ 'roughness_length' ] . iloc [ : , 0 ] , self . hellman_exp ) elif self . wind_speed_model == 'interpolation_extrapolation' : logging . debug ( 'Calculating wind speed using linear inter- or ' 'extrapolation.' ) wind_speed_hub = tools . linear_interpolation_extrapolation ( weather_df [ 'wind_speed' ] , self . power_plant . hub_height ) elif self . wind_speed_model == 'log_interpolation_extrapolation' : logging . debug ( 'Calculating wind speed using logarithmic inter- or ' 'extrapolation.' ) wind_speed_hub = tools . logarithmic_interpolation_extrapolation ( weather_df [ 'wind_speed' ] , self . power_plant . hub_height ) else : raise ValueError ( "'{0}' is an invalid value. " . format ( self . wind_speed_model ) + "`wind_speed_model` must be " "'logarithmic', 'hellman', 'interpolation_extrapolation' " + "or 'log_interpolation_extrapolation'." ) return wind_speed_hub | r Calculates the wind speed at hub height . |
13,227 | def calculate_power_output ( self , wind_speed_hub , density_hub ) : r if self . power_output_model == 'power_curve' : if self . power_plant . power_curve is None : raise TypeError ( "Power curve values of " + self . power_plant . name + " are missing." ) logging . debug ( 'Calculating power output using power curve.' ) return ( power_output . power_curve ( wind_speed_hub , self . power_plant . power_curve [ 'wind_speed' ] , self . power_plant . power_curve [ 'value' ] , density_hub , self . density_correction ) ) elif self . power_output_model == 'power_coefficient_curve' : if self . power_plant . power_coefficient_curve is None : raise TypeError ( "Power coefficient curve values of " + self . power_plant . name + " are missing." ) logging . debug ( 'Calculating power output using power coefficient ' 'curve.' ) return ( power_output . power_coefficient_curve ( wind_speed_hub , self . power_plant . power_coefficient_curve [ 'wind_speed' ] , self . power_plant . power_coefficient_curve [ 'value' ] , self . power_plant . rotor_diameter , density_hub ) ) else : raise ValueError ( "'{0}' is an invalid value. " . format ( self . power_output_model ) + "`power_output_model` must be " + "'power_curve' or 'power_coefficient_curve'." ) | r Calculates the power output of the wind power plant . |
13,228 | def linear_interpolation_extrapolation ( df , target_height ) : r heights_sorted = df . columns [ sorted ( range ( len ( df . columns ) ) , key = lambda i : abs ( df . columns [ i ] - target_height ) ) ] return ( ( df [ heights_sorted [ 1 ] ] - df [ heights_sorted [ 0 ] ] ) / ( heights_sorted [ 1 ] - heights_sorted [ 0 ] ) * ( target_height - heights_sorted [ 0 ] ) + df [ heights_sorted [ 0 ] ] ) | r Linear inter - or extrapolates between the values of a data frame . |
13,229 | def logarithmic_interpolation_extrapolation ( df , target_height ) : r heights_sorted = df . columns [ sorted ( range ( len ( df . columns ) ) , key = lambda i : abs ( df . columns [ i ] - target_height ) ) ] return ( ( np . log ( target_height ) * ( df [ heights_sorted [ 1 ] ] - df [ heights_sorted [ 0 ] ] ) - df [ heights_sorted [ 1 ] ] * np . log ( heights_sorted [ 0 ] ) + df [ heights_sorted [ 0 ] ] * np . log ( heights_sorted [ 1 ] ) ) / ( np . log ( heights_sorted [ 1 ] ) - np . log ( heights_sorted [ 0 ] ) ) ) | r Logarithmic inter - or extrapolates between the values of a data frame . |
13,230 | def gauss_distribution ( function_variable , standard_deviation , mean = 0 ) : r return ( 1 / ( standard_deviation * np . sqrt ( 2 * np . pi ) ) * np . exp ( - ( function_variable - mean ) ** 2 / ( 2 * standard_deviation ** 2 ) ) ) | r Gauss distribution . |
13,231 | def assign_power_curve ( self , weather_df ) : r turbulence_intensity = ( weather_df [ 'turbulence_intensity' ] . values . mean ( ) if 'turbulence_intensity' in weather_df . columns . get_level_values ( 0 ) else None ) if ( self . wake_losses_model == 'power_efficiency_curve' or self . wake_losses_model == 'constant_efficiency' or self . wake_losses_model is None ) : wake_losses_model_to_power_curve = self . wake_losses_model if self . wake_losses_model is None : logging . debug ( 'Wake losses in wind farms not considered.' ) else : logging . debug ( 'Wake losses considered with {}.' . format ( self . wake_losses_model ) ) else : logging . debug ( 'Wake losses considered by {} wind ' . format ( self . wake_losses_model ) + 'efficiency curve.' ) wake_losses_model_to_power_curve = None self . power_plant . assign_power_curve ( wake_losses_model = wake_losses_model_to_power_curve , smoothing = self . smoothing , block_width = self . block_width , standard_deviation_method = self . standard_deviation_method , smoothing_order = self . smoothing_order , roughness_length = weather_df [ 'roughness_length' ] [ 0 ] . mean ( ) , turbulence_intensity = turbulence_intensity ) if self . smoothing is None : logging . debug ( 'Aggregated power curve not smoothed.' ) else : logging . debug ( 'Aggregated power curve smoothed by method: ' + self . standard_deviation_method ) return self | r Calculates the power curve of the wind turbine cluster . |
13,232 | def power_coefficient_curve ( wind_speed , power_coefficient_curve_wind_speeds , power_coefficient_curve_values , rotor_diameter , density ) : r power_coefficient_time_series = np . interp ( wind_speed , power_coefficient_curve_wind_speeds , power_coefficient_curve_values , left = 0 , right = 0 ) power_output = ( 1 / 8 * density * rotor_diameter ** 2 * np . pi * np . power ( wind_speed , 3 ) * power_coefficient_time_series ) if isinstance ( wind_speed , pd . Series ) : power_output = pd . Series ( data = power_output , index = wind_speed . index , name = 'feedin_power_plant' ) else : power_output = np . array ( power_output ) return power_output | r Calculates the turbine power output using a power coefficient curve . |
13,233 | def power_curve ( wind_speed , power_curve_wind_speeds , power_curve_values , density = None , density_correction = False ) : r if density_correction is False : power_output = np . interp ( wind_speed , power_curve_wind_speeds , power_curve_values , left = 0 , right = 0 ) if isinstance ( wind_speed , pd . Series ) : power_output = pd . Series ( data = power_output , index = wind_speed . index , name = 'feedin_power_plant' ) else : power_output = np . array ( power_output ) elif density_correction is True : power_output = power_curve_density_correction ( wind_speed , power_curve_wind_speeds , power_curve_values , density ) else : raise TypeError ( "'{0}' is an invalid type. " . format ( type ( density_correction ) ) + "`density_correction` must " + "be Boolean (True or False)." ) return power_output | r Calculates the turbine power output using a power curve . |
13,234 | def power_curve_density_correction ( wind_speed , power_curve_wind_speeds , power_curve_values , density ) : r if density is None : raise TypeError ( "`density` is None. For the calculation with a " + "density corrected power curve density at hub " + "height is needed." ) power_output = [ ( np . interp ( wind_speed [ i ] , power_curve_wind_speeds * ( 1.225 / density [ i ] ) ** ( np . interp ( power_curve_wind_speeds , [ 7.5 , 12.5 ] , [ 1 / 3 , 2 / 3 ] ) ) , power_curve_values , left = 0 , right = 0 ) ) for i in range ( len ( wind_speed ) ) ] if isinstance ( wind_speed , pd . Series ) : power_output = pd . Series ( data = power_output , index = wind_speed . index , name = 'feedin_power_plant' ) else : power_output = np . array ( power_output ) return power_output | r Calculates the turbine power output using a density corrected power curve . |
13,235 | def mean_hub_height ( self ) : r self . hub_height = np . exp ( sum ( np . log ( wind_farm . hub_height ) * wind_farm . get_installed_power ( ) for wind_farm in self . wind_farms ) / self . get_installed_power ( ) ) return self | r Calculates the mean hub height of the wind turbine cluster . |
13,236 | def get_installed_power ( self ) : r for wind_farm in self . wind_farms : wind_farm . installed_power = wind_farm . get_installed_power ( ) return sum ( wind_farm . installed_power for wind_farm in self . wind_farms ) | r Calculates the installed power of a wind turbine cluster . |
13,237 | def assign_power_curve ( self , wake_losses_model = 'power_efficiency_curve' , smoothing = False , block_width = 0.5 , standard_deviation_method = 'turbulence_intensity' , smoothing_order = 'wind_farm_power_curves' , turbulence_intensity = None , ** kwargs ) : r for farm in self . wind_farms : farm . mean_hub_height ( ) farm . assign_power_curve ( wake_losses_model = wake_losses_model , smoothing = smoothing , block_width = block_width , standard_deviation_method = standard_deviation_method , smoothing_order = smoothing_order , turbulence_intensity = turbulence_intensity , ** kwargs ) df = pd . concat ( [ farm . power_curve . set_index ( [ 'wind_speed' ] ) . rename ( columns = { 'value' : farm . name } ) for farm in self . wind_farms ] , axis = 1 ) cluster_power_curve = pd . DataFrame ( df . interpolate ( method = 'index' ) . sum ( axis = 1 ) ) cluster_power_curve . columns = [ 'value' ] cluster_power_curve . reset_index ( 'wind_speed' , inplace = True ) self . power_curve = cluster_power_curve return self | r Calculates the power curve of a wind turbine cluster . |
13,238 | def run_example ( ) : r weather = mc_e . get_weather_data ( 'weather.csv' ) my_turbine , e126 , dummy_turbine = mc_e . initialize_wind_turbines ( ) example_farm , example_farm_2 = initialize_wind_farms ( my_turbine , e126 ) example_cluster = initialize_wind_turbine_cluster ( example_farm , example_farm_2 ) calculate_power_output ( weather , example_farm , example_cluster ) plot_or_print ( example_farm , example_cluster ) | r Runs the example . |
13,239 | def fetch_turbine_data ( self , fetch_curve , data_source ) : r if data_source == 'oedb' : curve_df , nominal_power = get_turbine_data_from_oedb ( turbine_type = self . name , fetch_curve = fetch_curve ) else : curve_df , nominal_power = get_turbine_data_from_file ( turbine_type = self . name , file_ = data_source ) if fetch_curve == 'power_curve' : self . power_curve = curve_df elif fetch_curve == 'power_coefficient_curve' : self . power_coefficient_curve = curve_df else : raise ValueError ( "'{0}' is an invalid value. " . format ( fetch_curve ) + "`fetch_curve` must be " + "'power_curve' or 'power_coefficient_curve'." ) if self . nominal_power is None : self . nominal_power = nominal_power return self | r Fetches data of the requested wind turbine . |
13,240 | def distance ( latitude_1 , longitude_1 , latitude_2 , longitude_2 ) : coef = mod_math . cos ( latitude_1 / 180. * mod_math . pi ) x = latitude_1 - latitude_2 y = ( longitude_1 - longitude_2 ) * coef return mod_math . sqrt ( x * x + y * y ) * ONE_DEGREE | Distance between two points . |
13,241 | def get_color_between ( color1 , color2 , i ) : if i <= 0 : return color1 if i >= 1 : return color2 return ( int ( color1 [ 0 ] + ( color2 [ 0 ] - color1 [ 0 ] ) * i ) , int ( color1 [ 1 ] + ( color2 [ 1 ] - color1 [ 1 ] ) * i ) , int ( color1 [ 2 ] + ( color2 [ 2 ] - color1 [ 2 ] ) * i ) ) | i is a number between 0 and 1 if 0 then color1 if 1 color2 ... |
13,242 | def _IDW ( self , latitude , longitude , radius = 1 ) : tile = self . get_file ( latitude , longitude ) if tile is None : return None return tile . _InverseDistanceWeighted ( latitude , longitude , radius ) | Return the interpolated elevation at a point . |
13,243 | def get_image ( self , size , latitude_interval , longitude_interval , max_elevation , min_elevation = 0 , unknown_color = ( 255 , 255 , 255 , 255 ) , zero_color = ( 0 , 0 , 255 , 255 ) , min_color = ( 0 , 0 , 0 , 255 ) , max_color = ( 0 , 255 , 0 , 255 ) , mode = 'image' ) : if not size or len ( size ) != 2 : raise Exception ( 'Invalid size %s' % size ) if not latitude_interval or len ( latitude_interval ) != 2 : raise Exception ( 'Invalid latitude interval %s' % latitude_interval ) if not longitude_interval or len ( longitude_interval ) != 2 : raise Exception ( 'Invalid longitude interval %s' % longitude_interval ) width , height = size width , height = int ( width ) , int ( height ) latitude_from , latitude_to = latitude_interval longitude_from , longitude_to = longitude_interval if mode == 'array' : import numpy as np array = np . empty ( ( height , width ) ) for row in range ( height ) : for column in range ( width ) : latitude = latitude_from + float ( row ) / height * ( latitude_to - latitude_from ) longitude = longitude_from + float ( column ) / width * ( longitude_to - longitude_from ) elevation = self . get_elevation ( latitude , longitude ) array [ row , column ] = elevation return array elif mode == 'image' : try : import Image as mod_image except : from PIL import Image as mod_image try : import ImageDraw as mod_imagedraw except : from PIL import ImageDraw as mod_imagedraw image = mod_image . new ( 'RGBA' , ( width , height ) , ( 255 , 255 , 255 , 255 ) ) draw = mod_imagedraw . Draw ( image ) max_elevation -= min_elevation for row in range ( height ) : for column in range ( width ) : latitude = latitude_from + float ( row ) / height * ( latitude_to - latitude_from ) longitude = longitude_from + float ( column ) / width * ( longitude_to - longitude_from ) elevation = self . get_elevation ( latitude , longitude ) if elevation == None : color = unknown_color else : elevation_coef = ( elevation - min_elevation ) / float ( max_elevation ) if elevation_coef < 0 : elevation_coef = 0 if elevation_coef > 1 : elevation_coef = 1 color = mod_utils . get_color_between ( min_color , max_color , elevation_coef ) if elevation <= 0 : color = zero_color draw . point ( ( column , height - row ) , color ) return image else : raise Exception ( 'Invalid mode ' + mode ) | Returns a numpy array or PIL image . |
13,244 | def _add_interval_elevations ( self , gpx , min_interval_length = 100 ) : for track in gpx . tracks : for segment in track . segments : last_interval_changed = 0 previous_point = None length = 0 for no , point in enumerate ( segment . points ) : if previous_point : length += point . distance_2d ( previous_point ) if no == 0 or no == len ( segment . points ) - 1 or length > last_interval_changed : last_interval_changed += min_interval_length point . elevation = self . get_elevation ( point . latitude , point . longitude ) else : point . elevation = None previous_point = point gpx . add_missing_elevations ( ) | Adds elevation on points every min_interval_length and add missing elevation between |
13,245 | def get_elevation ( self , latitude , longitude , approximate = None ) : if not ( self . latitude - self . resolution <= latitude < self . latitude + 1 ) : raise Exception ( 'Invalid latitude %s for file %s' % ( latitude , self . file_name ) ) if not ( self . longitude <= longitude < self . longitude + 1 + self . resolution ) : raise Exception ( 'Invalid longitude %s for file %s' % ( longitude , self . file_name ) ) row , column = self . get_row_and_column ( latitude , longitude ) if approximate : return self . approximation ( latitude , longitude ) else : return self . get_elevation_from_row_and_column ( int ( row ) , int ( column ) ) | If approximate is True then only the points from SRTM grid will be used otherwise a basic aproximation of nearby points will be calculated . |
13,246 | def approximation ( self , latitude , longitude ) : d = 1. / self . square_side d_meters = d * mod_utils . ONE_DEGREE importance_1 = d_meters - mod_utils . distance ( latitude + d , longitude , latitude , longitude ) elevation_1 = self . geo_elevation_data . get_elevation ( latitude + d , longitude , approximate = False ) importance_2 = d_meters - mod_utils . distance ( latitude - d , longitude , latitude , longitude ) elevation_2 = self . geo_elevation_data . get_elevation ( latitude - d , longitude , approximate = False ) importance_3 = d_meters - mod_utils . distance ( latitude , longitude + d , latitude , longitude ) elevation_3 = self . geo_elevation_data . get_elevation ( latitude , longitude + d , approximate = False ) importance_4 = d_meters - mod_utils . distance ( latitude , longitude - d , latitude , longitude ) elevation_4 = self . geo_elevation_data . get_elevation ( latitude , longitude - d , approximate = False ) if elevation_1 == None or elevation_2 == None or elevation_3 == None or elevation_4 == None : elevation = self . get_elevation ( latitude , longitude , approximate = False ) if not elevation : return None elevation_1 = elevation_1 or elevation elevation_2 = elevation_2 or elevation elevation_3 = elevation_3 or elevation elevation_4 = elevation_4 or elevation sum_importances = float ( importance_1 + importance_2 + importance_3 + importance_4 ) assert abs ( importance_1 / sum_importances + importance_2 / sum_importances + importance_3 / sum_importances + importance_4 / sum_importances - 1 ) < 0.000001 result = importance_1 / sum_importances * elevation_1 + importance_2 / sum_importances * elevation_2 + importance_3 / sum_importances * elevation_3 + importance_4 / sum_importances * elevation_4 return result | Dummy approximation with nearest points . The nearest the neighbour the more important will be its elevation . |
13,247 | def _InverseDistanceWeighted ( self , latitude , longitude , radius = 1 ) : if radius == 1 : offsetmatrix = ( None , ( 0 , 1 ) , None , ( - 1 , 0 ) , ( 0 , 0 ) , ( 1 , 0 ) , None , ( 0 , - 1 ) , None ) elif radius == 2 : offsetmatrix = ( None , None , ( 0 , 2 ) , None , None , None , ( - 1 , 1 ) , ( 0 , 1 ) , ( 1 , 1 ) , None , ( - 2 , 0 ) , ( - 1 , 0 ) , ( 0 , 0 ) , ( 1 , 0 ) , ( 2 , 0 ) , None , ( - 1 , - 1 ) , ( 0 , - 1 ) , ( 1 , - 1 ) , None , None , None , ( 0 , - 2 ) , None , None ) else : raise ValueError ( "Radius {} invalid, " "expected 1 or 2" . format ( radius ) ) row , column = self . get_row_and_column ( latitude , longitude ) center_lat , center_long = self . get_lat_and_long ( row , column ) if latitude == center_lat and longitude == center_long : return self . get_elevation_from_row_and_column ( int ( row ) , int ( column ) ) weights = 0 elevation = 0 for offset in offsetmatrix : if ( offset is not None and 0 <= row + offset [ 0 ] < self . square_side and 0 <= column + offset [ 1 ] < self . square_side ) : cell = self . get_elevation_from_row_and_column ( int ( row + offset [ 0 ] ) , int ( column + offset [ 1 ] ) ) if cell is not None : distance = mod_utils . distance ( latitude , longitude , center_lat + float ( offset [ 0 ] ) / ( self . square_side - 1 ) , center_long + float ( offset [ 1 ] ) / ( self . square_side - 1 ) ) weights += 1 / distance elevation += cell / distance return elevation / weights | Return the Inverse Distance Weighted Elevation . |
13,248 | def get_data ( srtm1 = True , srtm3 = True , leave_zipped = False , file_handler = None , use_included_urls = True , batch_mode = False ) : if not file_handler : file_handler = FileHandler ( ) if not srtm1 and not srtm3 : raise Exception ( 'At least one of srtm1 and srtm3 must be True' ) srtm1_files , srtm3_files = _get_urls ( use_included_urls , file_handler ) assert srtm1_files assert srtm3_files if not srtm1 : srtm1_files = { } if not srtm3 : srtm3_files = { } assert srtm1_files or srtm3_files return mod_data . GeoElevationData ( srtm1_files , srtm3_files , file_handler = file_handler , leave_zipped = leave_zipped , batch_mode = batch_mode ) | Get the utility object for querying elevation data . |
13,249 | def get_srtm_dir ( self ) : result = "" if 'HOME' in mod_os . environ : result = mod_os . sep . join ( [ mod_os . environ [ 'HOME' ] , '.cache' , 'srtm' ] ) elif 'HOMEPATH' in mod_os . environ : result = mod_os . sep . join ( [ mod_os . environ [ 'HOMEPATH' ] , '.cache' , 'srtm' ] ) else : raise Exception ( 'No default HOME directory found, please specify a path where to store files' ) if not mod_path . exists ( result ) : mod_os . makedirs ( result ) return result | The default path to store files . |
13,250 | async def unsubscribe ( self , topic : str ) : req_msg = { 'type' : 'unsubscribe' , 'topic' : topic , 'response' : True } await self . _conn . send_message ( req_msg ) | Unsubscribe from a topic |
13,251 | def _generate_signature ( self , nonce , method , path , data ) : data_json = "" endpoint = path if method == "get" : if data : query_string = self . _get_params_for_sig ( data ) endpoint = "{}?{}" . format ( path , query_string ) elif data : data_json = compact_json_dict ( data ) sig_str = ( "{}{}{}{}" . format ( nonce , method . upper ( ) , endpoint , data_json ) ) . encode ( 'utf-8' ) m = hmac . new ( self . API_SECRET . encode ( 'utf-8' ) , sig_str , hashlib . sha256 ) return base64 . b64encode ( m . digest ( ) ) | Generate the call signature |
13,252 | def _handle_response ( response ) : if not str ( response . status_code ) . startswith ( '2' ) : raise KucoinAPIException ( response ) try : res = response . json ( ) if 'code' in res and res [ 'code' ] != "200000" : raise KucoinAPIException ( response ) if 'success' in res and not res [ 'success' ] : raise KucoinAPIException ( response ) if 'data' in res : res = res [ 'data' ] return res except ValueError : raise KucoinRequestException ( 'Invalid Response: %s' % response . text ) | Internal helper for handling API responses from the Quoine server . Raises the appropriate exceptions when necessary ; otherwise returns the response . |
13,253 | def create_account ( self , account_type , currency ) : data = { 'type' : account_type , 'currency' : currency } return self . _post ( 'accounts' , True , data = data ) | Create an account |
13,254 | def get_account_activity ( self , account_id , start = None , end = None , page = None , limit = None ) : data = { } if start : data [ 'startAt' ] = start if end : data [ 'endAt' ] = end if page : data [ 'currentPage' ] = page if limit : data [ 'pageSize' ] = limit return self . _get ( 'accounts/{}/ledgers' . format ( account_id ) , True , data = data ) | Get list of account activity |
13,255 | def create_deposit_address ( self , currency ) : data = { 'currency' : currency } return self . _post ( 'deposit-addresses' , True , data = data ) | Create deposit address of currency for deposit . You can just create one deposit address . |
13,256 | def get_deposit_address ( self , currency ) : data = { 'currency' : currency } return self . _get ( 'deposit-addresses' , True , data = data ) | Get deposit address for a currency |
13,257 | def get_withdrawals ( self , currency = None , status = None , start = None , end = None , page = None , limit = None ) : data = { } if currency : data [ 'currency' ] = currency if status : data [ 'status' ] = status if start : data [ 'startAt' ] = start if end : data [ 'endAt' ] = end if limit : data [ 'pageSize' ] = limit if page : data [ 'page' ] = page return self . _get ( 'withdrawals' , True , data = data ) | Get deposit records for a currency |
13,258 | def get_withdrawal_quotas ( self , currency ) : data = { 'currency' : currency } return self . _get ( 'withdrawals/quotas' , True , data = data ) | Get withdrawal quotas for a currency |
13,259 | def create_withdrawal ( self , currency , amount , address , memo = None , is_inner = False , remark = None ) : data = { 'currency' : currency , 'amount' : amount , 'address' : address } if memo : data [ 'memo' ] = memo if is_inner : data [ 'isInner' ] = is_inner if remark : data [ 'remark' ] = remark return self . _post ( 'withdrawals' , True , data = data ) | Process a withdrawal |
13,260 | def create_market_order ( self , symbol , side , size = None , funds = None , client_oid = None , remark = None , stp = None ) : if not size and not funds : raise MarketOrderException ( 'Need size or fund parameter' ) if size and funds : raise MarketOrderException ( 'Need size or fund parameter not both' ) data = { 'side' : side , 'symbol' : symbol , 'type' : self . ORDER_MARKET } if size : data [ 'size' ] = size if funds : data [ 'funds' ] = funds if client_oid : data [ 'clientOid' ] = client_oid else : data [ 'clientOid' ] = flat_uuid ( ) if remark : data [ 'remark' ] = remark if stp : data [ 'stp' ] = stp return self . _post ( 'orders' , True , data = data ) | Create a market order |
13,261 | def cancel_all_orders ( self , symbol = None ) : data = { } if symbol is not None : data [ 'symbol' ] = symbol return self . _delete ( 'orders' , True , data = data ) | Cancel all orders |
13,262 | def get_orders ( self , symbol = None , status = None , side = None , order_type = None , start = None , end = None , page = None , limit = None ) : data = { } if symbol : data [ 'symbol' ] = symbol if status : data [ 'status' ] = status if side : data [ 'side' ] = side if order_type : data [ 'type' ] = order_type if start : data [ 'startAt' ] = start if end : data [ 'endAt' ] = end if page : data [ 'page' ] = page if limit : data [ 'pageSize' ] = limit return self . _get ( 'orders' , True , data = data ) | Get list of orders |
13,263 | def get_historical_orders ( self , symbol = None , side = None , start = None , end = None , page = None , limit = None ) : data = { } if symbol : data [ 'symbol' ] = symbol if side : data [ 'side' ] = side if start : data [ 'startAt' ] = start if end : data [ 'endAt' ] = end if page : data [ 'page' ] = page if limit : data [ 'pageSize' ] = limit return self . _get ( 'hist-orders' , True , data = data ) | List of KuCoin V1 historical orders . |
13,264 | def get_ticker ( self , symbol = None ) : data = { } tick_path = 'market/allTickers' if symbol is not None : tick_path = 'market/orderbook/level1' data = { 'symbol' : symbol } return self . _get ( tick_path , False , data = data ) | Get symbol tick |
13,265 | def get_fiat_prices ( self , base = None , symbol = None ) : data = { } if base is not None : data [ 'base' ] = base if symbol is not None : data [ 'currencies' ] = symbol return self . _get ( 'prices' , False , data = data ) | Get fiat price for currency |
13,266 | def get_24hr_stats ( self , symbol ) : data = { 'symbol' : symbol } return self . _get ( 'market/stats' , False , data = data ) | Get 24hr stats for a symbol . Volume is in base currency units . open high low are in quote currency units . |
13,267 | def get_order_book ( self , symbol ) : data = { 'symbol' : symbol } return self . _get ( 'market/orderbook/level2_100' , False , data = data ) | Get a list of bids and asks aggregated by price for a symbol . |
13,268 | def get_full_order_book ( self , symbol ) : data = { 'symbol' : symbol } return self . _get ( 'market/orderbook/level2' , False , data = data ) | Get a list of all bids and asks aggregated by price for a symbol . |
13,269 | def get_full_order_book_level3 ( self , symbol ) : data = { 'symbol' : symbol } return self . _get ( 'market/orderbook/level3' , False , data = data ) | Get a list of all bids and asks non - aggregated for a symbol . |
13,270 | def get_trade_histories ( self , symbol ) : data = { 'symbol' : symbol } return self . _get ( 'market/histories' , False , data = data ) | List the latest trades for a symbol |
13,271 | def get_kline_data ( self , symbol , kline_type = '5min' , start = None , end = None ) : data = { 'symbol' : symbol } if kline_type is not None : data [ 'type' ] = kline_type if start is not None : data [ 'startAt' ] = start else : data [ 'startAt' ] = calendar . timegm ( datetime . utcnow ( ) . date ( ) . timetuple ( ) ) if end is not None : data [ 'endAt' ] = end else : data [ 'endAt' ] = int ( time . time ( ) ) return self . _get ( 'market/candles' , False , data = data ) | Get kline data |
13,272 | def get_ws_endpoint ( self , private = False ) : path = 'bullet-public' signed = private if private : path = 'bullet-private' return self . _post ( path , signed ) | Get websocket channel details |
13,273 | def get_real_stored_key ( self , session_key ) : prefix = settings . SESSION_REDIS_PREFIX if not prefix : return session_key return ':' . join ( [ prefix , session_key ] ) | Return the real key name in redis storage |
13,274 | def burn ( features , sequence , zoom ) : features = [ f for f in super_utils . filter_polygons ( features ) ] tiles = burntiles . burn ( features , zoom ) for t in tiles : click . echo ( t . tolist ( ) ) | Burn a stream of GeoJSONs into a output stream of the tiles they intersect for a given zoom . |
13,275 | def save ( self , * args , ** kwargs ) : max_retries = getattr ( settings , 'LOCALIZED_FIELDS_MAX_RETRIES' , 100 ) if not hasattr ( self , 'retries' ) : self . retries = 0 with transaction . atomic ( ) : try : return super ( ) . save ( * args , ** kwargs ) except IntegrityError as ex : if 'slug' not in str ( ex ) : raise ex if self . retries >= max_retries : raise ex self . retries += 1 return self . save ( ) | Saves this model instance to the database . |
13,276 | def to_python ( self , value : Union [ Dict [ str , int ] , int , None ] ) -> LocalizedIntegerValue : db_value = super ( ) . to_python ( value ) return self . _convert_localized_value ( db_value ) | Converts the value from a database value into a Python value . |
13,277 | def get_prep_value ( self , value : LocalizedIntegerValue ) -> dict : default_values = LocalizedIntegerValue ( self . default ) if isinstance ( value , LocalizedIntegerValue ) : for lang_code , _ in settings . LANGUAGES : local_value = value . get ( lang_code ) if local_value is None : value . set ( lang_code , default_values . get ( lang_code , None ) ) prepped_value = super ( ) . get_prep_value ( value ) if prepped_value is None : return None for lang_code , _ in settings . LANGUAGES : local_value = prepped_value [ lang_code ] try : if local_value is not None : int ( local_value ) except ( TypeError , ValueError ) : raise IntegrityError ( 'non-integer value in column "%s.%s" violates ' 'integer constraint' % ( self . name , lang_code ) ) prepped_value [ lang_code ] = str ( local_value ) if local_value is not None else None return prepped_value | Gets the value in a format to store into the database . |
13,278 | def _make_unique_slug ( slug : str , language : str , is_unique : Callable [ [ str ] , bool ] ) -> str : index = 1 unique_slug = slug while not is_unique ( unique_slug , language ) : unique_slug = '%s-%d' % ( slug , index ) index += 1 return unique_slug | Guarentees that the specified slug is unique by appending a number until it is unique . |
13,279 | def _get_populate_from_value ( instance , field_name : Union [ str , Tuple [ str ] ] , language : str ) : if callable ( field_name ) : return field_name ( instance ) def get_field_value ( name ) : value = resolve_object_property ( instance , name ) with translation . override ( language ) : return str ( value ) if isinstance ( field_name , tuple ) or isinstance ( field_name , list ) : value = '-' . join ( [ value for value in [ get_field_value ( name ) for name in field_name ] if value ] ) return value return get_field_value ( field_name ) | Gets the value to create a slug from in the specified language . |
13,280 | def deconstruct ( self ) : name , path , args , kwargs = super ( LocalizedUniqueSlugField , self ) . deconstruct ( ) kwargs [ 'populate_from' ] = self . populate_from kwargs [ 'include_time' ] = self . include_time return name , path , args , kwargs | Deconstructs the field into something the database can store . |
13,281 | def contribute_to_class ( self , model , name , ** kwargs ) : super ( LocalizedField , self ) . contribute_to_class ( model , name , ** kwargs ) setattr ( model , self . name , self . descriptor_class ( self ) ) | Adds this field to the specifed model . |
13,282 | def get_prep_value ( self , value : LocalizedValue ) -> dict : if isinstance ( value , dict ) : value = LocalizedValue ( value ) if not isinstance ( value , LocalizedValue ) and value : value = None if value : cleaned_value = self . clean ( value ) self . validate ( cleaned_value ) else : cleaned_value = value return super ( LocalizedField , self ) . get_prep_value ( cleaned_value . __dict__ if cleaned_value else None ) | Turns the specified value into something the database can store . |
13,283 | def clean ( self , value , * _ ) : if not value or not isinstance ( value , LocalizedValue ) : return None is_all_null = True for lang_code , _ in settings . LANGUAGES : if value . get ( lang_code ) is not None : is_all_null = False break if is_all_null and self . null : return None return value | Cleans the specified value into something we can store in the database . |
13,284 | def validate ( self , value : LocalizedValue , * _ ) : if self . null : return for lang in self . required : lang_val = getattr ( value , settings . LANGUAGE_CODE ) if lang_val is None : raise IntegrityError ( 'null value in column "%s.%s" violates ' 'not-null constraint' % ( self . name , lang ) ) | Validates that the values has been filled in for all required languages |
13,285 | def get ( self , language : str = None , default : str = None ) -> str : language = language or settings . LANGUAGE_CODE value = super ( ) . get ( language , default ) return value if value is not None else default | Gets the underlying value in the specified or primary language . |
13,286 | def set ( self , language : str , value : str ) : self [ language ] = value self . __dict__ . update ( self ) return self | Sets the value in the specified language . |
13,287 | def deconstruct ( self ) -> dict : path = 'localized_fields.value.%s' % self . __class__ . __name__ return path , [ self . __dict__ ] , { } | Deconstructs this value into a primitive type . |
13,288 | def translate ( self ) -> Optional [ str ] : fallbacks = getattr ( settings , 'LOCALIZED_FIELDS_FALLBACKS' , { } ) language = translation . get_language ( ) or settings . LANGUAGE_CODE languages = fallbacks . get ( language , [ settings . LANGUAGE_CODE ] ) [ : ] languages . insert ( 0 , language ) for lang_code in languages : value = self . get ( lang_code ) if value : return value or None return None | Gets the value in the current language or falls back to the next language if there s no value in the current language . |
13,289 | def translate ( self ) : value = super ( ) . translate ( ) if value is None or ( isinstance ( value , str ) and value . strip ( ) == '' ) : return None return int ( value ) | Gets the value in the current language or in the configured fallbck language . |
13,290 | def resolve_object_property ( obj , path : str ) : value = obj for path_part in path . split ( '.' ) : value = getattr ( value , path_part ) return value | Resolves the value of a property on an object . |
13,291 | def decompress ( self , value : LocalizedValue ) -> List [ str ] : result = [ ] for lang_code , _ in settings . LANGUAGES : if value : result . append ( value . get ( lang_code ) ) else : result . append ( None ) return result | Decompresses the specified value so it can be spread over the internal widgets . |
13,292 | def register_target ( repo_cmd , repo_service ) : def decorate ( klass ) : log . debug ( 'Loading service module class: {}' . format ( klass . __name__ ) ) klass . command = repo_cmd klass . name = repo_service RepositoryService . service_map [ repo_service ] = klass RepositoryService . command_map [ repo_cmd ] = repo_service return klass return decorate | Decorator to register a class with an repo_service |
13,293 | def get_service ( cls , repository , command ) : if not repository : config = git_config . GitConfigParser ( cls . get_config_path ( ) ) else : config = repository . config_reader ( ) target = cls . command_map . get ( command , command ) conf_section = list ( filter ( lambda n : 'gitrepo' in n and target in n , config . sections ( ) ) ) http_section = [ config . _sections [ scheme ] for scheme in ( 'http' , 'https' ) if scheme in config . sections ( ) ] if len ( conf_section ) == 0 : if not target : raise ValueError ( 'Service {} unknown' . format ( target ) ) else : config = dict ( ) elif len ( conf_section ) > 1 : raise ValueError ( 'Too many configurations for service {}' . format ( target ) ) else : config = config . _sections [ conf_section [ 0 ] ] if target in cls . service_map : service = cls . service_map . get ( target , cls ) service . name = target else : if 'type' not in config : raise ValueError ( 'Missing service type for custom service.' ) if config [ 'type' ] not in cls . service_map : raise ValueError ( 'Service type {} does not exists.' . format ( config [ 'type' ] ) ) service = cls . service_map . get ( config [ 'type' ] , cls ) cls . _current = service ( repository , config , http_section ) return cls . _current | Accessor for a repository given a command |
13,294 | def format_path ( self , repository , namespace = None , rw = False ) : repo = repository if namespace : repo = '{}/{}' . format ( namespace , repository ) if not rw and repo . count ( '/' ) >= self . _min_nested_namespaces : return '{}/{}' . format ( self . url_ro , repo ) elif rw and repo . count ( '/' ) >= self . _min_nested_namespaces : if self . url_rw . startswith ( 'ssh://' ) : return '{}/{}' . format ( self . url_rw , repo ) else : return '{}:{}' . format ( self . url_rw , repo ) else : raise ArgumentError ( "Cannot tell how to handle this url: `{}/{}`!" . format ( namespace , repo ) ) | format the repository s URL |
13,295 | def open ( self , user = None , repo = None ) : webbrowser . open ( self . format_path ( repo , namespace = user , rw = False ) ) | Open the URL of a repository in the user s browser |
13,296 | def request_fetch ( self , user , repo , request , pull = False , force = False ) : raise NotImplementedError | Fetches given request as a branch and switch if pull is true |
13,297 | def register_action ( * args , ** kwarg ) : def decorator ( fun ) : KeywordArgumentParser . _action_dict [ frozenset ( args ) ] = fun return fun return decorator | Decorator for an action the arguments order is not relevant but it s best to use the same order as in the docopt for clarity . |
13,298 | def get ( self , bus_name , object_path = None , ** kwargs ) : for kwarg in kwargs : if kwarg not in ( "timeout" , ) : raise TypeError ( self . __qualname__ + " got an unexpected keyword argument '{}'" . format ( kwarg ) ) timeout = kwargs . get ( "timeout" , None ) bus_name = auto_bus_name ( bus_name ) object_path = auto_object_path ( bus_name , object_path ) ret = self . con . call_sync ( bus_name , object_path , 'org.freedesktop.DBus.Introspectable' , "Introspect" , None , GLib . VariantType . new ( "(s)" ) , 0 , timeout_to_glib ( timeout ) , None ) if not ret : raise KeyError ( "no such object; you might need to pass object path as the 2nd argument for get()" ) xml , = ret . unpack ( ) try : introspection = ET . fromstring ( xml ) except : raise KeyError ( "object provides invalid introspection XML" ) return CompositeInterface ( introspection ) ( self , bus_name , object_path ) | Get a remote object . |
13,299 | def request_name ( self , name , allow_replacement = True , replace = False ) : return NameOwner ( self , name , allow_replacement , replace ) | Aquires a bus name . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.