idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
10,900
def calc_downsample ( w , h , target = 400 ) : if w > h : return h / target elif h >= w : return w / target
Calculate downsampling value .
10,901
def move ( self ) : k = random . choice ( self . keys ) multiplier = random . choice ( ( 0.95 , 1.05 ) ) invalid_key = True while invalid_key : if k == "bias" : if self . state [ k ] > 0.909 : k = random . choice ( self . keys ) continue invalid_key = False newval = self . state [ k ] * multiplier self . state [ k ] = ...
Create a state change .
10,902
def apply_color ( self , arr , state ) : ops = self . cmd ( state ) for func in parse_operations ( ops ) : arr = func ( arr ) return arr
Apply color formula to an array .
10,903
def energy ( self ) : arr = self . src . copy ( ) arr = self . apply_color ( arr , self . state ) scores = [ histogram_distance ( self . ref [ i ] , arr [ i ] ) for i in range ( 3 ) ] return sum ( scores ) * 100
Calculate state s energy .
10,904
def update ( self , step , T , E , acceptance , improvement ) : if acceptance is None : acceptance = 0 if improvement is None : improvement = 0 if step > 0 : elapsed = time . time ( ) - self . start remain = ( self . steps - step ) * ( elapsed / step ) else : elapsed = 0 remain = 0 curr = self . cmd ( self . state ) cu...
Print progress .
10,905
def atmos_worker ( srcs , window , ij , args ) : src = srcs [ 0 ] rgb = src . read ( window = window ) rgb = to_math_type ( rgb ) atmos = simple_atmo ( rgb , args [ "atmo" ] , args [ "contrast" ] , args [ "bias" ] ) return scale_dtype ( atmos , args [ "out_dtype" ] )
A simple atmospheric correction user function .
10,906
def color_worker ( srcs , window , ij , args ) : src = srcs [ 0 ] arr = src . read ( window = window ) arr = to_math_type ( arr ) for func in parse_operations ( args [ "ops_string" ] ) : arr = func ( arr ) return scale_dtype ( arr , args [ "out_dtype" ] )
A user function .
10,907
def add_raw_code ( self , string_or_list ) : if _is_string ( string_or_list ) : self . _GMSH_CODE . append ( string_or_list ) else : assert isinstance ( string_or_list , list ) for string in string_or_list : self . _GMSH_CODE . append ( string ) return
Add raw Gmsh code .
10,908
def _add_torus_extrude_lines ( self , irad , orad , lcar = None , R = numpy . eye ( 3 ) , x0 = numpy . array ( [ 0.0 , 0.0 , 0.0 ] ) ) : self . add_comment ( "Torus" ) x0t = numpy . dot ( R , numpy . array ( [ 0.0 , orad , 0.0 ] ) ) Rc = numpy . array ( [ [ 0.0 , 0.0 , 1.0 ] , [ 0.0 , 1.0 , 0.0 ] , [ 1.0 , 0.0 , 0.0 ] ...
Create Gmsh code for the torus in the x - y plane under the coordinate transformation
10,909
def _add_torus_extrude_circle ( self , irad , orad , lcar = None , R = numpy . eye ( 3 ) , x0 = numpy . array ( [ 0.0 , 0.0 , 0.0 ] ) ) : self . add_comment ( 76 * "-" ) self . add_comment ( "Torus" ) x0t = numpy . dot ( R , numpy . array ( [ 0.0 , orad , 0.0 ] ) ) Rc = numpy . array ( [ [ 0.0 , 0.0 , 1.0 ] , [ 1.0 , 0...
Create Gmsh code for the torus under the coordinate transformation
10,910
def _add_pipe_by_rectangle_rotation ( self , outer_radius , inner_radius , length , R = numpy . eye ( 3 ) , x0 = numpy . array ( [ 0.0 , 0.0 , 0.0 ] ) , lcar = None , ) : self . add_comment ( "Define rectangle." ) X = numpy . array ( [ [ 0.0 , outer_radius , - 0.5 * length ] , [ 0.0 , outer_radius , + 0.5 * length ] , ...
Hollow cylinder . Define a rectangle extrude it by rotation .
10,911
def _add_pipe_by_circle_extrusion ( self , outer_radius , inner_radius , length , R = numpy . eye ( 3 ) , x0 = numpy . array ( [ 0.0 , 0.0 , 0.0 ] ) , lcar = None , ) : Rc = numpy . array ( [ [ 0.0 , 0.0 , 1.0 ] , [ 1.0 , 0.0 , 0.0 ] , [ 0.0 , 1.0 , 0.0 ] ] ) c_inner = self . add_circle ( x0 , inner_radius , lcar = lca...
Hollow cylinder . Define a ring extrude it by translation .
10,912
def translate ( self , input_entity , vector ) : d = { 1 : "Line" , 2 : "Surface" , 3 : "Volume" } self . _GMSH_CODE . append ( "Translate {{{}}} {{ {}{{{}}}; }}" . format ( ", " . join ( [ str ( co ) for co in vector ] ) , d [ input_entity . dimension ] , input_entity . id , ) ) return
Translates input_entity itself by vector .
10,913
def symmetry ( self , input_entity , coefficients , duplicate = True ) : d = { 1 : "Line" , 2 : "Surface" , 3 : "Volume" } entity = "{}{{{}}};" . format ( d [ input_entity . dimension ] , input_entity . id ) if duplicate : entity = "Duplicata{{{}}}" . format ( entity ) self . _GMSH_CODE . append ( "Symmetry {{{}}} {{{}...
Transforms all elementary entities symmetrically to a plane . The vector should contain four expressions giving the coefficients of the plane s equation .
10,914
def patch_qcombobox ( QComboBox ) : from . . QtGui import QIcon from . . QtCore import Qt , QObject class userDataWrapper ( ) : def __init__ ( self , data ) : self . data = data _addItem = QComboBox . addItem def addItem ( self , * args , ** kwargs ) : if len ( args ) == 3 or ( not isinstance ( args [ 0 ] , QIcon ) and...
In PySide using Python objects as userData in QComboBox causes Segmentation faults under certain conditions . Even in cases where it doesn t findData does not work correctly . Likewise findData also does not work correctly with Python objects when using PyQt4 . On the other hand PyQt5 deals with this case correctly . W...
10,915
def to_czml ( traffic : Union [ Traffic , SO6 ] , filename : Union [ str , Path ] , minimum_time : Optional [ timelike ] = None , ) -> None : if isinstance ( traffic , Traffic ) : if "baro_altitude" in traffic . data . columns : traffic = traffic . query ( "baro_altitude == baro_altitude" ) elif "altitude" in traffic ....
Generates a CesiumJS scenario file .
10,916
def plot ( self , ax : GeoAxesSubplot , ** kwargs ) -> Artist : if "facecolor" not in kwargs : kwargs [ "facecolor" ] = "None" if "edgecolor" not in kwargs : kwargs [ "edgecolor" ] = ax . _get_lines . get_next_color ( ) if "projection" in ax . __dict__ : return ax . add_geometries ( [ self . shape ] , crs = PlateCarree...
Plotting function . All arguments are passed to the geometry
10,917
def api_states ( self , own : bool = False , bounds : Union [ BaseGeometry , Tuple [ float , float , float , float ] , None ] = None , ) -> StateVectors : what = "own" if ( own and self . auth is not None ) else "all" if bounds is not None : try : west , south , east , north = bounds . bounds except AttributeError : we...
Returns the current state vectors from OpenSky REST API .
10,918
def api_tracks ( self , icao24 : str ) -> Flight : c = requests . get ( f"https://opensky-network.org/api/tracks/?icao24={icao24}" ) if c . status_code != 200 : raise ValueError ( c . content . decode ( ) ) json = c . json ( ) df = pd . DataFrame . from_records ( json [ "path" ] , columns = [ "timestamp" , "latitude" ,...
Returns a Flight corresponding to a given aircraft .
10,919
def api_routes ( self , callsign : str ) -> Tuple [ Airport , ... ] : from . . import airports c = requests . get ( f"https://opensky-network.org/api/routes?callsign={callsign}" ) if c . status_code == 404 : raise ValueError ( "Unknown callsign" ) if c . status_code != 200 : raise ValueError ( c . content . decode ( ) ...
Returns the route associated to a callsign .
10,920
def api_aircraft ( self , icao24 : str , begin : Optional [ timelike ] = None , end : Optional [ timelike ] = None , ) -> pd . DataFrame : if begin is None : begin = round_time ( datetime . now ( timezone . utc ) , by = timedelta ( days = 1 ) ) begin = to_datetime ( begin ) if end is None : end = begin + timedelta ( da...
Returns a flight table associated to an aircraft .
10,921
def api_range ( self , serial : str , date : Optional [ timelike ] = None ) -> SensorRange : if date is None : date = round_time ( datetime . now ( timezone . utc ) , by = timedelta ( days = 1 ) ) else : date = to_datetime ( date ) date = int ( date . timestamp ( ) ) c = requests . get ( f"https://opensky-network.org/a...
Wraps a polygon representing a sensor s range .
10,922
def api_arrival ( self , airport : Union [ str , Airport ] , begin : Optional [ timelike ] = None , end : Optional [ timelike ] = None , ) -> pd . DataFrame : if isinstance ( airport , str ) : from . . import airports airport_code = airports [ airport ] . icao else : airport_code = airport . icao if begin is None : beg...
Returns a flight table associated to an airport .
10,923
def start ( self ) -> pd . Timestamp : start = self . data . timestamp . min ( ) self . data = self . data . assign ( start = start ) return start
Returns the minimum timestamp value of the DataFrame .
10,924
def squawk ( self ) -> Set [ str ] : return set ( self . data . squawk . ffill ( ) . bfill ( ) )
Returns all the unique squawk values in the trajectory .
10,925
def query_opensky ( self ) -> Optional [ "Flight" ] : from . . data import opensky query_params = { "start" : self . start , "stop" : self . stop , "callsign" : self . callsign , "icao24" : self . icao24 , } return opensky . history ( ** query_params )
Return the equivalent Flight from OpenSky History .
10,926
def coords ( self ) -> Iterator [ Tuple [ float , float , float ] ] : data = self . data [ self . data . longitude . notnull ( ) ] yield from zip ( data [ "longitude" ] , data [ "latitude" ] , data [ "altitude" ] )
Iterates on longitudes latitudes and altitudes .
10,927
def xy_time ( self ) -> Iterator [ Tuple [ float , float , float ] ] : iterator = iter ( zip ( self . coords , self . timestamp ) ) while True : next_ = next ( iterator , None ) if next_ is None : return coords , time = next_ yield ( coords [ 0 ] , coords [ 1 ] , time . to_pydatetime ( ) . timestamp ( ) )
Iterates on longitudes latitudes and timestamps .
10,928
def split ( self , value = 10 , unit = None ) : if type ( value ) == int and unit is None : unit = "m" for data in _split ( self . data , value , unit ) : yield self . __class__ ( data )
Splits Flights in several legs .
10,929
def resample ( self , rule : Union [ str , int ] = "1s" ) -> "Flight" : if isinstance ( rule , str ) : data = ( self . _handle_last_position ( ) . data . assign ( start = self . start , stop = self . stop ) . set_index ( "timestamp" ) . resample ( rule ) . first ( ) . interpolate ( ) . reset_index ( ) . fillna ( method...
Resamples a Flight at a one point per second rate .
10,930
def simplify ( self , tolerance : float , altitude : Optional [ str ] = None , z_factor : float = 3.048 , return_type : Type [ Mask ] = Type [ "Flight" ] , ) -> Mask : mask = douglas_peucker ( df = self . data , tolerance = tolerance , lat = "latitude" , lon = "longitude" , z = altitude , z_factor = z_factor , ) if ret...
Simplifies a trajectory with Douglas - Peucker algorithm .
10,931
def project_shape ( self , projection : Union [ pyproj . Proj , crs . Projection , None ] = None ) -> base . BaseGeometry : if self . shape is None : return None if isinstance ( projection , crs . Projection ) : projection = pyproj . Proj ( projection . proj4_init ) if projection is None : bounds = self . bounds projec...
Projection for a decent representation of the structure .
10,932
def compute_xy ( self , projection : Union [ pyproj . Proj , crs . Projection , None ] = None ) : if isinstance ( projection , crs . Projection ) : projection = pyproj . Proj ( projection . proj4_init ) if projection is None : projection = pyproj . Proj ( proj = "lcc" , lat_1 = self . data . latitude . min ( ) , lat_2 ...
Computes x and y columns from latitudes and longitudes .
10,933
def callsigns ( self ) -> Set [ str ] : sub = self . data . query ( "callsign == callsign" ) return set ( cs for cs in sub . callsign if len ( cs ) > 3 and " " not in cs )
Return only the most relevant callsigns
10,934
def resample ( self , rule : Union [ str , int ] = "1s" , max_workers : int = 4 , ) -> "Traffic" : with ProcessPoolExecutor ( max_workers = max_workers ) as executor : cumul = [ ] tasks = { executor . submit ( flight . resample , rule ) : flight for flight in self } for future in tqdm ( as_completed ( tasks ) , total =...
Resamples all trajectories flight by flight .
10,935
def vcas2mach ( cas , h ) : tas = vcas2tas ( cas , h ) M = vtas2mach ( tas , h ) return M
CAS to Mach conversion
10,936
def cas2mach ( cas , h ) : tas = cas2tas ( cas , h ) M = tas2mach ( tas , h ) return M
CAS Mach conversion
10,937
def to_bluesky ( traffic : Traffic , filename : Union [ str , Path ] , minimum_time : Optional [ timelike ] = None , ) -> None : if minimum_time is not None : minimum_time = to_datetime ( minimum_time ) traffic = traffic . query ( f"timestamp >= '{minimum_time}'" ) if isinstance ( filename , str ) : filename = Path ( f...
Generates a Bluesky scenario file .
10,938
def import_submodules ( package , recursive = True ) : if isinstance ( package , str ) : package = importlib . import_module ( package ) results = { } for loader , name , is_pkg in pkgutil . walk_packages ( package . __path__ ) : full_name = package . __name__ + "." + name results [ name ] = importlib . import_module (...
Import all submodules of a module recursively including subpackages
10,939
def interpolate ( self , times , proj = PlateCarree ( ) ) -> np . ndarray : if proj not in self . interpolator : self . interpolator [ proj ] = interp1d ( np . stack ( t . to_pydatetime ( ) . timestamp ( ) for t in self . timestamp ) , proj . transform_points ( PlateCarree ( ) , * np . stack ( self . coords ) . T ) . T...
Interpolates a trajectory in time .
10,940
def _set_default_extent ( self ) : west , south , east , north = self . projection . boundary . bounds self . set_extent ( ( west , east , south , north ) , crs = self . projection )
Helper for a default extent limited to the projection boundaries .
10,941
def _format_dataframe ( df : pd . DataFrame , nautical_units = True ) -> pd . DataFrame : if "callsign" in df . columns and df . callsign . dtype == object : df . callsign = df . callsign . str . strip ( ) if nautical_units : df . altitude = df . altitude / 0.3048 if "geoaltitude" in df . columns : df . geoaltitude = d...
This function converts types strips spaces after callsigns and sorts the DataFrame by timestamp .
10,942
def filter ( self , info , releases ) : removed = 0 versions = list ( releases . keys ( ) ) for version in versions : new_files = [ ] for file_desc in releases [ version ] : if self . _check_match ( file_desc ) : removed += 1 else : new_files . append ( file_desc ) if len ( new_files ) == 0 : del releases [ version ] e...
Remove files from releases that match any pattern .
10,943
def load_filter_plugins ( entrypoint_group : str ) -> Iterable [ Filter ] : global loaded_filter_plugins enabled_plugins : List [ str ] = [ ] config = BandersnatchConfig ( ) . config try : config_blacklist_plugins = config [ "blacklist" ] [ "plugins" ] split_plugins = config_blacklist_plugins . split ( "\n" ) if "all" ...
Load all blacklist plugins that are registered with pkg_resources
10,944
def filter ( self , info , releases ) : for version in list ( releases . keys ( ) ) : if any ( pattern . match ( version ) for pattern in self . patterns ) : del releases [ version ]
Remove all release versions that match any of the specificed patterns .
10,945
def _check_match ( self , name , version_string ) -> bool : if not name or not version_string : return False try : version = Version ( version_string ) except InvalidVersion : logger . debug ( f"Package {name}=={version_string} has an invalid version" ) return False for requirement in self . blacklist_release_requireme...
Check if the package name and version matches against a blacklisted package version specifier .
10,946
def find ( root : Union [ Path , str ] , dirs : bool = True ) -> str : if isinstance ( root , str ) : root = Path ( root ) results : List [ Path ] = [ ] for dirpath , dirnames , filenames in os . walk ( root ) : names = filenames if dirs : names += dirnames for name in names : results . append ( Path ( dirpath ) / name...
A test helper simulating find .
10,947
def rewrite ( filepath : Union [ str , Path ] , mode : str = "w" , ** kw : Any ) -> Generator [ IO , None , None ] : if isinstance ( filepath , str ) : base_dir = os . path . dirname ( filepath ) filename = os . path . basename ( filepath ) else : base_dir = str ( filepath . parent ) filename = filepath . name with tem...
Rewrite an existing file atomically to avoid programs running in parallel to have race conditions while reading .
10,948
def unlink_parent_dir ( path : Path ) -> None : logger . info ( f"unlink {str(path)}" ) path . unlink ( ) parent_path = path . parent try : parent_path . rmdir ( ) logger . info ( f"rmdir {str(parent_path)}" ) except OSError as oe : logger . debug ( f"Did not remove {str(parent_path)}: {str(oe)}" )
Remove a file and if the dir is empty remove it
10,949
def update_safe ( filename : str , ** kw : Any ) -> Generator [ IO , None , None ] : with tempfile . NamedTemporaryFile ( dir = os . path . dirname ( filename ) , delete = False , prefix = f"{os.path.basename(filename)}." , ** kw , ) as tf : if os . path . exists ( filename ) : os . chmod ( tf . name , os . stat ( file...
Rewrite a file atomically .
10,950
def save_json_metadata ( self , package_info : Dict ) -> bool : try : with utils . rewrite ( self . json_file ) as jf : dump ( package_info , jf , indent = 4 , sort_keys = True ) except Exception as e : logger . error ( "Unable to write json to {}: {}" . format ( self . json_file , str ( e ) ) ) return False symlink_di...
Take the JSON metadata we just fetched and save to disk
10,951
def _filter_releases ( self ) : global display_filter_log filter_plugins = filter_release_plugins ( ) if not filter_plugins : if display_filter_log : logger . info ( "No release filters are enabled. Skipping filtering" ) display_filter_log = False else : for plugin in filter_plugins : plugin . filter ( self . info , se...
Run the release filtering plugins
10,952
def sync_release_files ( self ) : release_files = [ ] for release in self . releases . values ( ) : release_files . extend ( release ) downloaded_files = set ( ) deferred_exception = None for release_file in release_files : try : downloaded_file = self . download_file ( release_file [ "url" ] , release_file [ "digests"...
Purge + download files returning files removed + added
10,953
def _cleanup ( self ) : if self . todolist . exists ( ) : try : saved_todo = iter ( open ( self . todolist , encoding = "utf-8" ) ) int ( next ( saved_todo ) . strip ( ) ) for line in saved_todo : _ , serial = line . strip ( ) . split ( ) int ( serial ) except ( StopIteration , ValueError ) : logger . info ( "Removing ...
Does a couple of cleanup tasks to ensure consistent data for later processing .
10,954
def _filter_packages ( self ) : global LOG_PLUGINS filter_plugins = filter_project_plugins ( ) if not filter_plugins : if LOG_PLUGINS : logger . info ( "No project filters are enabled. Skipping filtering" ) LOG_PLUGINS = False return packages = list ( self . packages_to_sync . keys ( ) ) for package_name in packages : ...
Run the package filtering plugins and remove any packages from the packages_to_sync that match any filters . - Logging of action will be done within the check_match methods
10,955
def determine_packages_to_sync ( self ) : self . target_serial = self . synced_serial self . packages_to_sync = { } logger . info ( f"Current mirror serial: {self.synced_serial}" ) if self . todolist . exists ( ) : logger . info ( "Resuming interrupted sync from local todo list." ) saved_todo = iter ( open ( self . tod...
Update the self . packages_to_sync to contain packages that need to be synced .
10,956
def get_simple_dirs ( self , simple_dir : Path ) -> List [ Path ] : if self . hash_index : subdirs = [ simple_dir / x for x in simple_dir . iterdir ( ) if x . is_dir ( ) ] else : subdirs = [ simple_dir ] return subdirs
Return a list of simple index directories that should be searched for package indexes when compiling the main index page .
10,957
def find_package_indexes_in_dir ( self , simple_dir ) : packages = sorted ( { canonicalize_name ( x ) for x in os . listdir ( simple_dir ) } ) packages = [ x for x in packages if os . path . isdir ( os . path . join ( simple_dir , x ) ) ] return packages
Given a directory that contains simple packages indexes return a sorted list of normalized package names . This presumes every directory within is a simple package index directory .
10,958
def load_configuration ( self ) -> None : config_file = self . default_config_file if self . config_file : config_file = self . config_file self . config = ConfigParser ( ) self . config . read ( config_file )
Read the configuration from a configuration file
10,959
async def metadata_verify ( config , args ) -> int : all_package_files = [ ] loop = asyncio . get_event_loop ( ) mirror_base = config . get ( "mirror" , "directory" ) json_base = Path ( mirror_base ) / "web" / "json" workers = args . workers or config . getint ( "mirror" , "workers" ) executor = concurrent . futures . ...
Crawl all saved JSON metadata or online to check we have all packages if delete - generate a diff of unowned files
10,960
def _der_to_pem ( der_key , marker ) : pem_key_chunks = [ ( '-----BEGIN %s-----' % marker ) . encode ( 'utf-8' ) ] for chunk_start in range ( 0 , len ( der_key ) , 48 ) : pem_key_chunks . append ( b64encode ( der_key [ chunk_start : chunk_start + 48 ] ) ) pem_key_chunks . append ( ( '-----END %s-----' % marker ) . enco...
Perform a simple DER to PEM conversion .
10,961
def _der_to_raw ( self , der_signature ) : r , s = decode_dss_signature ( der_signature ) component_length = self . _sig_component_length ( ) return int_to_bytes ( r , component_length ) + int_to_bytes ( s , component_length )
Convert signature from DER encoding to RAW encoding .
10,962
def _raw_to_der ( self , raw_signature ) : component_length = self . _sig_component_length ( ) if len ( raw_signature ) != int ( 2 * component_length ) : raise ValueError ( "Invalid signature" ) r_bytes = raw_signature [ : component_length ] s_bytes = raw_signature [ component_length : ] r = int_from_bytes ( r_bytes , ...
Convert signature from RAW encoding to DER encoding .
10,963
def encode ( claims , key , algorithm = ALGORITHMS . HS256 , headers = None , access_token = None ) : for time_claim in [ 'exp' , 'iat' , 'nbf' ] : if isinstance ( claims . get ( time_claim ) , datetime ) : claims [ time_claim ] = timegm ( claims [ time_claim ] . utctimetuple ( ) ) if access_token : claims [ 'at_hash' ...
Encodes a claims set and returns a JWT string .
10,964
def decode ( token , key , algorithms = None , options = None , audience = None , issuer = None , subject = None , access_token = None ) : defaults = { 'verify_signature' : True , 'verify_aud' : True , 'verify_iat' : True , 'verify_exp' : True , 'verify_nbf' : True , 'verify_iss' : True , 'verify_sub' : True , 'verify_...
Verifies a JWT string s signature and validates reserved claims .
10,965
def _validate_nbf ( claims , leeway = 0 ) : if 'nbf' not in claims : return try : nbf = int ( claims [ 'nbf' ] ) except ValueError : raise JWTClaimsError ( 'Not Before claim (nbf) must be an integer.' ) now = timegm ( datetime . utcnow ( ) . utctimetuple ( ) ) if nbf > ( now + leeway ) : raise JWTClaimsError ( 'The tok...
Validates that the nbf claim is valid .
10,966
def _validate_exp ( claims , leeway = 0 ) : if 'exp' not in claims : return try : exp = int ( claims [ 'exp' ] ) except ValueError : raise JWTClaimsError ( 'Expiration Time claim (exp) must be an integer.' ) now = timegm ( datetime . utcnow ( ) . utctimetuple ( ) ) if exp < ( now - leeway ) : raise ExpiredSignatureErro...
Validates that the exp claim is valid .
10,967
def _validate_aud ( claims , audience = None ) : if 'aud' not in claims : return audience_claims = claims [ 'aud' ] if isinstance ( audience_claims , string_types ) : audience_claims = [ audience_claims ] if not isinstance ( audience_claims , list ) : raise JWTClaimsError ( 'Invalid claim format in token' ) if any ( no...
Validates that the aud claim is valid .
10,968
def _validate_iss ( claims , issuer = None ) : if issuer is not None : if isinstance ( issuer , string_types ) : issuer = ( issuer , ) if claims . get ( 'iss' ) not in issuer : raise JWTClaimsError ( 'Invalid issuer' )
Validates that the iss claim is valid .
10,969
def _validate_sub ( claims , subject = None ) : if 'sub' not in claims : return if not isinstance ( claims [ 'sub' ] , string_types ) : raise JWTClaimsError ( 'Subject must be a string.' ) if subject is not None : if claims . get ( 'sub' ) != subject : raise JWTClaimsError ( 'Invalid subject' )
Validates that the sub claim is valid .
10,970
def _gcd ( a , b ) : while b : a , b = b , ( a % b ) return a
Calculate the Greatest Common Divisor of a and b .
10,971
def _rsa_recover_prime_factors ( n , e , d ) : ktot = d * e - 1 t = ktot while t % 2 == 0 : t = t // 2 spotted = False a = 2 while not spotted and a < _MAX_RECOVERY_ATTEMPTS : k = t while k < ktot : cand = pow ( a , k , n ) if cand != 1 and cand != ( n - 1 ) and pow ( cand , 2 , n ) == 1 : p = _gcd ( cand + 1 , n ) spo...
Compute factors p and q from the private exponent d . We assume that n has no more than two factors . This function is adapted from code in PyCrypto .
10,972
def _legacy_private_key_pkcs8_to_pkcs1 ( pkcs8_key ) : if not pkcs8_key . startswith ( LEGACY_INVALID_PKCS8_RSA_HEADER + ASN1_SEQUENCE_ID ) : raise ValueError ( "Invalid private key encoding" ) return pkcs8_key [ len ( LEGACY_INVALID_PKCS8_RSA_HEADER ) : ]
Legacy RSA private key PKCS8 - to - PKCS1 conversion .
10,973
def base64url_decode ( input ) : rem = len ( input ) % 4 if rem > 0 : input += b'=' * ( 4 - rem ) return base64 . urlsafe_b64decode ( input )
Helper method to base64url_decode a string .
10,974
def constant_time_string_compare ( a , b ) : try : return hmac . compare_digest ( a , b ) except AttributeError : if len ( a ) != len ( b ) : return False result = 0 for x , y in zip ( a , b ) : result |= ord ( x ) ^ ord ( y ) return result == 0
Helper for comparing string in constant time independent of the python version being used .
10,975
def sign ( payload , key , headers = None , algorithm = ALGORITHMS . HS256 ) : if algorithm not in ALGORITHMS . SUPPORTED : raise JWSError ( 'Algorithm %s not supported.' % algorithm ) encoded_header = _encode_header ( algorithm , additional_headers = headers ) encoded_payload = _encode_payload ( payload ) signed_outpu...
Signs a claims set and returns a JWS string .
10,976
def verify ( token , key , algorithms , verify = True ) : header , payload , signing_input , signature = _load ( token ) if verify : _verify_signature ( signing_input , header , signature , key , algorithms ) return payload
Verifies a JWS string s signature .
10,977
def construct ( key_data , algorithm = None ) : if not algorithm and isinstance ( key_data , dict ) : algorithm = key_data . get ( 'alg' , None ) if not algorithm : raise JWKError ( 'Unable to find a algorithm for key: %s' % key_data ) key_class = get_key ( algorithm ) if not key_class : raise JWKError ( 'Unable to fin...
Construct a Key object for the given algorithm with the given key_data .
10,978
def train ( self , dataset ) : r X , Y = dataset . format_sklearn ( ) X = np . array ( X ) Y = np . array ( Y ) self . n_labels_ = np . shape ( Y ) [ 1 ] self . n_features_ = np . shape ( X ) [ 1 ] self . clfs_ = [ ] for i in range ( self . n_labels_ ) : if len ( np . unique ( Y [ : , i ] ) ) == 1 : clf = DummyClf ( ) ...
r Train model with given feature .
10,979
def predict ( self , X ) : r X = np . asarray ( X ) if self . clfs_ is None : raise ValueError ( "Train before prediction" ) if X . shape [ 1 ] != self . n_features_ : raise ValueError ( 'Given feature size does not match' ) pred = np . zeros ( ( X . shape [ 0 ] , self . n_labels_ ) ) for i in range ( self . n_labels_ ...
r Predict labels .
10,980
def predict_real ( self , X ) : r X = np . asarray ( X ) if self . clfs_ is None : raise ValueError ( "Train before prediction" ) if X . shape [ 1 ] != self . n_features_ : raise ValueError ( 'given feature size does not match' ) pred = np . zeros ( ( X . shape [ 0 ] , self . n_labels_ ) ) for i in range ( self . n_lab...
r Predict the probability of being 1 for each label .
10,981
def score ( self , testing_dataset , criterion = 'hamming' ) : X , Y = testing_dataset . format_sklearn ( ) if criterion == 'hamming' : return np . mean ( np . abs ( self . predict ( X ) - Y ) . mean ( axis = 1 ) ) elif criterion == 'f1' : Z = self . predict ( X ) Z = Z . astype ( int ) Y = Y . astype ( int ) up = 2 * ...
Return the mean accuracy on the test dataset
10,982
def seed_random_state ( seed ) : if ( seed is None ) or ( isinstance ( seed , int ) ) : return np . random . RandomState ( seed ) elif isinstance ( seed , np . random . RandomState ) : return seed raise ValueError ( "%r can not be used to generate numpy.random.RandomState" " instance" % seed )
Turn seed into np . random . RandomState instance
10,983
def calc_cost ( y , yhat , cost_matrix ) : return np . mean ( cost_matrix [ list ( y ) , list ( yhat ) ] )
Calculate the cost with given cost matrix
10,984
def make_query ( self , return_score = False ) : dataset = self . dataset self . model . train ( dataset ) unlabeled_entry_ids , X_pool = zip ( * dataset . get_unlabeled_entries ( ) ) if isinstance ( self . model , ProbabilisticModel ) : dvalue = self . model . predict_proba ( X_pool ) elif isinstance ( self . model , ...
Return the index of the sample to be queried and labeled and selection score of each sample . Read - only .
10,985
def _vote_disagreement ( self , votes ) : ret = [ ] for candidate in votes : ret . append ( 0.0 ) lab_count = { } for lab in candidate : lab_count [ lab ] = lab_count . setdefault ( lab , 0 ) + 1 for lab in lab_count . keys ( ) : ret [ - 1 ] -= lab_count [ lab ] / self . n_students * math . log ( float ( lab_count [ la...
Return the disagreement measurement of the given number of votes . It uses the vote vote to measure the disagreement .
10,986
def _labeled_uniform_sample ( self , sample_size ) : labeled_entries = self . dataset . get_labeled_entries ( ) samples = [ labeled_entries [ self . random_state_ . randint ( 0 , len ( labeled_entries ) ) ] for _ in range ( sample_size ) ] return Dataset ( * zip ( * samples ) )
sample labeled entries uniformly
10,987
def calc_reward_fn ( self ) : model = copy . copy ( self . model ) model . train ( self . dataset ) reward = 0. for i in range ( len ( self . queried_hist_ ) ) : reward += self . W [ i ] * ( model . predict ( self . dataset . data [ self . queried_hist_ [ i ] ] [ 0 ] . reshape ( 1 , - 1 ) ) [ 0 ] == self . dataset . da...
Calculate the reward value
10,988
def calc_query ( self ) : if self . query_dist is None : self . query_dist = self . exp4p_ . next ( - 1 , None , None ) else : self . query_dist = self . exp4p_ . next ( self . calc_reward_fn ( ) , self . queried_hist_ [ - 1 ] , self . dataset . data [ self . queried_hist_ [ - 1 ] ] [ 1 ] ) return
Calculate the sampling query distribution
10,989
def next ( self , reward , ask_id , lbl ) : if reward == - 1 : return next ( self . exp4p_gen ) else : return self . exp4p_gen . send ( ( reward , ask_id , lbl ) )
Taking the label and the reward value of last question and returns the next question to ask .
10,990
def exp4p ( self ) : while True : query = np . zeros ( ( self . N , len ( self . unlabeled_invert_id_idx ) ) ) if self . uniform_sampler : query [ - 1 , : ] = 1. / len ( self . unlabeled_invert_id_idx ) for i , model in enumerate ( self . query_strategies_ ) : query [ i ] [ self . unlabeled_invert_id_idx [ model . make...
The generator which implements the main part of Exp4 . P .
10,991
def import_libsvm_sparse ( filename ) : from sklearn . datasets import load_svmlight_file X , y = load_svmlight_file ( filename ) return Dataset ( X . toarray ( ) . tolist ( ) , y . tolist ( ) )
Imports dataset file in libsvm sparse format
10,992
def update ( self , entry_id , new_label ) : self . data [ entry_id ] = ( self . data [ entry_id ] [ 0 ] , new_label ) self . modified = True for callback in self . _update_callback : callback ( entry_id , new_label )
Updates an entry with entry_id with the given label
10,993
def get_unlabeled_entries ( self ) : return [ ( idx , entry [ 0 ] ) for idx , entry in enumerate ( self . data ) if entry [ 1 ] is None ]
Returns list of unlabeled features along with their entry_ids
10,994
def labeled_uniform_sample ( self , sample_size , replace = True ) : if replace : samples = [ random . choice ( self . get_labeled_entries ( ) ) for _ in range ( sample_size ) ] else : samples = random . sample ( self . get_labeled_entries ( ) , sample_size ) return Dataset ( * zip ( * samples ) )
Returns a Dataset object with labeled data only which is resampled uniformly with given sample size . Parameter replace decides whether sampling with replacement or not .
10,995
def push_token ( self , tok ) : "Push a token onto the stack popped by the get_token method" if self . debug >= 1 : print ( "shlex: pushing token " + repr ( tok ) ) self . pushback . appendleft ( tok )
Push a token onto the stack popped by the get_token method
10,996
def _get_next_positional ( self ) : active_parser = self . active_parsers [ - 1 ] last_positional = self . visited_positionals [ - 1 ] all_positionals = active_parser . _get_positional_actions ( ) if not all_positionals : return None if active_parser == last_positional : return all_positionals [ 0 ] i = 0 for i in rang...
Get the next positional action if it exists .
10,997
def shellcode ( executables , use_defaults = True , shell = 'bash' , complete_arguments = None ) : if complete_arguments is None : complete_options = '-o nospace -o default' if use_defaults else '-o nospace' else : complete_options = " " . join ( complete_arguments ) if shell == 'bash' : quoted_executables = [ quote ( ...
Provide the shell code required to register a python executable for use with the argcomplete module .
10,998
def _send ( self , message ) : params = { 'V' : SMSPUBLI_API_VERSION , 'UN' : SMSPUBLI_USERNAME , 'PWD' : SMSPUBLI_PASSWORD , 'R' : SMSPUBLI_ROUTE , 'SA' : message . from_phone , 'DA' : ',' . join ( message . to ) , 'M' : message . body . encode ( 'latin-1' ) , 'DC' : SMSPUBLI_DC , 'DR' : SMSPUBLI_DR , 'UR' : message ....
Private method for send one message .
10,999
def _get_filename ( self ) : if self . _fname is None : timestamp = datetime . datetime . now ( ) . strftime ( "%Y%m%d-%H%M%S" ) fname = "%s-%s.log" % ( timestamp , abs ( id ( self ) ) ) self . _fname = os . path . join ( self . file_path , fname ) return self . _fname
Return a unique file name .