signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def facilityMsToNet ( SsVersionIndicator_presence = 0 ) : """FACILITY Section 9.3.9.2"""
a = TpPd ( pd = 0x3 ) b = MessageType ( mesType = 0x3a ) # 00111010 c = Facility ( ) packet = a / b / c if SsVersionIndicator_presence is 1 : d = SsVersionIndicatorHdr ( ieiSVI = 0x7F , eightBitSVI = 0x0 ) packet = packet / d return packet
def changeSize ( self , newsize ) : """Changes the size of the layer . Should only be called through Network . changeLayerSize ( ) ."""
# overwrites current data if newsize <= 0 : raise LayerError ( 'Layer size changed to zero.' , newsize ) minSize = min ( self . size , newsize ) bias = randomArray ( newsize , self . _maxRandom ) Numeric . put ( bias , Numeric . arange ( minSize ) , self . weight ) self . weight = bias self . size = newsize self . ...
def use_categories_as_metadata_and_replace_terms ( self ) : '''Returns a TermDocMatrix which is identical to self except the metadata values are now identical to the categories present and term - doc - matrix is now the metadata matrix . : return : TermDocMatrix'''
new_metadata_factory = CSRMatrixFactory ( ) for i , category_idx in enumerate ( self . get_category_ids ( ) ) : new_metadata_factory [ i , category_idx ] = 1 new_metadata = new_metadata_factory . get_csr_matrix ( ) new_tdm = self . _make_new_term_doc_matrix ( self . _mX , new_metadata , self . _y , self . _metadata...
def _RemoveForwardedIps ( self , forwarded_ips , interface ) : """Remove the forwarded IP addresses from the network interface . Args : forwarded _ ips : list , the forwarded IP address strings to delete . interface : string , the output device to use ."""
for address in forwarded_ips : self . ip_forwarding_utils . RemoveForwardedIp ( address , interface )
def run_with_router ( func , * args , ** kwargs ) : """Arrange for ` func ( router , * args , * * kwargs ) ` to run with a temporary : class : ` mitogen . master . Router ` , ensuring the Router and Broker are correctly shut down during normal or exceptional return . : returns : ` func ` ' s return value ."...
broker = mitogen . master . Broker ( ) router = mitogen . master . Router ( broker ) try : return func ( router , * args , ** kwargs ) finally : broker . shutdown ( ) broker . join ( )
def _from_dict ( cls , _dict ) : """Initialize a ValueCollection object from a json dictionary ."""
args = { } if 'values' in _dict : args [ 'values' ] = [ Value . _from_dict ( x ) for x in ( _dict . get ( 'values' ) ) ] else : raise ValueError ( 'Required property \'values\' not present in ValueCollection JSON' ) if 'pagination' in _dict : args [ 'pagination' ] = Pagination . _from_dict ( _dict . get ( '...
def fix_whitespace ( line , offset , replacement ) : """Replace whitespace at offset and return fixed line ."""
# Replace escaped newlines too left = line [ : offset ] . rstrip ( '\n\r \t\\' ) right = line [ offset : ] . lstrip ( '\n\r \t\\' ) if right . startswith ( '#' ) : return line else : return left + replacement + right
def _state_run ( self ) : '''Execute a state run based on information set in the minion config file'''
if self . opts [ 'startup_states' ] : if self . opts . get ( 'master_type' , 'str' ) == 'disable' and self . opts . get ( 'file_client' , 'remote' ) == 'remote' : log . warning ( 'Cannot run startup_states when \'master_type\' is set ' 'to \'disable\' and \'file_client\' is set to ' '\'remote\'. Skipping.' ...
def asmono ( samples : np . ndarray , channel : Union [ int , str ] = 0 ) -> np . ndarray : """convert samples to mono if they are not mono already . The returned array will always have the shape ( numframes , ) channel : the channel number to use , or ' mix ' to mix - down all channels"""
if numchannels ( samples ) == 1 : # it could be [ 1,2,3,4 , . . . ] , or [ [ 1 ] , [ 2 ] , [ 3 ] , [ 4 ] , . . . ] if isinstance ( samples [ 0 ] , float ) : return samples elif isinstance ( samples [ 0 ] , np . dnarray ) : return np . reshape ( samples , ( len ( samples ) , ) ) else : ...
def Rz_matrix ( theta ) : """Rotation matrix around the Z axis"""
return np . array ( [ [ np . cos ( theta ) , - np . sin ( theta ) , 0 ] , [ np . sin ( theta ) , np . cos ( theta ) , 0 ] , [ 0 , 0 , 1 ] ] )
def _maybe_pack_examples ( self , generator ) : """Wraps generator with packer if self . packed _ length ."""
if not self . packed_length : return generator return generator_utils . pack_examples ( generator , self . has_inputs , self . packed_length , spacing = self . packed_spacing , chop_long_sequences = not self . has_inputs )
def render_page ( path = None , user_content = False , context = None , username = None , password = None , render_offline = False , render_wide = False , render_inline = False , api_url = None , title = None , text = None , quiet = None , grip_class = None ) : """Renders the specified markup text to an HTML page a...
return create_app ( path , user_content , context , username , password , render_offline , render_wide , render_inline , api_url , title , text , False , quiet , grip_class ) . render ( )
def click ( self , x , y ) : '''Simulate click operation Args : - x ( int ) : position of x - y ( int ) : position of y Returns : self'''
self . _run_nowait ( 'target.tap({x: %d, y: %d})' % ( x / self . _scale , y / self . _scale ) ) return self
def get_reminder ( self , reminder_key ) : '''Gets one reminder Args : reminder _ keykey for the reminder to get return ( status code , reminder dict )'''
# required sanity check if reminder_key : return requests . codes . bad_request , None uri = '/' . join ( [ self . api_uri , self . reminders_suffix , reminder_key ] ) return self . _req ( 'get' , uri )
def get_choices ( module_name ) : """Retrieve members from ` ` module _ name ` ` ' s ` ` _ _ all _ _ ` ` list . : rtype : list"""
try : module = importlib . import_module ( module_name ) if hasattr ( module , '__all__' ) : return module . __all__ else : return [ name for name , _ in inspect . getmembers ( module , inspect . isclass ) if name != "device" ] except ImportError : return [ ]
async def reconnect ( self ) : """断线重连 ."""
self . clean ( ) try : self . writer . close ( ) except : pass self . closed = True await self . connect ( ) if self . debug : print ( "reconnect to {}" . format ( ( self . hostname , self . port ) ) )
def auth ( self ) : """Authenticate with the miner and obtain a JSON web token ( JWT ) ."""
response = requests . post ( parse . urljoin ( self . base_url , '/api/auth' ) , timeout = self . timeout , data = { 'username' : self . username , 'password' : self . password } ) response . raise_for_status ( ) json = response . json ( ) if 'jwt' not in json : raise ValueError ( "Not authorized: didn't receive to...
def get_upstream_fork_point ( self ) : """Get the most recent ancestor of HEAD that occurs on an upstream branch . First looks at the current branch ' s tracking branch , if applicable . If that doesn ' t work , looks at every other branch to find the most recent ancestor of HEAD that occurs on a tracking b...
possible_relatives = [ ] try : if not self . repo : return None try : active_branch = self . repo . active_branch except ( TypeError , ValueError ) : logger . debug ( "git is in a detached head state" ) return None # detached head else : tracking_branch = ...
def _parse_spacy_kwargs ( ** kwargs ) : """Supported args include : Args : n _ threads / num _ threads : Number of threads to use . Uses num _ cpus - 1 by default . batch _ size : The number of texts to accumulate into a common working set before processing . ( Default value : 1000)"""
n_threads = kwargs . get ( 'n_threads' ) or kwargs . get ( 'num_threads' ) batch_size = kwargs . get ( 'batch_size' ) if n_threads is None or n_threads is - 1 : n_threads = cpu_count ( ) - 1 if batch_size is None or batch_size is - 1 : batch_size = 1000 return n_threads , batch_size
def _pigpio_aio_command_ext ( self , cmd , p1 , p2 , p3 , extents , rl = True ) : """Runs an extended pigpio socket command . sl : = command socket and lock . cmd : = the command to be executed . p1 : = command parameter 1 ( if applicable ) . p2 : = command parameter 2 ( if applicable ) . p3 : = total siz...
with ( yield from self . _lock ) : ext = bytearray ( struct . pack ( 'IIII' , cmd , p1 , p2 , p3 ) ) for x in extents : if isinstance ( x , str ) : ext . extend ( _b ( x ) ) else : ext . extend ( x ) self . _loop . sock_sendall ( self . s , ext ) response = yield ...
def fit ( self , y , exogenous = None ) : """Fit the transformer Learns the value of ` ` lmbda ` ` , if not specified in the constructor . If defined in the constructor , is not re - learned . Parameters y : array - like or None , shape = ( n _ samples , ) The endogenous ( time - series ) array . exogen...
lam1 = self . lmbda lam2 = self . lmbda2 if lam2 < 0 : raise ValueError ( "lmbda2 must be a non-negative scalar value" ) if lam1 is None : y , _ = self . _check_y_exog ( y , exogenous ) _ , lam1 = stats . boxcox ( y , lmbda = None , alpha = None ) self . lam1_ = lam1 self . lam2_ = lam2 return self
def projects ( self , term , field = None , ** kwargs ) : """Search for projects . Defaults to project _ title . Other fields are : project _ reference project _ abstract Args : term ( str ) : Term to search for . kwargs ( dict ) : additional keywords passed into requests . session . get params keywor...
params = kwargs params [ 'q' ] = term if field : params [ 'f' ] = self . _FIELD_MAP [ field ] else : params [ 'f' ] = 'pro.t' baseuri = self . _BASE_URI + 'projects' res = self . session . get ( baseuri , params = params ) self . handle_http_error ( res ) return res
def addClassPath ( path1 ) : """Add a path to the java class path"""
global _CLASSPATHS path1 = _os . path . abspath ( path1 ) if _sys . platform == 'cygwin' : path1 = _posix2win ( path1 ) _CLASSPATHS . add ( str ( path1 ) )
async def _connect_one ( self , remote_address ) : '''Connect to the proxy and perform a handshake requesting a connection . Return the open socket on success , or the exception on failure .'''
loop = asyncio . get_event_loop ( ) for info in await loop . getaddrinfo ( str ( self . address . host ) , self . address . port , type = socket . SOCK_STREAM ) : # This object has state so is only good for one connection client = self . protocol ( remote_address , self . auth ) sock = socket . socket ( family ...
def map_query ( self , init_iter = 1000 , later_iter = 20 , dual_threshold = 0.0002 , integrality_gap_threshold = 0.0002 , tighten_triplet = True , max_triplets = 5 , max_iterations = 100 , prolong = False ) : """MAP query method using Max Product LP method . This returns the best assignment of the nodes in the f...
self . dual_threshold = dual_threshold self . integrality_gap_threshold = integrality_gap_threshold # Run MPLP initially for a maximum of init _ iter times . self . _run_mplp ( init_iter ) # If triplets are to be used for the tightening , we proceed as follows if tighten_triplet : self . _tighten_triplet ( max_iter...
def indexOf ( self , editor ) : """Returns the index of the inputed editor , or - 1 if not found . : param editor | < QtGui . QWidget > : return < int >"""
lay = self . layout ( ) for i in range ( lay . count ( ) ) : if lay . itemAt ( i ) . widget ( ) == editor : return i return - 1
def AddProperty ( self , interface , name , value ) : '''Add property to this object interface : D - Bus interface to add this to . For convenience you can specify ' ' here to add the property to the object ' s main interface ( as specified on construction ) . name : Property name . value : Property value...
if not interface : interface = self . interface try : self . props [ interface ] [ name ] raise dbus . exceptions . DBusException ( 'property %s already exists' % name , name = self . interface + '.PropertyExists' ) except KeyError : # this is what we expect pass # copy . copy removes one level of varia...
def _copy_with_changed_callback ( self , new_callback ) : '''Dev API used to wrap the callback with decorators .'''
return PeriodicCallback ( self . _document , new_callback , self . _period , self . _id )
def multi_index ( idx , dim ) : """Single to multi - index using graded reverse lexicographical notation . Parameters idx : int Index in interger notation dim : int The number of dimensions in the multi - index notation Returns out : tuple Multi - index of ` idx ` with ` len ( out ) = dim ` Exampl...
def _rec ( idx , dim ) : idxn = idxm = 0 if not dim : return ( ) if idx == 0 : return ( 0 , ) * dim while terms ( idxn , dim ) <= idx : idxn += 1 idx -= terms ( idxn - 1 , dim ) if idx == 0 : return ( idxn , ) + ( 0 , ) * ( dim - 1 ) while terms ( idxm , dim -...
def _set_config_defaults ( self , request , form , obj = None ) : """Cycle through app _ config _ values and sets the form value according to the options in the current apphook config . self . app _ config _ values is a dictionary containing config options as keys , form fields as values : : app _ config _ ...
for config_option , field in self . app_config_values . items ( ) : if field in form . base_fields : form . base_fields [ field ] . initial = self . get_config_data ( request , obj , config_option ) return form
def expm1 ( x ) : """Calculate exp ( x ) - 1"""
if isinstance ( x , UncertainFunction ) : mcpts = np . expm1 ( x . _mcpts ) return UncertainFunction ( mcpts ) else : return np . expm1 ( x )
def to_table_data ( self ) : """: raises ValueError : : raises pytablereader . error . ValidationError :"""
self . _validate_source_data ( ) self . _loader . inc_table_count ( ) yield TableData ( self . _make_table_name ( ) , [ "key" , "value" ] , [ record for record in self . _buffer . items ( ) ] , dp_extractor = self . _loader . dp_extractor , type_hints = self . _extract_type_hints ( ) , )
def _get_formatted_val ( self , obj , name , column ) : """Format the value of the attribute ' name ' from the given object"""
attr_path = name . split ( '.' ) val = None tmp_val = obj for attr in attr_path : tmp_val = getattr ( tmp_val , attr , None ) if tmp_val is None : break if tmp_val is not None : val = tmp_val return format_value ( column , val , self . config_key )
def InsertIntArg ( self , string = '' , ** unused_kwargs ) : """Inserts an Integer argument ."""
try : int_value = int ( string ) except ( TypeError , ValueError ) : raise errors . ParseError ( '{0:s} is not a valid integer.' . format ( string ) ) return self . InsertArg ( int_value )
def add_layer ( self , layer ) : """Add a layer ( TileTileLayer , TiledImageLayer , or TiledObjectGroup ) : param layer : TileTileLayer , TiledImageLayer , TiledObjectGroup object"""
assert ( isinstance ( layer , ( TiledTileLayer , TiledImageLayer , TiledObjectGroup ) ) ) self . layers . append ( layer ) self . layernames [ layer . name ] = layer
def setup_config ( config_directories = None , config_file = None , default_filename = "opentc.yml" ) : """Setup configuration"""
config_found = False config_file_path = None if config_file : config_file_path = config_file if os . path . isfile ( config_file_path ) and os . access ( config_file_path , os . R_OK ) : config_found = True else : for directory in config_directories : if directory is None : conti...
def copy ( self ) : '''Returns a copy of self'''
copy = Response ( self . app ) copy . status = self . status copy . headers = self . headers . copy ( ) copy . content_type = self . content_type return copy
def isoparse ( iso_str ) : """Parses the limited subset of ` ISO8601 - formatted time ` _ strings as returned by : meth : ` datetime . datetime . isoformat ` . > > > epoch _ dt = datetime . utcfromtimestamp ( 0) > > > iso _ str = epoch _ dt . isoformat ( ) > > > print ( iso _ str ) 1970-01-01T00:00:00 >...
dt_args = [ int ( p ) for p in _NONDIGIT_RE . split ( iso_str ) ] return datetime ( * dt_args )
def rollout ( policy , env , timestep_limit = None , add_noise = False , offset = 0 ) : """Do a rollout . If add _ noise is True , the rollout will take noisy actions with noise drawn from that stream . Otherwise , no action noise will be added . Parameters policy : tf object policy from which to draw act...
env_timestep_limit = env . spec . max_episode_steps timestep_limit = ( env_timestep_limit if timestep_limit is None else min ( timestep_limit , env_timestep_limit ) ) rews = [ ] t = 0 observation = env . reset ( ) for _ in range ( timestep_limit or 999999 ) : ac = policy . compute ( observation , add_noise = add_no...
def _key_changed ( self , client , cnxn_id , entry , data = None ) : """Callback when a gconf key changes"""
key = self . _fix_key ( entry . key ) [ len ( self . GCONF_DIR ) : ] value = self . _get_value ( entry . value , self . DEFAULTS [ key ] ) self . emit ( 'conf-changed' , key , value )
def GET_account_at ( self , path_info , account_addr , block_height ) : """Get the state ( s ) of an account at a particular point in history Returns [ { . . . } ]"""
if not check_account_address ( account_addr ) : return self . _reply_json ( { 'error' : 'Invalid address' } , status_code = 400 ) try : block_height = int ( block_height ) assert check_block ( block_height ) except : return self . _reply_json ( { 'error' : 'Invalid block height' } , status_code = 400 ) ...
def statusLine ( self ) : 'String of row and column stats .'
rowinfo = 'row %d/%d (%d selected)' % ( self . cursorRowIndex , self . nRows , len ( self . _selectedRows ) ) colinfo = 'col %d/%d (%d visible)' % ( self . cursorColIndex , self . nCols , len ( self . visibleCols ) ) return '%s %s' % ( rowinfo , colinfo )
def scheduler ( broker = None ) : """Creates a task from a schedule at the scheduled time and schedules next run"""
if not broker : broker = get_broker ( ) db . close_old_connections ( ) try : for s in Schedule . objects . exclude ( repeats = 0 ) . filter ( next_run__lt = timezone . now ( ) ) : args = ( ) kwargs = { } # get args , kwargs and hook if s . kwargs : try : # eval should...
def copy ( self , target = None , name = None ) : """Asynchronously creates a copy of this DriveItem and all it ' s child elements . : param target : target location to move to . If it ' s a drive the item will be moved to the root folder . : type target : drive . Folder or Drive : param name : a new name...
if target is None and name is None : raise ValueError ( 'Must provide a target or a name (or both)' ) if isinstance ( target , Folder ) : target_id = target . object_id drive_id = target . drive_id elif isinstance ( target , Drive ) : # we need the root folder root_folder = target . get_root_folder ( ) ...
def samefile ( self , other_path ) : """Return whether other _ path is the same or not as this file ( as returned by os . path . samefile ( ) ) ."""
if hasattr ( os . path , "samestat" ) : st = self . stat ( ) try : other_st = other_path . stat ( ) except AttributeError : other_st = os . stat ( other_path ) return os . path . samestat ( st , other_st ) else : filename1 = six . text_type ( self ) filename2 = six . text_type ( ...
def rot ( inputArray , theta = 0 , pc = ( 0 , 0 ) ) : """rotate input array with angle of theta : param inputArray : input array or list , e . g . np . array ( [ [ 0,0 ] , [ 0,1 ] , [ 0,2 ] ] ) or [ [ 0,0 ] , [ 0,1 ] , [ 0,2 ] ] : param theta : rotation angle in degree : param pc : central point coords ( x ...
if not isinstance ( inputArray , np . ndarray ) : inputArray = np . array ( inputArray ) if not isinstance ( pc , np . ndarray ) : pc = np . array ( pc ) theta = theta / 180.0 * np . pi # degree to rad mr = np . array ( [ [ np . cos ( theta ) , - np . sin ( theta ) ] , [ np . sin ( theta ) , np . cos ( theta ) ...
def congruent ( self , other ) : '''A congruent B True iff all angles of ' A ' equal angles in ' B ' and all side lengths of ' A ' equal all side lengths of ' B ' , boolean .'''
a = set ( self . angles ) b = set ( other . angles ) if len ( a ) != len ( b ) or len ( a . difference ( b ) ) != 0 : return False a = set ( self . sides ) b = set ( other . sides ) return len ( a ) == len ( b ) and len ( a . difference ( b ) ) == 0
def parse_network ( network_fp ) : """Parses network file and returns a network instance and a gene set . Attribute : network _ fp ( str ) : File path to a network file ."""
graph = nx . Graph ( ) gene_set = set ( ) with open ( network_fp ) as inFile : inFile . readline ( ) # Skip header . for line in inFile . readlines ( ) : gene1 , gene2 = line . strip ( ) . split ( ) graph . add_edge ( gene1 , gene2 ) gene_set . add ( gene1 ) gene_set . add ( ...
def hex ( self ) : """Emit the address in bare hex format ( aabbcc ) ."""
addrstr = '000000' if self . addr is not None : addrstr = binascii . hexlify ( self . addr ) . decode ( ) return addrstr
def has_preview ( self ) : """stub"""
# I had to add the following check because file record types don ' t seem to be implemented # correctly for raw edx Question objects if ( 'fileIds' not in self . my_osid_object . _my_map or 'preview' not in self . my_osid_object . _my_map [ 'fileIds' ] or self . my_osid_object . _my_map [ 'fileIds' ] [ 'preview' ] is N...
def render_content ( text , user_content = False , context = None , username = None , password = None , render_offline = False , api_url = None ) : """Renders the specified markup and returns the result ."""
renderer = ( GitHubRenderer ( user_content , context , api_url ) if not render_offline else OfflineRenderer ( user_content , context ) ) auth = ( username , password ) if username or password else None return renderer . render ( text , auth )
def upcaseTokens ( s , l , t ) : """Helper parse action to convert tokens to upper case ."""
return [ tt . upper ( ) for tt in map ( _ustr , t ) ]
def yaml_force_unicode ( ) : """Force pyyaml to return unicode values ."""
# # modified from | http : / / stackoverflow . com / a / 2967461 | if sys . version_info [ 0 ] == 2 : def construct_func ( self , node ) : return self . construct_scalar ( node ) yaml . Loader . add_constructor ( U ( 'tag:yaml.org,2002:str' ) , construct_func ) yaml . SafeLoader . add_constructor ( ...
def n_to_g ( self , n_interval ) : """convert a transcript ( n . ) interval to a genomic ( g . ) interval"""
frs , fre = n_interval . start . base - 1 , n_interval . end . base - 1 start_offset , end_offset = n_interval . start . offset , n_interval . end . offset if self . strand == - 1 : fre , frs = self . tgt_len - frs - 1 , self . tgt_len - fre - 1 start_offset , end_offset = - end_offset , - start_offset # return...
def add_source ( self , evidence_line , source , label = None , src_type = None ) : """Applies the triples : < evidence > < dc : source > < source > < source > < rdf : type > < type > < source > < rdfs : label > " label " TODO this should belong in a higher level class : param evidence _ line : str curie ...
self . graph . addTriple ( evidence_line , self . globaltt [ 'source' ] , source ) self . model . addIndividualToGraph ( source , label , src_type ) return
def get_daemon_stats ( self , details = False ) : """Send a HTTP request to the satellite ( GET / get _ daemon _ stats ) : return : Daemon statistics : rtype : dict"""
logger . debug ( "Get daemon statistics for %s, %s %s" , self . name , self . alive , self . reachable ) return self . con . get ( 'stats%s' % ( '?details=1' if details else '' ) )
def end_policy_update ( self ) : """Inform Metrics class that policy update has started ."""
if self . time_policy_update_start : self . delta_policy_update = time ( ) - self . time_policy_update_start else : self . delta_policy_update = 0 delta_train_start = time ( ) - self . time_training_start LOGGER . debug ( " Policy Update Training Metrics for {}: " "\n\t\tTime to update Policy: {:0.3f} s \n" "\t...
def setuptools_install_options ( local_storage_folder ) : """Return options to make setuptools use installations from the given folder . No other installation source is allowed ."""
if local_storage_folder is None : return [ ] # setuptools expects its find - links parameter to contain a list of link # sources ( either local paths , file : URLs pointing to folders or URLs # pointing to a file containing HTML links ) separated by spaces . That means # that , when specifying such items , whether ...
def run ( self , repo : str , branch : str , task : Task , * , depth : DepthDefinitionType = 1 , reference : ReferenceDefinitionType = None ) -> Result : """Runs the ` ` task ` ` using the configured backend . : param repo : Target git repository : param branch : Target git branch : param task : Task which wi...
self . validate_repo_url ( repo ) depth = self . validate_depth ( depth ) reference = self . validate_reference ( reference ) logger . info ( "Running Arca task %r for repo '%s' in branch '%s'" , task , repo , branch ) git_repo , repo_path = self . get_files ( repo , branch , depth = depth , reference = reference ) def...
def cli ( conf ) : """OpenVPN status initdb method"""
try : config = init_config ( conf ) debug = config . getboolean ( 'DEFAULT' , 'debug' ) conn = get_conn ( config . get ( 'DEFAULT' , 'statusdb' ) ) cur = conn . cursor ( ) sqlstr = '''create table client_status (session_id text PRIMARY KEY, username text, userip text, realip tex...
def update ( self , value = None , label = None ) : """Update the progress bar @ type value : int @ type label : str"""
if label : self . label = label super ( ProgressBar , self ) . update ( value )
def uavionix_adsb_out_cfg_send ( self , ICAO , callsign , emitterType , aircraftSize , gpsOffsetLat , gpsOffsetLon , stallSpeed , rfSelect , force_mavlink1 = False ) : '''Static data to configure the ADS - B transponder ( send within 10 sec of a POR and every 10 sec thereafter ) ICAO : Vehicle address ( 24 bit ...
return self . send ( self . uavionix_adsb_out_cfg_encode ( ICAO , callsign , emitterType , aircraftSize , gpsOffsetLat , gpsOffsetLon , stallSpeed , rfSelect ) , force_mavlink1 = force_mavlink1 )
def graphDensityContourPlot ( G , iters = 50 , layout = None , layoutScaleFactor = 1 , overlay = False , nodeSize = 10 , axisSamples = 100 , blurringFactor = .1 , contours = 15 , graphType = 'coloured' ) : """Creates a 3D plot giving the density of nodes on a 2D plane , as a surface in 3D . Most of the options ar...
from mpl_toolkits . mplot3d import Axes3D if not isinstance ( G , nx . classes . digraph . DiGraph ) and not isinstance ( G , nx . classes . graph . Graph ) : raise TypeError ( "{} is not a valid input." . format ( type ( G ) ) ) if layout is None : layout = nx . spring_layout ( G , scale = axisSamples - 1 , it...
def get_learning_path_session_for_objective_bank ( self , objective_bank_id = None ) : """Gets the OsidSession associated with the learning path service for the given objective bank . arg : objectiveBankId ( osid . id . Id ) : the Id of the ObjectiveBank return : ( osid . learning . LearningPathSession ) - ...
if not objective_bank_id : raise NullArgument if not self . supports_learning_path ( ) : raise Unimplemented ( ) try : from . import sessions except ImportError : raise OperationFailed ( ) try : session = sessions . LearningPathSession ( objective_bank_id , runtime = self . _runtime ) except Attribu...
def request ( self , path_segment , method = "GET" , headers = None , body = "" , owner = None , app = None , sharing = None ) : """Issues an arbitrary HTTP request to the REST path segment . This method is named to match ` ` httplib . request ` ` . This function makes a single round trip to the server . If *...
if headers is None : headers = [ ] path = self . authority + self . _abspath ( path_segment , owner = owner , app = app , sharing = sharing ) all_headers = headers + self . additional_headers + self . _auth_headers logging . debug ( "%s request to %s (headers: %s, body: %s)" , method , path , str ( all_headers ) , ...
def delete_user_favorite ( self , series_id ) : """Deletes the series of the provided id from the favorites list of the current user . : param series _ id : The TheTVDB id of the series . : return : a python dictionary with either the result of the search or an error from TheTVDB ."""
return self . parse_raw_response ( requests_util . run_request ( 'delete' , self . API_BASE_URL + '/user/favorites/%d' % series_id , headers = self . __get_header_with_auth ( ) ) )
def forward_message ( self , from_chat_id , message_id ) : """Forward a message from another chat to this chat . : param int from _ chat _ id : ID of the chat to forward the message from : param int message _ id : ID of the message to forward"""
return self . bot . api_call ( "forwardMessage" , chat_id = self . id , from_chat_id = from_chat_id , message_id = message_id , )
def append_item ( self , item ) : """Append new item to set"""
if not isinstance ( item , LR0Item ) : raise TypeError self . itemlist . append ( item )
def put_metric_data ( self , namespace , name , value = None , timestamp = None , unit = None , dimensions = None , statistics = None ) : """Publishes metric data points to Amazon CloudWatch . Amazon Cloudwatch associates the data points with the specified metric . If the specified metric does not exist , Amazo...
params = { 'Namespace' : namespace } self . build_put_params ( params , name , value = value , timestamp = timestamp , unit = unit , dimensions = dimensions , statistics = statistics ) return self . get_status ( 'PutMetricData' , params )
def add_children_gos ( self , gos ) : """Return children of input gos plus input gos ."""
lst = [ ] obo_dag = self . obo_dag get_children = lambda go_obj : list ( go_obj . get_all_children ( ) ) + [ go_obj . id ] for go_id in gos : go_obj = obo_dag [ go_id ] lst . extend ( get_children ( go_obj ) ) return set ( lst )
def get_accounts ( self , owner_id = None , member_id = None , properties = None ) : """GetAccounts . Get a list of accounts for a specific owner or a specific member . : param str owner _ id : ID for the owner of the accounts . : param str member _ id : ID for a member of the accounts . : param str propert...
query_parameters = { } if owner_id is not None : query_parameters [ 'ownerId' ] = self . _serialize . query ( 'owner_id' , owner_id , 'str' ) if member_id is not None : query_parameters [ 'memberId' ] = self . _serialize . query ( 'member_id' , member_id , 'str' ) if properties is not None : query_parameter...
def day ( t , now = None , format = '%B %d' ) : '''Date delta compared to ` ` t ` ` . You can override ` ` now ` ` to specify what date to compare to . You can override the date format by supplying a ` ` format ` ` parameter . : param t : timestamp , : class : ` datetime . date ` or : class : ` datetime . dat...
t1 = _to_date ( t ) t2 = _to_date ( now or datetime . datetime . now ( ) ) diff = t1 - t2 secs = _total_seconds ( diff ) days = abs ( diff . days ) if days == 0 : return _ ( 'today' ) elif days == 1 : if secs < 0 : return _ ( 'yesterday' ) else : return _ ( 'tomorrow' ) elif days == 7 : ...
def get_db_prep_save ( self , value ) : """Convert our JSON object to a string before we save"""
if not value : return super ( JSONField , self ) . get_db_prep_save ( "" ) else : return super ( JSONField , self ) . get_db_prep_save ( dumps ( value ) )
def run_norm ( net , df = None , norm_type = 'zscore' , axis = 'row' , keep_orig = False ) : '''A dataframe ( more accurately a dictionary of dataframes , e . g . mat , mat _ up . . . ) can be passed to run _ norm and a normalization will be run ( e . g . zscore ) on either the rows or columns'''
# df here is actually a dictionary of several dataframes , ' mat ' , ' mat _ orig ' , # etc if df is None : df = net . dat_to_df ( ) if norm_type == 'zscore' : df = zscore_df ( df , axis , keep_orig ) if norm_type == 'qn' : df = qn_df ( df , axis , keep_orig ) net . df_to_dat ( df )
def watch_docs ( ctx ) : """Run build the docs when a file changes ."""
try : import sphinx_autobuild # noqa except ImportError : print ( 'ERROR: watch task requires the sphinx_autobuild package.' ) print ( 'Install it with:' ) print ( ' pip install sphinx-autobuild' ) sys . exit ( 1 ) docs ( ctx ) ctx . run ( 'sphinx-autobuild {} {}' . format ( docs_dir , build_...
def get_user_permission_full_codename ( perm ) : """Returns ' app _ label . < perm > _ < usermodulename > ' . If standard ` ` auth . User ` ` is used , for ' change ' perm this would return ` ` auth . change _ user ` ` and if ` ` myapp . CustomUser ` ` is used it would return ` ` myapp . change _ customuser ` `...
User = get_user_model ( ) return '%s.%s_%s' % ( User . _meta . app_label , perm , User . _meta . module_name )
def get_clean_content ( self ) : """Implementation of the clean ( ) method ."""
fill_chars = { 'BLANK_TEMPLATE' : ' ' , 'ECHO_TEMPLATE' : '0' } for match in self . pattern . finditer ( self . html_content ) : start , end = match . start ( ) , match . end ( ) tag = _get_tag ( match ) if tag == 'ECHO' : self . _write_content ( start ) self . _index = start self . ...
def export ( self ) : """Generate a NIDM - Results export ."""
try : if not os . path . isdir ( self . export_dir ) : os . mkdir ( self . export_dir ) # Initialise main bundle self . _create_bundle ( self . version ) self . add_object ( self . software ) # Add model fitting steps if not isinstance ( self . model_fittings , list ) : self . mo...
def callback ( self , filename , lines , ** kwargs ) : """Sends log lines to redis servers"""
self . _logger . debug ( 'Redis transport called' ) timestamp = self . get_timestamp ( ** kwargs ) if kwargs . get ( 'timestamp' , False ) : del kwargs [ 'timestamp' ] namespaces = self . _beaver_config . get_field ( 'redis_namespace' , filename ) if not namespaces : namespaces = self . _namespace namespaces = ...
def lstm_cell ( hidden_size ) : """Wrapper function to create an LSTM cell ."""
return tf . contrib . rnn . LSTMCell ( hidden_size , use_peepholes = True , state_is_tuple = True )
def update ( name , password = None , fullname = None , description = None , home = None , homedrive = None , logonscript = None , profile = None , expiration_date = None , expired = None , account_disabled = None , unlock_account = None , password_never_expires = None , disallow_change_password = None ) : # pylint : d...
# pylint : enable = anomalous - backslash - in - string if six . PY2 : name = _to_unicode ( name ) password = _to_unicode ( password ) fullname = _to_unicode ( fullname ) description = _to_unicode ( description ) home = _to_unicode ( home ) homedrive = _to_unicode ( homedrive ) logonscript =...
def classify_users ( X_test , model , classifier_type , meta_model , upper_cutoff ) : """Uses a trained model and the unlabelled features to associate users with labels . The decision is done as per scikit - learn : http : / / scikit - learn . org / stable / modules / generated / sklearn . multiclass . OneVsRes...
if classifier_type == "LinearSVC" : prediction = model . decision_function ( X_test ) # prediction = penalize _ large _ classes ( prediction ) meta_prediction = meta_model . predict ( X_test ) meta_prediction = np . rint ( meta_prediction ) + 1 meta_prediction [ meta_prediction > upper_cutoff ] = up...
def format_timedelta ( dt : timedelta ) -> str : """Formats timedelta to readable format , e . g . 1h30min . : param dt : timedelta : return : str"""
seconds = int ( dt . total_seconds ( ) ) days , remainder = divmod ( seconds , 86400 ) hours , remainder = divmod ( remainder , 3600 ) minutes , seconds = divmod ( remainder , 60 ) s = "" if days > 0 : s += str ( days ) + "d" if hours > 0 : s += str ( hours ) + "h" if minutes > 0 : s += str ( minutes ) + "m...
def _fill_get_item_cache ( self , catalog , key ) : """get from redis , cache locally then return : param catalog : catalog name : param key : : return :"""
lang = self . _get_lang ( ) keylist = self . get_all ( catalog ) self . ITEM_CACHE [ lang ] [ catalog ] = dict ( [ ( i [ 'value' ] , i [ 'name' ] ) for i in keylist ] ) return self . ITEM_CACHE [ lang ] [ catalog ] . get ( key )
def get_out_srvc_node_ip_addr ( cls , tenant_id ) : """Retrieves the OUT service node IP address ."""
if tenant_id not in cls . serv_obj_dict : LOG . error ( "Fabric not prepared for tenant %s" , tenant_id ) return tenant_obj = cls . serv_obj_dict . get ( tenant_id ) out_subnet_dict = tenant_obj . get_out_ip_addr ( ) next_hop = str ( netaddr . IPAddress ( out_subnet_dict . get ( 'subnet' ) ) + 2 ) return next_h...
def update_columns_dict ( self , kwargs ) : """Update the value of a column or multiple columns by passing as a dict . For observable columns , provide the label of the observable itself and it will be found ( so long as it does not conflict with an existing non - observable column ) ."""
# make sure to do the geometric things that are needed for some of the # ComputedColumns first for key in ( 'triangles' , 'vertices' , 'centers' , 'vnormals' , 'tnormals' ) : if key in kwargs . keys ( ) : self . __setitem__ ( key , kwargs . pop ( key ) ) for k , v in kwargs . items ( ) : if isinstance (...
def normalize_commit_message ( commit_message ) : """Return a tuple of title and body from the commit message"""
split_commit_message = commit_message . split ( "\n" ) title = split_commit_message [ 0 ] body = "\n" . join ( split_commit_message [ 1 : ] ) return title , body . lstrip ( "\n" )
def get_urlpatterns ( self ) : """Returns the URL patterns managed by the considered factory / application ."""
return [ path ( _ ( 'topic/<str:slug>-<int:pk>/lock/' ) , self . topic_lock_view . as_view ( ) , name = 'topic_lock' , ) , path ( _ ( 'topic/<str:slug>-<int:pk>/unlock/' ) , self . topic_unlock_view . as_view ( ) , name = 'topic_unlock' , ) , path ( _ ( 'topic/<str:slug>-<int:pk>/delete/' ) , self . topic_delete_view ....
def generate_semantic_data_key ( used_semantic_keys ) : """Create a new and unique semantic data key : param list used _ semantic _ keys : Handed list of keys already in use : rtype : str : return : semantic _ data _ id"""
semantic_data_id_counter = - 1 while True : semantic_data_id_counter += 1 if "semantic data key " + str ( semantic_data_id_counter ) not in used_semantic_keys : break return "semantic data key " + str ( semantic_data_id_counter )
def convert_default ( self , field , ** params ) : """Return raw field ."""
for klass , ma_field in self . TYPE_MAPPING : if isinstance ( field , klass ) : return ma_field ( ** params ) return fields . Raw ( ** params )
def hostedzone_from_element ( zone ) : """Construct a L { HostedZone } instance from a I { HostedZone } XML element ."""
return HostedZone ( name = maybe_bytes_to_unicode ( zone . find ( "Name" ) . text ) . encode ( "ascii" ) . decode ( "idna" ) , identifier = maybe_bytes_to_unicode ( zone . find ( "Id" ) . text ) . replace ( u"/hostedzone/" , u"" ) , rrset_count = int ( zone . find ( "ResourceRecordSetCount" ) . text ) , reference = may...
def instruction_NEG_memory ( self , opcode , ea , m ) : """Negate memory"""
if opcode == 0x0 and ea == 0x0 and m == 0x0 : self . _wrong_NEG += 1 if self . _wrong_NEG > 10 : raise RuntimeError ( "Wrong PC ???" ) else : self . _wrong_NEG = 0 r = m * - 1 # same as : r = ~ m + 1 # log . debug ( " $ % 04x NEG $ % 02x from % 04x to $ % 02x " % ( # self . program _ counter , m , e...
def build_chunk ( oscillators ) : """Build an audio chunk and progress the oscillator states . Args : oscillators ( list ) : A list of oscillator . Oscillator objects to build chunks from Returns : str : a string of audio sample bytes ready to be written to a wave file"""
step_random_processes ( oscillators ) subchunks = [ ] for osc in oscillators : osc . amplitude . step_amp ( ) osc_chunk = osc . get_samples ( config . CHUNK_SIZE ) if osc_chunk is not None : subchunks . append ( osc_chunk ) if len ( subchunks ) : new_chunk = sum ( subchunks ) else : new_chun...
def set_reload_on_exception_params ( self , do_reload = None , etype = None , evalue = None , erepr = None ) : """Sets workers reload on exceptions parameters . : param bool do _ reload : Reload a worker when an exception is raised . : param str etype : Reload a worker when a specific exception type is raised ....
self . _set ( 'reload-on-exception' , do_reload , cast = bool ) self . _set ( 'reload-on-exception-type' , etype ) self . _set ( 'reload-on-exception-value' , evalue ) self . _set ( 'reload-on-exception-repr' , erepr ) return self . _section
def main ( arguments ) : """Parse arguments , request the urls , notify if different ."""
formatter_class = argparse . ArgumentDefaultsHelpFormatter parser = argparse . ArgumentParser ( description = __doc__ , formatter_class = formatter_class ) parser . add_argument ( 'infile' , help = "Input file" , type = argparse . FileType ( 'r' ) ) parser . add_argument ( '-o' , '--outfile' , help = "Output file" , de...
def set_range ( self , range ) : """Set the range of the instrument . A range is a tuple of two Notes or note strings ."""
if type ( range [ 0 ] ) == str : range [ 0 ] = Note ( range [ 0 ] ) range [ 1 ] = Note ( range [ 1 ] ) if not hasattr ( range [ 0 ] , 'name' ) : raise UnexpectedObjectError ( "Unexpected object '%s'. " "Expecting a mingus.containers.Note object" % range [ 0 ] ) self . range = range
def add ( self , obj = None , filename = None , data = None , info = { } , ** kwargs ) : """If a filename is supplied , it will be used . Otherwise , a filename will be generated from the supplied object . Note that if the explicit filename uses the { timestamp } field , it will be formatted upon export . T...
if [ filename , obj ] == [ None , None ] : raise Exception ( "Either filename or a HoloViews object is " "needed to create an entry in the archive." ) elif obj is None and not self . parse_fields ( filename ) . issubset ( { 'timestamp' } ) : raise Exception ( "Only the {timestamp} formatter may be used unless a...
def call_alert ( * args , ** kwargs ) : '''Lamp alert Options : * * * id * * : Specifies a device ID . Can be a comma - separated values . All , if omitted . * * * on * * : Turns on or off an alert . Default is True . CLI Example : . . code - block : : bash salt ' * ' hue . alert salt ' * ' hue . aler...
res = dict ( ) devices = _get_lights ( ) for dev_id in 'id' not in kwargs and sorted ( devices . keys ( ) ) or _get_devices ( kwargs ) : res [ dev_id ] = _set ( dev_id , { "alert" : kwargs . get ( "on" , True ) and "lselect" or "none" } ) return res
def PopItem ( self ) : """Pops an item off the queue . If no ZeroMQ socket has been created , one will be created the first time this method is called . Returns : object : item from the queue . Raises : KeyboardInterrupt : if the process is sent a KeyboardInterrupt while popping an item . QueueEmpty...
if not self . _zmq_socket : self . _CreateZMQSocket ( ) if not self . _closed_event or not self . _terminate_event : raise RuntimeError ( 'Missing closed or terminate event.' ) logger . debug ( 'Pop on {0:s} queue, port {1:d}' . format ( self . name , self . port ) ) last_retry_timestamp = time . time ( ) + sel...
def add_auth_attempt ( self , auth_type , successful , ** kwargs ) : """: param username : : param password : : param auth _ type : possible values : plain : plaintext username / password : return :"""
entry = { 'timestamp' : datetime . utcnow ( ) , 'auth' : auth_type , 'id' : uuid . uuid4 ( ) , 'successful' : successful } log_string = '' for key , value in kwargs . iteritems ( ) : if key == 'challenge' or key == 'response' : entry [ key ] = repr ( value ) else : entry [ key ] = value ...