signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_next_objective ( self ) : """Gets the next Objective in this list . return : ( osid . learning . Objective ) - the next Objective in this list . The has _ next ( ) method should be used to test that a next Objective is available before calling this method . raise : IllegalState - no more elements ...
try : next_object = next ( self ) except StopIteration : raise IllegalState ( 'no more elements available in this list' ) except Exception : # Need to specify exceptions here ! raise OperationFailed ( ) else : return next_object
def get_neuroglancer_link ( self , resource , resolution , x_range , y_range , z_range , ** kwargs ) : """Get a neuroglancer link of the cutout specified from the host specified in the remote configuration step . Args : resource ( intern . resource . Resource ) : Resource compatible with cutout operations . r...
return self . service . get_neuroglancer_link ( resource , resolution , x_range , y_range , z_range , self . url_prefix , ** kwargs )
def query ( ** kwargs ) : """Queries for work items based on their criteria . Args : queue _ name : Optional queue name to restrict to . build _ id : Optional build ID to restrict to . release _ id : Optional release ID to restrict to . run _ id : Optional run ID to restrict to . count : How many tasks ...
count = kwargs . get ( 'count' , None ) task_list = _query ( ** kwargs ) task_dict_list = [ _task_to_dict ( task ) for task in task_list ] if count == 1 : if not task_dict_list : return None else : return task_dict_list [ 0 ] return task_dict_list
def GetElevation ( self , latitude , longitude , timeout = 0 ) : '''Returns the altitude ( m ASL ) of a given lat / long pair , or None if unknown'''
if latitude is None or longitude is None : return None if self . database == 'srtm' : TileID = ( numpy . floor ( latitude ) , numpy . floor ( longitude ) ) if TileID in self . tileDict : alt = self . tileDict [ TileID ] . getAltitudeFromLatLon ( latitude , longitude ) else : tile = self ...
def get_multireddits ( self , redditor , * args , ** kwargs ) : """Return a list of multireddits belonging to a redditor . : param redditor : The username or Redditor object to find multireddits from . : returns : The json response from the server The additional parameters are passed directly into : meth ...
redditor = six . text_type ( redditor ) url = self . config [ 'multireddit_user' ] . format ( user = redditor ) return self . request_json ( url , * args , ** kwargs )
def pipe_strtransform ( context = None , _INPUT = None , conf = None , ** kwargs ) : """A string module that splits a string into tokens delimited by separators . Loopable . Parameters context : pipe2py . Context object _ INPUT : iterable of items or strings conf : { ' transformation ' : { value ' : < ' s...
splits = get_splits ( _INPUT , conf , ** cdicts ( opts , kwargs ) ) parsed = utils . dispatch ( splits , * get_dispatch_funcs ( ) ) _OUTPUT = starmap ( parse_result , parsed ) return _OUTPUT
def reload ( self ) : """Create a new partition scheme . A scheme defines which utterances are in which partition . The scheme only changes after every call if ` ` self . shuffle = = True ` ` . Returns : list : List of PartitionInfo objects , defining the new partitions ( same as ` ` self . partitions ` ` )""...
# Create the order in which utterances will be loaded utt_ids = sorted ( self . utt_ids ) if self . shuffle : self . rand . shuffle ( utt_ids ) partitions = [ ] current_partition = PartitionInfo ( ) for utt_id in utt_ids : utt_size = self . utt_sizes [ utt_id ] utt_lengths = self . utt_lengths [ utt_id ] ...
def convert_binary_field_to_attachment ( env , field_spec ) : """This method converts the 8.0 binary fields to attachments like Odoo 9.0 makes with the new attachment = True attribute . It has to be called on post - migration script , as there ' s a call to get the res _ name of the target model , which is no...
logger = logging . getLogger ( 'OpenUpgrade' ) attachment_model = env [ 'ir.attachment' ] for model_name in field_spec : model = env [ model_name ] for field , column in field_spec [ model_name ] : if column is None : column = openupgrade . get_legacy_name ( field ) logger . info ( "...
def _calc_b ( w , aod700 ) : """Calculate the b coefficient ."""
b1 = 0.00925 * aod700 ** 2 + 0.0148 * aod700 - 0.0172 b0 = - 0.7565 * aod700 ** 2 + 0.5057 * aod700 + 0.4557 b = b1 * np . log ( w ) + b0 return b
def select_resources ( self , * args , ** kwargs ) : """Copy the query and add filtering by resource labels . Examples : : query = query . select _ resources ( zone = ' us - central1 - a ' ) query = query . select _ resources ( zone _ prefix = ' europe - ' ) query = query . select _ resources ( resource _ t...
new_query = copy . deepcopy ( self ) new_query . _filter . select_resources ( * args , ** kwargs ) return new_query
def _Pcn ( x , dsz , Nv , dimN = 2 , dimC = 1 ) : """Projection onto dictionary update constraint set : support projection and normalisation . The result has the full spatial dimensions of the input . Parameters x : array _ like Input array dsz : tuple Filter support size ( s ) , specified using the s...
return normalise ( zpad ( bcrop ( x , dsz , dimN ) , Nv ) , dimN + dimC )
def by_skills ( queryset , skill_string = None ) : """Filter queryset by a comma delimeted skill list"""
if skill_string : operator , items = get_operator_and_items ( skill_string ) q_obj = SQ ( ) for s in items : if len ( s ) > 0 : q_obj . add ( SQ ( skills = s ) , operator ) queryset = queryset . filter ( q_obj ) return queryset
def exec_command ( self , cmd ) : """Executes the given command . This method executes a command by calling the DLL ' s exec method . Direct API methods should be prioritized over calling this method . Args : self ( JLink ) : the ` ` JLink ` ` instance cmd ( str ) : the command to run Returns : The re...
err_buf = ( ctypes . c_char * self . MAX_BUF_SIZE ) ( ) res = self . _dll . JLINKARM_ExecCommand ( cmd . encode ( ) , err_buf , self . MAX_BUF_SIZE ) err_buf = ctypes . string_at ( err_buf ) . decode ( ) if len ( err_buf ) > 0 : # This is how they check for error in the documentation , so check # this way as well . ...
def digest ( self , ** args ) : """calculate a digest based on the hash of the XML content"""
return String ( XML . canonicalized_string ( self . root ) ) . digest ( ** args )
def encode_quopri ( msg ) : """Encode the message ' s payload in quoted - printable . Also , add an appropriate Content - Transfer - Encoding header ."""
orig = msg . get_payload ( ) encdata = _qencode ( orig ) msg . set_payload ( encdata ) msg [ 'Content-Transfer-Encoding' ] = 'quoted-printable'
def get_bool_attr ( self , name ) : """Returns the value of a boolean HTML attribute like ` checked ` or ` disabled `"""
val = self . get_attr ( name ) return val is not None and val . lower ( ) in ( "true" , name )
def create_config_files ( directory ) : """Initialize directory ready for vpn walker : param directory : the path where you want this to happen : return :"""
# Some constant strings config_zip_url = "https://s3-us-west-1.amazonaws.com/heartbleed/linux/linux-files.zip" if not os . path . exists ( directory ) : os . makedirs ( directory ) logging . info ( "Starting to download PureVPN config file zip" ) url_opener = urllib . URLopener ( ) zip_path = os . path . join ( dir...
def create_migration_ctx ( ** kwargs ) : """Create an alembic migration context ."""
env = EnvironmentContext ( Config ( ) , None ) env . configure ( connection = db . engine . connect ( ) , sqlalchemy_module_prefix = 'db.' , ** kwargs ) return env . get_context ( )
def _parse_tile_part_bit_stream ( self , fptr , sod_marker , tile_length ) : """Parse the tile part bit stream for SOP , EPH marker segments ."""
read_buffer = fptr . read ( tile_length ) # The tile length could possibly be too large and extend past # the end of file . We need to be a bit resilient . count = min ( tile_length , len ( read_buffer ) ) packet = np . frombuffer ( read_buffer , dtype = np . uint8 , count = count ) indices = np . where ( packet == 0xf...
async def start ( self ) : """Enter the transaction or savepoint block ."""
self . __check_state_base ( 'start' ) if self . _state is TransactionState . STARTED : raise apg_errors . InterfaceError ( 'cannot start; the transaction is already started' ) con = self . _connection if con . _top_xact is None : if con . _protocol . is_in_transaction ( ) : raise apg_errors . InterfaceE...
def audio_set_format ( self , format , rate , channels ) : '''Set decoded audio format . This only works in combination with L { audio _ set _ callbacks } ( ) , and is mutually exclusive with L { audio _ set _ format _ callbacks } ( ) . @ param format : a four - characters string identifying the sample format...
return libvlc_audio_set_format ( self , str_to_bytes ( format ) , rate , channels )
def pkginfo ( name , version , arch , repoid , install_date = None , install_date_time_t = None ) : '''Build and return a pkginfo namedtuple'''
pkginfo_tuple = collections . namedtuple ( 'PkgInfo' , ( 'name' , 'version' , 'arch' , 'repoid' , 'install_date' , 'install_date_time_t' ) ) return pkginfo_tuple ( name , version , arch , repoid , install_date , install_date_time_t )
def create_datapoint ( value , timestamp = None , ** tags ) : """Creates a single datapoint dict with a value , timestamp and tags . : param value : Value of the datapoint . Type depends on the id ' s MetricType : param timestamp : Optional timestamp of the datapoint . Uses client current time if not set . Mill...
if timestamp is None : timestamp = time_millis ( ) if type ( timestamp ) is datetime : timestamp = datetime_to_time_millis ( timestamp ) item = { 'timestamp' : timestamp , 'value' : value } if tags is not None : item [ 'tags' ] = tags return item
def user_password_update ( user_id = None , name = None , password = None , profile = None , ** connection_args ) : '''Update a user ' s password ( keystone user - password - update ) CLI Examples : . . code - block : : bash salt ' * ' keystone . user _ password _ update c965f79c4f864eaaa9c3b41904e67082 passw...
kstone = auth ( profile , ** connection_args ) if name : for user in kstone . users . list ( ) : if user . name == name : user_id = user . id break if not user_id : return { 'Error' : 'Unable to resolve user id' } if _OS_IDENTITY_API_VERSION > 2 : kstone . users . update ( us...
def _on_namreply ( self , connection , event ) : """event . arguments [ 0 ] = = " @ " for secret channels , " * " for private channels , " = " for others ( public channels ) event . arguments [ 1 ] = = channel event . arguments [ 2 ] = = nick list"""
ch_type , channel , nick_list = event . arguments if channel == '*' : # User is not in any visible channel # http : / / tools . ietf . org / html / rfc2812 # section - 3.2.5 return for nick in nick_list . split ( ) : nick_modes = [ ] if nick [ 0 ] in self . connection . features . prefix : nick_mode...
def convert_missing_indexer ( indexer ) : """reverse convert a missing indexer , which is a dict return the scalar indexer and a boolean indicating if we converted"""
if isinstance ( indexer , dict ) : # a missing key ( but not a tuple indexer ) indexer = indexer [ 'key' ] if isinstance ( indexer , bool ) : raise KeyError ( "cannot use a single bool to index into setitem" ) return indexer , True return indexer , False
def new_canvas ( self , figure = None , col = 1 , row = 1 , projection = '2d' , xlabel = None , ylabel = None , zlabel = None , title = None , xlim = None , ylim = None , zlim = None , ** kwargs ) : """Return a canvas , kwargupdate for your plotting library . if figure is not None , create a canvas in the figure ...
raise NotImplementedError ( "Implement all plot functions in AbstractPlottingLibrary in order to use your own plotting library" )
def missing_parameter_values ( self , parameter_values ) : """Checks if the given input contains values for all parameters used by this template : param dict parameter _ values : Dictionary of values for each parameter used in the template : return list : List of names of parameters that are missing . : raise...
if not self . _is_valid_parameter_values ( parameter_values ) : raise InvalidParameterValues ( "Parameter values are required to process a policy template" ) return list ( set ( self . parameters . keys ( ) ) - set ( parameter_values . keys ( ) ) )
def register ( self , subject , avro_schema ) : """POST / subjects / ( string : subject ) / versions Register a schema with the registry under the given subject and receive a schema id . avro _ schema must be a parsed schema from the python avro library Multiple instances of the same schema will result in c...
schemas_to_id = self . subject_to_schema_ids [ subject ] schema_id = schemas_to_id . get ( avro_schema , None ) if schema_id is not None : return schema_id # send it up url = '/' . join ( [ self . url , 'subjects' , subject , 'versions' ] ) # body is { schema : json _ string } body = { 'schema' : json . dumps ( avr...
def pkcs_mgf1 ( mgfSeed , maskLen , h ) : """Implements generic MGF1 Mask Generation function as described in Appendix B . 2.1 of RFC 3447 . The hash function is passed by name . valid values are ' md2 ' , ' md4 ' , ' md5 ' , ' sha1 ' , ' tls , ' sha256 ' , ' sha384 ' and ' sha512 ' . Returns None on error . ...
# steps are those of Appendix B . 2.1 if not h in _hashFuncParams : warning ( "pkcs_mgf1: invalid hash (%s) provided" ) return None hLen = _hashFuncParams [ h ] [ 0 ] hFunc = _hashFuncParams [ h ] [ 1 ] if maskLen > 2 ** 32 * hLen : warning ( "pkcs_mgf1: maskLen > 2**32 * hLen" ) return None T = "" maxC...
def _get_or_create_group_parent ( message_body , user_id ) : """Determine if the given task belongs to a group or not , and if so , get or create a status record for the group . Arguments : message _ body ( dict ) : The body of the before _ task _ publish signal for the task in question user _ id ( int ) : Th...
parent_id = message_body . get ( 'taskset' , None ) if not parent_id : # Not part of a group return None parent_class = 'celery.group' parent_name = message_body [ 'kwargs' ] . get ( 'user_task_name' , '' ) parent , _ = UserTaskStatus . objects . get_or_create ( task_id = parent_id , defaults = { 'is_container' : T...
def _onWhat ( self , name , line , pos , absPosition ) : """Memorizes an imported item"""
self . __lastImport . what . append ( ImportWhat ( name , line , pos , absPosition ) )
def find ( self , * tags ) : """Find containers that matches set of tags : param tags : : return :"""
tags = list ( map ( str , tags ) ) return self . _client . json ( 'corex.find' , { 'tags' : tags } )
def first ( values , axis , skipna = None ) : """Return the first non - NA elements in this array along the given axis"""
if ( skipna or skipna is None ) and values . dtype . kind not in 'iSU' : # only bother for dtypes that can hold NaN _fail_on_dask_array_input_skipna ( values ) return nanfirst ( values , axis ) return take ( values , 0 , axis = axis )
def start_task ( self , task ) : """Begin logging of a task Stores the time this task was started in order to return time lapsed when ` complete _ task ` is called . Parameters task : str Name of the task to be started"""
self . info ( "Calculating {}..." . format ( task ) ) self . tasks [ task ] = self . timer ( )
def add ( self , packet ) : """Add the given Packet to this PacketHistory ."""
for name in self . _names : value = getattr ( packet , name ) if value is not None : self . _dict [ name ] = value
def description ( tag ) : """Gets a list of descriptions given the tag . : param str tag : ( hyphen - separated ) tag . : return : list of string descriptions . The return list can be empty ."""
tag_object = Tag ( tag ) results = [ ] results . extend ( tag_object . descriptions ) subtags = tag_object . subtags for subtag in subtags : results += subtag . description return results
def exp ( computation : BaseComputation , gas_per_byte : int ) -> None : """Exponentiation"""
base , exponent = computation . stack_pop ( num_items = 2 , type_hint = constants . UINT256 ) bit_size = exponent . bit_length ( ) byte_size = ceil8 ( bit_size ) // 8 if exponent == 0 : result = 1 elif base == 0 : result = 0 else : result = pow ( base , exponent , constants . UINT_256_CEILING ) computation ...
def __load_all ( self , config_filename ) : """Loads all stored routines into the RDBMS instance . : param str config _ filename : string The filename of the configuration file ."""
self . _read_configuration_file ( config_filename ) self . connect ( ) self . __find_source_files ( ) self . _get_column_type ( ) self . __read_stored_routine_metadata ( ) self . __get_constants ( ) self . _get_old_stored_routine_info ( ) self . _get_correct_sql_mode ( ) self . __load_stored_routines ( ) self . _drop_o...
def replies ( self , delegate , params = { } , extra_args = None ) : """Get the most recent replies for the authenticating user . See search for example of how results are returned ."""
return self . __get ( '/statuses/replies.atom' , delegate , params , extra_args = extra_args )
def get_model_fields ( model , add_reserver_flag = True ) : """Creating fields suit for model _ config , id will be skipped ."""
import uliweb . orm as orm fields = [ ] m = { 'type' : 'type_name' , 'hint' : 'hint' , 'default' : 'default' , 'required' : 'required' } m1 = { 'index' : 'index' , 'unique' : 'unique' } for name , prop in model . properties . items ( ) : if name == 'id' : continue d = { } for k , v in m . items ( ) ...
def _initURL ( self , org_url , referer_url ) : """sets proper URLs for AGOL"""
if org_url is not None and org_url != '' : if not org_url . startswith ( 'http://' ) and not org_url . startswith ( 'https://' ) : org_url = 'https://' + org_url self . _org_url = org_url if self . _org_url . lower ( ) . find ( '/sharing/rest' ) > - 1 : self . _url = self . _org_url else...
def modify_handle_value ( self , handle , ttl = None , add_if_not_exist = True , ** kvpairs ) : '''Modify entries ( key - value - pairs ) in a handle record . If the key does not exist yet , it is created . * Note : * We assume that a key exists only once . In case a key exists several time , an exception wil...
LOGGER . debug ( 'modify_handle_value...' ) # Read handle record : handlerecord_json = self . retrieve_handle_record_json ( handle ) if handlerecord_json is None : msg = 'Cannot modify unexisting handle' raise HandleNotFoundException ( handle = handle , msg = msg ) list_of_entries = handlerecord_json [ 'values'...
def get_atlas_zonefile_data ( zonefile_hash , zonefile_dir , check = True ) : """Get a serialized cached zonefile from local disk Return None if not found"""
zonefile_path = atlas_zonefile_path ( zonefile_dir , zonefile_hash ) zonefile_path_legacy = atlas_zonefile_path_legacy ( zonefile_dir , zonefile_hash ) for zfp in [ zonefile_path , zonefile_path_legacy ] : if not os . path . exists ( zfp ) : continue if check : res = _read_atlas_zonefile ( zfp ,...
def get_robust_background_threshold ( image , mask = None , lower_outlier_fraction = 0.05 , upper_outlier_fraction = 0.05 , deviations_above_average = 2.0 , average_fn = np . mean , variance_fn = np . std ) : """Calculate threshold based on mean & standard deviation The threshold is calculated by trimming the top...
cropped_image = np . array ( image . flat ) if mask is None else image [ mask ] n_pixels = np . product ( cropped_image . shape ) if n_pixels < 3 : return 0 cropped_image . sort ( ) if cropped_image [ 0 ] == cropped_image [ - 1 ] : return cropped_image [ 0 ] low_chop = int ( round ( n_pixels * lower_outlier_fra...
def start_tensorboard ( args ) : '''start tensorboard'''
experiment_id = check_experiment_id ( args ) experiment_config = Experiments ( ) experiment_dict = experiment_config . get_all_experiments ( ) config_file_name = experiment_dict [ experiment_id ] [ 'fileName' ] nni_config = Config ( config_file_name ) rest_port = nni_config . get_config ( 'restServerPort' ) rest_pid = ...
def create ( vm_ ) : '''Create a single Packet VM .'''
name = vm_ [ 'name' ] if not is_profile_configured ( vm_ ) : return False __utils__ [ 'cloud.fire_event' ] ( 'event' , 'starting create' , 'salt/cloud/{0}/creating' . format ( name ) , args = __utils__ [ 'cloud.filter_event' ] ( 'creating' , vm_ , [ 'name' , 'profile' , 'provider' , 'driver' ] ) , sock_dir = __opts...
def convert_value ( value , source_currency , target_currency ) : """Converts the price of a currency to another one using exchange rates : param price : the price value : param type : decimal : param source _ currency : source ISO - 4217 currency code : param type : str : param target _ currency : target...
# If price currency and target currency is same # return given currency as is if source_currency == target_currency : return value rate = get_rate ( source_currency , target_currency ) return value * rate
def eye ( n , d = None ) : """Creates an identity TT - matrix"""
c = _matrix . matrix ( ) c . tt = _vector . vector ( ) if d is None : n0 = _np . asanyarray ( n , dtype = _np . int32 ) c . tt . d = n0 . size else : n0 = _np . asanyarray ( [ n ] * d , dtype = _np . int32 ) c . tt . d = d c . n = n0 . copy ( ) c . m = n0 . copy ( ) c . tt . n = ( c . n ) * ( c . m ) c ...
def start_app ( self , bundle_id ) : '''Start app by bundle _ id Args : - bundle _ id ( string ) : ex com . netease . my Returns : idevicedebug subprocess instance'''
idevicedebug = must_look_exec ( 'idevicedebug' ) # run in background kwargs = { 'stdout' : subprocess . PIPE , 'stderr' : subprocess . PIPE } if sys . platform != 'darwin' : kwargs [ 'close_fds' ] = True return subprocess . Popen ( [ idevicedebug , "--udid" , self . udid , 'run' , bundle_id ] , ** kwargs )
def text ( self , paths , wholetext = False , lineSep = None ) : """Loads text files and returns a : class : ` DataFrame ` whose schema starts with a string column named " value " , and followed by partitioned columns if there are any . The text files must be encoded as UTF - 8. By default , each line in th...
self . _set_opts ( wholetext = wholetext , lineSep = lineSep ) if isinstance ( paths , basestring ) : paths = [ paths ] return self . _df ( self . _jreader . text ( self . _spark . _sc . _jvm . PythonUtils . toSeq ( paths ) ) )
def validate_header ( cls , header : BlockHeader , parent_header : BlockHeader , check_seal : bool = True ) -> None : """: raise eth . exceptions . ValidationError : if the header is not valid"""
if parent_header is None : # to validate genesis header , check if it equals canonical header at block number 0 raise ValidationError ( "Must have access to parent header to validate current header" ) else : validate_length_lte ( header . extra_data , 32 , title = "BlockHeader.extra_data" ) validate_gas_lim...
def _decode16 ( self , offset ) : """Decode an UTF - 16 String at the given offset : param offset : offset of the string inside the data : return : str"""
str_len , skip = self . _decode_length ( offset , 2 ) offset += skip # The len is the string len in utf - 16 units encoded_bytes = str_len * 2 data = self . m_charbuff [ offset : offset + encoded_bytes ] assert self . m_charbuff [ offset + encoded_bytes : offset + encoded_bytes + 2 ] == b"\x00\x00" , "UTF-16 String is ...
def find_video_by_url ( self , video_url ) : """doc : http : / / open . youku . com / docs / doc ? id = 44"""
url = 'https://openapi.youku.com/v2/videos/show_basic.json' params = { 'client_id' : self . client_id , 'video_url' : video_url } r = requests . get ( url , params = params ) check_error ( r ) return r . json ( )
def parse_name_altree ( record ) : """Parse NAME structure assuming ALTREE dialect . In ALTREE dialect maiden name ( if present ) is saved as SURN sub - record and is also appended to family name in parens . Given name is saved in GIVN sub - record . Few examples : No maiden name : 1 NAME John / Smith / ...
name_tuple = split_name ( record . value ) if name_tuple [ 1 ] == '?' : name_tuple = ( name_tuple [ 0 ] , '' , name_tuple [ 2 ] ) maiden = record . sub_tag_value ( "SURN" ) if maiden : # strip " ( maiden ) " from family name ending = '(' + maiden + ')' surname = name_tuple [ 1 ] if surname . endswith ( ...
def find_multiplicity ( knot , knot_vector , ** kwargs ) : """Finds knot multiplicity over the knot vector . Keyword Arguments : * ` ` tol ` ` : tolerance ( delta ) value for equality checking : param knot : knot or parameter , : math : ` u ` : type knot : float : param knot _ vector : knot vector , : mat...
# Get tolerance value tol = kwargs . get ( 'tol' , 10e-8 ) mult = 0 # initial multiplicity for kv in knot_vector : if abs ( knot - kv ) <= tol : mult += 1 return mult
def find_model_by_table_name ( name ) : """Find a model reference by its table name"""
for model in ModelBase . _decl_class_registry . values ( ) : if hasattr ( model , '__table__' ) and model . __table__ . fullname == name : return model return None
async def container ( self , container = None , container_type = None , params = None ) : """Loads / dumps container : return :"""
if hasattr ( container_type , 'blob_serialize' ) : container = container_type ( ) if container is None else container return await container . blob_serialize ( self , elem = container , elem_type = container_type , params = params ) # Container entry version + container if self . writing : return await self...
def from_fields ( cls , ** kwargs ) : '''Create an ` Atom ` instance from a set of fields . This is a slightly faster way to initialize an Atom . * * Example * * > > > Atom . from _ fields ( type = ' Ar ' , r _ array = np . array ( [ 0.0 , 0.0 , 0.0 ] ) , mass = 39.948, export = { } )'''
obj = cls . __new__ ( cls ) for name , field in obj . __fields__ . items ( ) : if name in kwargs : field . value = kwargs [ name ] return obj
def _predicate ( self , i ) : """Given a valid datetime or slace , return the predicate portion of the SQL query , a boolean indicating whether multiple items are expected from the result , and a dictionary of parameters for the query"""
if isinstance ( i , slice ) : if i . step is not None : raise TypeError ( "Slice step not permitted" ) if ( ( i . start is not None and not isinstance ( i . start , datetime ) ) or ( i . stop is not None and not isinstance ( i . stop , datetime ) ) ) : raise TypeError ( "Slice indices must be {}...
def combination_step ( self ) : """Build next update by a smart combination of previous updates . ( standard FISTA : cite : ` beck - 2009 - fast ` ) ."""
# Update t step tprv = self . t self . t = 0.5 * float ( 1. + np . sqrt ( 1. + 4. * tprv ** 2 ) ) # Update Y if not self . opt [ 'FastSolve' ] : self . Yprv = self . Y . copy ( ) self . Y = self . X + ( ( tprv - 1. ) / self . t ) * ( self . X - self . Xprv )
def parse_stack_refs ( stack_references : List [ str ] ) -> List [ str ] : '''Check if items included in ` stack _ references ` are Senza definition file paths or stack name reference . If Senza definition file path , substitute the definition file path by the stack name in the same position on the list .'''
stack_names = [ ] references = list ( stack_references ) references . reverse ( ) while references : current = references . pop ( ) # current that might be a file file_path = os . path . abspath ( current ) if os . path . exists ( file_path ) and os . path . isfile ( file_path ) : try : ...
def format_raw_data ( self , tpe , raw_data ) : """uses type to format the raw information to a dictionary usable by the mapper"""
if tpe == 'text' : formatted_raw_data = self . parse_text_to_dict ( raw_data ) elif tpe == 'file' : formatted_raw_data = self . parse_file_to_dict ( raw_data ) else : formatted_raw_data = { 'ERROR' : 'unknown data type' , 'data' : [ raw_data ] } return formatted_raw_data
def tryload ( self , cfgstr = None ) : """Like load , but returns None if the load fails"""
if cfgstr is None : cfgstr = self . cfgstr if cfgstr is None : import warnings warnings . warn ( 'No cfgstr given in Cacher constructor or call' ) cfgstr = '' # assert cfgstr is not None , ( # ' must specify cfgstr in constructor or call ' ) if not self . enabled : if self . verbose > 0 : pr...
def _read_ascii ( self ) : """Reads data and metadata from ASCII format ."""
# NOTE : ascii files store binned data using C - like ordering . # Dimensions are iterated like x , y , z ( so z changes fastest ) header_str = '' with open ( self . path ) as f : for line in f : if line . startswith ( '#' ) : header_str += line self . _read_header ( header_str ) data = np . loa...
def cos_distance ( t1 , t2 , epsilon = 1e-12 , name = None ) : """Cos distance between t1 and t2 and caps the gradient of the Square Root . Args : t1 : A tensor t2 : A tensor that can be multiplied by t1. epsilon : A lower bound value for the distance . The square root is used as the normalizer . name :...
with tf . name_scope ( name , 'cos_distance' , [ t1 , t2 ] ) as scope : t1 = tf . convert_to_tensor ( t1 , name = 't1' ) t2 = tf . convert_to_tensor ( t2 , name = 't2' ) x_inv_norm = tf . rsqrt ( tf . maximum ( length_squared ( t1 ) * length_squared ( t2 ) , epsilon ) ) return tf . subtract ( 1.0 , dot_...
def createRole ( self , name , description = "" , privileges = None ) : """Creates a new role . Args : name ( str ) : The name of the new role . description ( str ) : The description of the new role . Defaults to ` ` " " ` ` . privileges ( str ) : A comma delimited list of privileges to apply to the new rol...
admin = None portal = None setPrivResults = None roleID = None createResults = None try : admin = arcrest . manageorg . Administration ( securityHandler = self . _securityHandler ) portal = admin . portals . portalSelf try : roleID = portal . roles . findRoleID ( name ) if roleID is None : ...
def map ( self , timeout = None , max_concurrency = 64 , auto_batch = None ) : """Returns a context manager for a map operation . This runs multiple queries in parallel and then joins in the end to collect all results . In the context manager the client available is a : class : ` MappingClient ` . Example u...
return MapManager ( self . get_mapping_client ( max_concurrency , auto_batch ) , timeout = timeout )
def _sign_data ( secret , data ) : """Sign data . : param data : the string to sign : return : string base64 encoding of the HMAC - SHA1 hash of the data parameter using { @ code secretKey } as cipher key ."""
sha1_hash = hmac . new ( secret . encode ( ) , data . encode ( ) , sha1 ) return binascii . b2a_base64 ( sha1_hash . digest ( ) ) [ : - 1 ] . decode ( 'utf8' )
def phase2t ( self , psi ) : """Given phase - pi < psi < = pi , returns the t value such that exp ( 1j * psi ) = self . u1transform ( self . point ( t ) ) ."""
def _deg ( rads , domain_lower_limit ) : # Convert rads to degrees in [ 0 , 360 ) domain degs = degrees ( rads % ( 2 * pi ) ) # Convert to [ domain _ lower _ limit , domain _ lower _ limit + 360 ) domain k = domain_lower_limit // 360 degs += k * 360 if degs < domain_lower_limit : degs += 360...
def pprint_arg ( vnames , value ) : """pretty print argument : param vnames : : param value : : return :"""
ret = '' for name , v in zip ( vnames , value ) : ret += '%s=%s;' % ( name , str ( v ) ) return ret ;
def of ( cls , key : SearchKey , params : SearchParams ) -> 'SearchCriteria' : """Factory method for producing a search criteria sub - class from a search key . Args : key : The search key defining the criteria . params : The parameters that may be used by some searches ."""
key_name = key . value if key_name in params . disabled : raise SearchNotAllowed ( key_name ) elif key . inverse : return InverseSearchCriteria ( key . not_inverse , params ) elif key_name == b'SEQSET' : return SequenceSetSearchCriteria ( key . filter_sequence_set , params ) elif key_name == b'KEYSET' : ...
def custom_modify_user_view ( request , targetUsername ) : '''The page to modify a user .'''
if targetUsername == ANONYMOUS_USERNAME : messages . add_message ( request , messages . WARNING , MESSAGES [ 'ANONYMOUS_EDIT' ] ) page_name = "Admin - Modify User" targetUser = get_object_or_404 ( User , username = targetUsername ) targetProfile = get_object_or_404 ( UserProfile , user = targetUser ) update_user_fo...
def pid_from_context ( _ , context ) : """Get PID from marshmallow context ."""
pid = ( context or { } ) . get ( 'pid' ) return pid . pid_value if pid else missing
def latex ( source : str ) : """Add a mathematical equation in latex math - mode syntax to the display . Instead of the traditional backslash escape character , the @ character is used instead to prevent backslash conflicts with Python strings . For example , \\ delta would be @ delta . : param source : T...
r = _get_report ( ) if 'katex' not in r . library_includes : r . library_includes . append ( 'katex' ) r . append_body ( render_texts . latex ( source . replace ( '@' , '\\' ) ) ) r . stdout_interceptor . write_source ( '[ADDED] Latex equation\n' )
def execute ( self , input_data ) : '''Execute the VTQuery worker'''
md5 = input_data [ 'meta' ] [ 'md5' ] response = requests . get ( 'http://www.virustotal.com/vtapi/v2/file/report' , params = { 'apikey' : self . apikey , 'resource' : md5 , 'allinfo' : 1 } ) # Make sure we got a json blob back try : vt_output = response . json ( ) except ValueError : return { 'vt_error' : 'Vir...
def close ( self ) : """Closes the hid device"""
if self . _is_open : self . _is_open = False hidapi . hid_close ( self . _device )
def map_property_instances ( original_part , new_part ) : """Map the id of the original part with the ` Part ` object of the newly created one . Updated the singleton ` mapping dictionary ` with the new mapping table values . : param original _ part : ` Part ` object to be copied / moved : type original _ par...
# Map the original part with the new one get_mapping_dictionary ( ) [ original_part . id ] = new_part # Do the same for each Property of original part instance , using the ' model ' id and the get _ mapping _ dictionary for prop_original in original_part . properties : get_mapping_dictionary ( ) [ prop_original . i...
def run ( self , ** kwargs ) : """Runs this command . : param kwargs : Any extra keyword arguments to pass along to ` subprocess . Popen ` . : returns : A handle to the running command . : rtype : : class : ` subprocess . Popen `"""
env , kwargs = self . _prepare_env ( kwargs ) logger . debug ( 'Running command {}' . format ( self . cmd ) ) return subprocess . Popen ( self . cmd , env = env , ** kwargs )
def factors ( n ) : """Computes all the integer factors of the number ` n ` Example : > > > # ENABLE _ DOCTEST > > > from utool . util _ alg import * # NOQA > > > import utool as ut > > > result = sorted ( ut . factors ( 10 ) ) > > > print ( result ) [1 , 2 , 5 , 10] References : http : / / stacko...
return set ( reduce ( list . __add__ , ( [ i , n // i ] for i in range ( 1 , int ( n ** 0.5 ) + 1 ) if n % i == 0 ) ) )
def screen ( self ) : """PIL Image of current window screen . ( the window must be on the top ) reference : https : / / msdn . microsoft . com / en - us / library / dd183402 ( v = vs . 85 ) . aspx"""
# opengl windows cannot get from it ' s hwnd , so we use the screen hwnd = win32gui . GetDesktopWindow ( ) # get window size and offset left , top , right , bottom = self . rect width , height = right - left , bottom - top # the device context of the window hdcwin = win32gui . GetWindowDC ( hwnd ) # make a temporary dc...
def find_elements ( self , by = By . ID , value = None ) : """Find elements given a By strategy and locator . Prefer the find _ elements _ by _ * methods when possible . : Usage : elements = driver . find _ elements ( By . CLASS _ NAME , ' foo ' ) : rtype : list of WebElement"""
if self . w3c : if by == By . ID : by = By . CSS_SELECTOR value = '[id="%s"]' % value elif by == By . TAG_NAME : by = By . CSS_SELECTOR elif by == By . CLASS_NAME : by = By . CSS_SELECTOR value = ".%s" % value elif by == By . NAME : by = By . CSS_SELECTOR ...
def hicup_alignment_chart ( self ) : """Generate the HiCUP Aligned reads plot"""
# Specify the order of the different possible categories keys = OrderedDict ( ) keys [ 'Unique_Alignments_Read' ] = { 'color' : '#2f7ed8' , 'name' : 'Unique Alignments' } keys [ 'Multiple_Alignments_Read' ] = { 'color' : '#492970' , 'name' : 'Multiple Alignments' } keys [ 'Failed_To_Align_Read' ] = { 'color' : '#0d233a...
def fallbackPackage ( package_name , fallback_package_name ) : '''if an import cannot be resolved import from fallback package example : from [ package _ name ] . doesnt _ exist import Foo results in from [ fallback _ package _ name ] . doesnt _ exist import Foo'''
importer = Finder ( package_name , fallback_package_name ) sys . meta_path . append ( importer )
def particles ( self , include_ports = False ) : """Return all Particles of the Compound . Parameters include _ ports : bool , optional , default = False Include port particles Yields mb . Compound The next Particle in the Compound"""
if not self . children : yield self else : for particle in self . _particles ( include_ports ) : yield particle
def get_consistent_resource ( self ) : """: return a payment that you can trust . : rtype Payment"""
http_client = HttpClient ( ) response , _ = http_client . get ( routes . url ( routes . PAYMENT_RESOURCE , resource_id = self . id ) ) return Payment ( ** response )
def dump ( obj , fp ) : """Write a GSFont object to a . glyphs file . ' fp ' should be a ( writable ) file object ."""
writer = Writer ( fp ) logger . info ( "Writing .glyphs file" ) writer . write ( obj )
def subset_sum ( x , R ) : """Subsetsum : param x : table of non negative values : param R : target value : returns bool : True if a subset of x sums to R : complexity : O ( n * R )"""
b = [ False ] * ( R + 1 ) b [ 0 ] = True for xi in x : for s in range ( R , xi - 1 , - 1 ) : b [ s ] |= b [ s - xi ] return b [ R ]
def ensure_ceph_keyring ( service , user = None , group = None , relation = 'ceph' , key = None ) : """Ensures a ceph keyring is created for a named service and optionally ensures user and group ownership . @ returns boolean : Flag to indicate whether a key was successfully written to disk based on either rel...
if not key : for rid in relation_ids ( relation ) : for unit in related_units ( rid ) : key = relation_get ( 'key' , rid = rid , unit = unit ) if key : break if not key : return False add_key ( service = service , key = key ) keyring = _keyring_path ( service ) if...
def _iscomment ( line ) : """Determine if a line is a comment line . A valid line contains at least three words , with the first two being integers . Note that Python 2 and 3 deal with strings differently ."""
if line . isspace ( ) : return True elif len ( line . split ( ) ) >= 3 : try : # python 3 str if line . split ( ) [ 0 ] . isdecimal ( ) and line . split ( ) [ 1 ] . isdecimal ( ) : return False except : # python 2 str if ( line . decode ( ) . split ( ) [ 0 ] . isdecimal ( ) and l...
def parse_band_request_termination ( self , message ) : """Service declares it should be terminated ."""
self . log . debug ( "Service requests termination" ) self . _terminate_service ( ) if not self . restart_service : self . shutdown = True
def main ( model = None , output_dir = None , n_iter = 100 ) : """Load the model , set up the pipeline and train the entity recognizer ."""
if model is not None : nlp = spacy . load ( model ) # load existing spaCy model print ( "Loaded model '%s'" % model ) else : nlp = spacy . blank ( "en" ) # create blank Language class print ( "Created blank 'en' model" ) # create the built - in pipeline components and add them to the pipeline # ...
def job_list ( ) : '''List all jobs . : param _ limit : maximum number of jobs to show ( default 100) : type _ limit : int : param _ offset : how many jobs to skip before showin the first one ( default 0) : type _ offset : int : param _ status : filter jobs by status ( complete , error ) : type _ status...
args = dict ( ( key , value ) for key , value in flask . request . args . items ( ) ) limit = args . pop ( '_limit' , 100 ) offset = args . pop ( '_offset' , 0 ) select = sql . select ( [ db . JOBS_TABLE . c . job_id ] , from_obj = [ db . JOBS_TABLE . outerjoin ( db . METADATA_TABLE , db . JOBS_TABLE . c . job_id == db...
def md5 ( self ) : """Return a md5 key string based on position , ref and alt"""
return hashlib . md5 ( '_' . join ( [ self . CHROM , str ( self . POS ) , self . REF , self . ALT ] ) ) . hexdigest ( )
def getBaseSpec ( cls ) : """Return the base Spec for TemporalPoolerRegion . Doesn ' t include the pooler parameters"""
spec = dict ( description = TemporalPoolerRegion . __doc__ , singleNodeOnly = True , inputs = dict ( activeCells = dict ( description = "Active cells" , dataType = "Real32" , count = 0 , required = True , regionLevel = False , isDefaultInput = True , requireSplitterMap = False ) , predictedActiveCells = dict ( descript...
def write ( self , s : str ) -> None : """Add str to internal bytes buffer and if echo is True , echo contents to inner stream"""
if not isinstance ( s , str ) : raise TypeError ( 'write() argument must be str, not {}' . format ( type ( s ) ) ) if not self . pause_storage : self . buffer . byte_buf += s . encode ( encoding = self . encoding , errors = self . errors ) if self . echo : self . inner_stream . write ( s )
def delete_project ( self , project ) : """Deletes all versions of a project . First class , maps to Scrapyd ' s delete project endpoint ."""
url = self . _build_url ( constants . DELETE_PROJECT_ENDPOINT ) data = { 'project' : project , } self . client . post ( url , data = data , timeout = self . timeout ) return True
def _DateToEpoch ( date ) : """Converts python datetime to epoch microseconds ."""
tz_zero = datetime . datetime . utcfromtimestamp ( 0 ) diff_sec = int ( ( date - tz_zero ) . total_seconds ( ) ) return diff_sec * 1000000
def qteSplitApplet ( self , applet : ( QtmacsApplet , str ) = None , splitHoriz : bool = True , windowObj : QtmacsWindow = None ) : """Reveal ` ` applet ` ` by splitting the space occupied by the current applet . If ` ` applet ` ` is already visible then the method does nothing . Furthermore , this method doe...
# If ` ` newAppObj ` ` was specified by its ID ( ie . a string ) then # fetch the associated ` ` QtmacsApplet ` ` instance . If # ` ` newAppObj ` ` is already an instance of ` ` QtmacsApplet ` ` # then use it directly . if isinstance ( applet , str ) : newAppObj = self . qteGetAppletHandle ( applet ) else : new...
def set_sampled_topics ( self , sampled_topics ) : """Allocate sampled topics to the documents rather than estimate them . Automatically generate term - topic and document - topic matrices ."""
assert sampled_topics . dtype == np . int and len ( sampled_topics . shape ) <= 2 if len ( sampled_topics . shape ) == 1 : self . sampled_topics = sampled_topics . reshape ( 1 , sampled_topics . shape [ 0 ] ) else : self . sampled_topics = sampled_topics self . samples = self . sampled_topics . shape [ 0 ] self...