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... | 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 encodin... | 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 N... | 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 ... | 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 ... | 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 ( ... | 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 ) :... | 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 )... | 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' ] )... | 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... | 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 ... | 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 ( roughnes... | 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 [ 'turbule... | 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 ' 'gradi... | 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' ]... | 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.' ... | 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.' ... | 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... | 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 [ he... | 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_ef... | 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... | 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 ) : po... | 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... | 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 ( ... | 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_po... | 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... | 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 Ex... | 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... | 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 . resol... | 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 = Fals... | 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 )... | 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 = _ge... | 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... | 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 ( nonc... | 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 KucoinAPIEx... | 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 ( ... | 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' ] = ... | 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 . _po... | 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 = { 'si... | 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 s... | 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 :... | 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 ( ... | 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 ) : rai... | 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... | 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 isin... | 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 s... | 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 lang... | 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_... | 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... | 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 . _m... | 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 = a... | 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.