idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
33,900
def Print ( self , x , data , message , ** kwargs ) : del data , message , kwargs tf . logging . warning ( "Warning - mtf.Print not implemented for this mesh type" ) return x
Calls tf . Print .
33,901
def allsplit ( self , x , mesh_axis , split_axis , which = None ) : if which is None : which = self . laid_out_pcoord ( mesh_axis ) num_splits = self . shape [ mesh_axis ] . size def my_fn ( x , which ) : slice_begin = [ dimsize // num_splits * which if i == split_axis else 0 for i , dimsize in enumerate ( x . shape . ...
Inverse of allconcat - split each slice and keep only one piece of it .
33,902
def shift_by_n_processors ( self , x , mesh_axis , offset , wrap ) : n = self . shape [ mesh_axis ] . size source_pcoord = [ ] for i in xrange ( n ) : c = i - offset if c != c % n : if wrap : c = c % n else : c = None source_pcoord . append ( c ) return self . receive ( x , mesh_axis , source_pcoord )
Receive the slice from processor pcoord - offset .
33,903
def laid_out_pcoord ( self , mesh_axis ) : divisor = list_product ( self . shape . to_integer_list [ mesh_axis + 1 : ] ) modulus = self . shape [ mesh_axis ] . size def my_fn ( pnum ) : return ( pnum // divisor ) % modulus return self . slicewise ( my_fn , self . laid_out_pnum ( ) )
Returns a LaidOutTensor containing the processor coordinate .
33,904
def laid_out_slice_num ( self , tensor_shape ) : ret = self . slicewise ( lambda : tf . to_int32 ( 0 ) ) tensor_layout = self . tensor_layout ( tensor_shape ) for mesh_axis in tensor_layout . tensor_axis_to_mesh_axis : if mesh_axis is not None : def my_fn ( x , pcoord , mesh_dim_size ) : return x * mesh_dim_size + pcoo...
A LaidOutTensor with an int32 scalar identical for identical slices .
33,905
def broadcast_impl ( self , old_slices , old_shape , new_shape ) : new_slice_shape = self . slice_shape ( new_shape ) def tf_fn ( x ) : return ( tf . zeros ( new_slice_shape , dtype = x . dtype ) + _expand_dims ( x , old_shape , new_shape ) ) return self . slicewise ( tf_fn , old_slices )
Implementation of a broadcast operation .
33,906
def make_slices ( self , tf_tensor , tensor_shape ) : tensor_layout = self . tensor_layout ( tensor_shape ) slice_shape = self . slice_shape ( tensor_shape ) def my_fn ( pnum ) : if tensor_layout . is_fully_replicated : return tf_tensor else : slice_begin = self . slice_begin ( tensor_shape , pnum ) return tf . slice (...
Turns a single tf . Tensor into a list of slices one for each processor .
33,907
def combine_slices ( self , slices , tensor_shape , device = None ) : if tensor_shape . ndims == 0 : return slices [ 0 ] ret = slices [ : ] tensor_layout = self . tensor_layout ( tensor_shape ) for mesh_dim , tensor_axis in zip ( self . shape , tensor_layout . mesh_axis_to_tensor_axis ( self . ndims ) ) : slice_size = ...
Turns a set of slices into a single tensor .
33,908
def _initialize_splittable_and_unsplittable_dims ( self , default_splittability , exception_dims_iterable = None ) : default_dims = set ( ) exception_dims = set ( ) if exception_dims_iterable : exception_dims . update ( exception_dims_iterable ) for t in itertools . chain ( self . inputs , self . outputs ) : for dim_na...
Initializer for splittable_dims and unsplittable_dims .
33,909
def lower ( self , lowering ) : old_shape = self . inputs [ 0 ] . shape new_shape = self . outputs [ 0 ] . shape mesh_impl = lowering . mesh_impl ( self ) slices = lowering . tensors [ self . inputs [ 0 ] ] mesh_axis_to_cumprod_old = mesh_impl . mesh_axis_to_cumprod ( old_shape ) mesh_axis_to_cumprod_new = mesh_impl . ...
Lower the ReshapeOperation .
33,910
def get_variable_dtype ( master_dtype = tf . bfloat16 , slice_dtype = tf . float32 , activation_dtype = tf . float32 ) : return mtf . VariableDType ( master_dtype = tf . as_dtype ( master_dtype ) , slice_dtype = tf . as_dtype ( slice_dtype ) , activation_dtype = tf . as_dtype ( activation_dtype ) )
Datatypes to use for the run .
33,911
def build_model ( model_type = "bitransformer" , input_vocab_size = gin . REQUIRED , output_vocab_size = gin . REQUIRED , layout_rules = None , mesh_shape = None ) : if model_type == "bitransformer" : return transformer . make_bitransformer ( input_vocab_size = input_vocab_size , output_vocab_size = output_vocab_size ,...
Build a transformer model .
33,912
def decode_from_file ( estimator , vocabulary , model_type , batch_size , sequence_length , checkpoint_path = "" , input_filename = gin . REQUIRED , output_filename = gin . REQUIRED , eos_id = 1 ) : with tf . gfile . Open ( input_filename ) as f : text = f . read ( ) records = text . split ( "\n" ) inputs = [ record . ...
Decode from a text file .
33,913
def clean_decodes ( ids , vocab_size , eos_id = 1 ) : ret = [ ] for i in ids : if i == eos_id : break if i >= vocab_size : break ret . append ( int ( i ) ) return ret
Stop at EOS or padding or OOV .
33,914
def auto_batch_size ( sequence_length , mesh_shape , layout_rules , tokens_per_split = 2048 ) : num_splits = mtf . tensor_dim_to_mesh_dim_size ( layout_rules , mesh_shape , mtf . Dimension ( "batch" , 0 ) ) ret = max ( 1 , tokens_per_split // sequence_length ) * num_splits tf . logging . info ( "AUTO_BATCH_SIZE tokens_...
Automatically compute batch size .
33,915
def evaluate ( estimator , eval_args ) : values = { } checkpoint_path = estimator . latest_checkpoint ( ) if not checkpoint_path : return values tf . logging . info ( "Starting evaluation on checkpoint %s" , checkpoint_path ) for eval_name in eval_args : input_fn , eval_steps = eval_args [ eval_name ] metric_values = e...
Runs evaluation on the latest model checkpoint & logs to tensorboard .
33,916
def _ring_2d ( m , n ) : if m == 1 : return [ ( 0 , i ) for i in range ( n ) ] if n == 1 : return [ ( i , 0 ) for i in range ( m ) ] if m % 2 != 0 : tf . logging . warning ( "Odd dimension" ) return [ ( i % m , i // m ) for i in range ( n * m ) ] ret = [ ( 0 , 0 ) ] for i in range ( m // 2 ) : for j in range ( 1 , n ) ...
Ring - order of a mxn mesh .
33,917
def tile_2d ( physical_shape , tile_shape , outer_name = "outer" , inner_name = "inner" , cores_name = None ) : logical_to_physical = [ ] p0 , p1 , p2 = physical_shape t0 , t1 = tile_shape tile_ring = _ring_2d ( t0 , t1 ) tiles_ring = _ring_2d ( p0 // t0 , p1 // t1 ) for logical_pnum in range ( p0 * p1 * p2 ) : core_on...
2D tiling of a 3d physical mesh .
33,918
def slice ( self , tf_tensor , tensor_shape ) : tensor_layout = self . tensor_layout ( tensor_shape ) if tensor_layout . is_fully_replicated : return self . LaidOutTensor ( [ tf_tensor ] ) else : slice_shape = self . slice_shape ( tensor_shape ) slice_begins = [ self . slice_begin ( tensor_shape , pnum ) for pnum in xr...
Slice out the corresponding part of tensor given the pnum variable .
33,919
def read32 ( bytestream ) : dt = np . dtype ( np . uint32 ) . newbyteorder ( '>' ) return np . frombuffer ( bytestream . read ( 4 ) , dtype = dt ) [ 0 ]
Read 4 bytes from bytestream as an unsigned 32 - bit integer .
33,920
def check_image_file_header ( filename ) : with tf . gfile . Open ( filename , 'rb' ) as f : magic = read32 ( f ) read32 ( f ) rows = read32 ( f ) cols = read32 ( f ) if magic != 2051 : raise ValueError ( 'Invalid magic number %d in MNIST file %s' % ( magic , f . name ) ) if rows != 28 or cols != 28 : raise ValueError ...
Validate that filename corresponds to images for the MNIST dataset .
33,921
def check_labels_file_header ( filename ) : with tf . gfile . Open ( filename , 'rb' ) as f : magic = read32 ( f ) read32 ( f ) if magic != 2049 : raise ValueError ( 'Invalid magic number %d in MNIST file %s' % ( magic , f . name ) )
Validate that filename corresponds to labels for the MNIST dataset .
33,922
def dataset ( directory , images_file , labels_file ) : images_file = download ( directory , images_file ) labels_file = download ( directory , labels_file ) check_image_file_header ( images_file ) check_labels_file_header ( labels_file ) def decode_image ( image ) : image = tf . decode_raw ( image , tf . uint8 ) image...
Download and parse MNIST dataset .
33,923
def sample_discrete ( distn , size = [ ] , dtype = np . int32 ) : 'samples from a one-dimensional finite pmf' distn = np . atleast_1d ( distn ) assert ( distn >= 0 ) . all ( ) and distn . ndim == 1 if ( 0 == distn ) . all ( ) : return np . random . randint ( distn . shape [ 0 ] , size = size ) cumvals = np . cumsum ( d...
samples from a one - dimensional finite pmf
33,924
def used_states ( self ) : 'a list of the used states in the order they appear' c = itertools . count ( ) canonical_ids = collections . defaultdict ( lambda : next ( c ) ) for s in self . states_list : for state in s . stateseq : canonical_ids [ state ] return list ( map ( operator . itemgetter ( 0 ) , sorted ( canonic...
a list of the used states in the order they appear
33,925
def plot_gaussian_2D ( mu , lmbda , color = 'b' , centermarker = True , label = '' , alpha = 1. , ax = None , artists = None ) : assert len ( mu ) == 2 ax = ax if ax else plt . gca ( ) t = np . hstack ( [ np . arange ( 0 , 2 * np . pi , 0.01 ) , 0 ] ) circle = np . vstack ( [ np . sin ( t ) , np . cos ( t ) ] ) ellipse...
Plots mean and cov ellipsoid into current axes . Must be 2D . lmbda is a covariance matrix .
33,926
def resample_with_censoring ( self , data = [ ] , censored_data = [ ] ) : filled_in = self . _uncensor_data ( censored_data ) return self . resample ( data = combinedata ( ( data , filled_in ) ) )
censored_data is full of observations that were censored meaning a value of x really could have been anything > = x so this method samples them out to be at least that large
33,927
def scoreatpercentile ( data , per , axis = 0 ) : 'like the function in scipy.stats but with an axis argument and works on arrays' a = np . sort ( data , axis = axis ) idx = per / 100. * ( data . shape [ axis ] - 1 ) if ( idx % 1 == 0 ) : return a [ [ slice ( None ) if ii != axis else idx for ii in range ( a . ndim ) ]...
like the function in scipy . stats but with an axis argument and works on arrays
33,928
def content_type ( self , mime_type : Optional [ MimeType ] = None ) -> str : fmt = self . __file . mime_type ( type_ = mime_type ) return 'Content-Type: {}' . format ( fmt )
Get a random HTTP content type .
33,929
def ip_v4 ( self , with_port : bool = False ) -> str : ip = '.' . join ( str ( self . random . randint ( 0 , 255 ) ) for _ in range ( 4 ) ) if with_port : ip += ':{}' . format ( self . port ( ) ) return ip
Generate a random IPv4 address .
33,930
def ip_v6 ( self ) -> str : ipv6 = IPv6Address ( self . random . randint ( 0 , 2 ** 128 - 1 , ) , ) return str ( ipv6 )
Generate a random IPv6 address .
33,931
def mac_address ( self ) -> str : mac_hex = [ 0x00 , 0x16 , 0x3e , self . random . randint ( 0x00 , 0x7f ) , self . random . randint ( 0x00 , 0xff ) , self . random . randint ( 0x00 , 0xff ) , ] mac = map ( lambda x : '%02x' % x , mac_hex ) return ':' . join ( mac )
Generate a random MAC address .
33,932
def image_placeholder ( width : Union [ int , str ] = 1920 , height : Union [ int , str ] = 1080 ) -> str : url = 'http://placehold.it/{width}x{height}' return url . format ( width = width , height = height )
Generate a link to the image placeholder .
33,933
def hashtags ( self , quantity : int = 4 ) -> Union [ str , list ] : tags = [ '#' + self . random . choice ( HASHTAGS ) for _ in range ( quantity ) ] if int ( quantity ) == 1 : return tags [ 0 ] return tags
Generate a list of hashtags .
33,934
def home_page ( self , tld_type : Optional [ TLDType ] = None ) -> str : resource = self . random . choice ( USERNAMES ) domain = self . top_level_domain ( tld_type = tld_type , ) return 'http://www.{}{}' . format ( resource , domain )
Generate a random home page .
33,935
def top_level_domain ( self , tld_type : Optional [ TLDType ] = None ) -> str : key = self . _validate_enum ( item = tld_type , enum = TLDType ) return self . random . choice ( TLD [ key ] )
Return random top level domain .
33,936
def network_protocol ( self , layer : Optional [ Layer ] = None ) -> str : key = self . _validate_enum ( item = layer , enum = Layer ) protocols = NETWORK_PROTOCOLS [ key ] return self . random . choice ( protocols )
Get a random network protocol form OSI model .
33,937
def port ( self , port_range : PortRange = PortRange . ALL ) -> int : if port_range and port_range in PortRange : return self . random . randint ( * port_range . value ) else : raise NonEnumerableError ( PortRange )
Generate random port .
33,938
def truck ( self , model_mask : str = '#### @@' ) -> str : return '{}-{}' . format ( self . random . choice ( TRUCKS ) , self . random . custom_code ( model_mask ) , )
Generate a truck model .
33,939
def airplane ( self , model_mask : str = '###' ) -> str : model = self . random . custom_code ( mask = model_mask ) plane = self . random . choice ( AIRPLANES ) return '{} {}' . format ( plane , model )
Generate a dummy airplane model .
33,940
def vehicle_registration_code ( self , locale : Optional [ str ] = None ) -> str : if locale : return VRC_BY_LOCALES [ locale ] return self . random . choice ( VR_CODES )
Get vehicle registration code of country .
33,941
def bulk_create_datetimes ( date_start : DateTime , date_end : DateTime , ** kwargs ) -> List [ DateTime ] : dt_objects = [ ] if not date_start and not date_end : raise ValueError ( 'You must pass date_start and date_end' ) if date_end < date_start : raise ValueError ( 'date_start can not be larger than date_end' ) whi...
Bulk create datetime objects .
33,942
def week_date ( self , start : int = 2017 , end : int = 2018 ) -> str : year = self . year ( start , end ) week = self . random . randint ( 1 , 52 ) return '{year}-W{week}' . format ( year = year , week = week , )
Get week number with year .
33,943
def day_of_week ( self , abbr : bool = False ) -> str : key = 'abbr' if abbr else 'name' days = self . _data [ 'day' ] . get ( key ) return self . random . choice ( days )
Get a random day of week .
33,944
def month ( self , abbr : bool = False ) -> str : key = 'abbr' if abbr else 'name' months = self . _data [ 'month' ] . get ( key ) return self . random . choice ( months )
Get a random month .
33,945
def year ( self , minimum : int = 1990 , maximum : int = 2050 ) -> int : return self . random . randint ( minimum , maximum )
Generate a random year .
33,946
def periodicity ( self ) -> str : periodicity = self . _data [ 'periodicity' ] return self . random . choice ( periodicity )
Get a random periodicity string .
33,947
def date ( self , start : int = 2000 , end : int = 2019 ) -> Date : year = self . random . randint ( start , end ) month = self . random . randint ( 1 , 12 ) day = self . random . randint ( 1 , monthrange ( year , month ) [ 1 ] ) date_object = date ( year , month , day ) return date_object
Generate random date object .
33,948
def formatted_date ( self , fmt : str = '' , ** kwargs ) -> str : date_obj = self . date ( ** kwargs ) if not fmt : fmt = self . _data [ 'formats' ] . get ( 'date' ) return date_obj . strftime ( fmt )
Generate random date as string .
33,949
def time ( self ) -> Time : random_time = time ( self . random . randint ( 0 , 23 ) , self . random . randint ( 0 , 59 ) , self . random . randint ( 0 , 59 ) , self . random . randint ( 0 , 999999 ) , ) return random_time
Generate a random time object .
33,950
def formatted_time ( self , fmt : str = '' ) -> str : time_obj = self . time ( ) if not fmt : fmt = self . _data [ 'formats' ] . get ( 'time' ) return time_obj . strftime ( fmt )
Generate string formatted time .
33,951
def datetime ( self , start : int = 2000 , end : int = 2035 , timezone : Optional [ str ] = None ) -> DateTime : datetime_obj = datetime . combine ( date = self . date ( start , end ) , time = self . time ( ) , ) if timezone : if not pytz : raise ImportError ( 'Timezones are supported only with pytz' ) tz = pytz . time...
Generate random datetime .
33,952
def formatted_datetime ( self , fmt : str = '' , ** kwargs ) -> str : dt_obj = self . datetime ( ** kwargs ) if not fmt : date_fmt = self . _data [ 'formats' ] . get ( 'date' ) time_fmt = self . _data [ 'formats' ] . get ( 'time' ) fmt = '{} {}' . format ( date_fmt , time_fmt ) return dt_obj . strftime ( fmt )
Generate datetime string in human readable format .
33,953
def timestamp ( self , posix : bool = True , ** kwargs ) -> Union [ str , int ] : stamp = self . datetime ( ** kwargs ) if posix : return timegm ( stamp . utctimetuple ( ) ) return stamp . strftime ( '%Y-%m-%dT%H:%M:%SZ' )
Generate random timestamp .
33,954
def uuid ( self , version : int = None ) -> str : bits = self . random . getrandbits ( 128 ) return str ( uuid . UUID ( int = bits , version = version ) )
Generate random UUID .
33,955
def hash ( self , algorithm : Algorithm = None ) -> str : key = self . _validate_enum ( algorithm , Algorithm ) if hasattr ( hashlib , key ) : fn = getattr ( hashlib , key ) return fn ( self . uuid ( ) . encode ( ) ) . hexdigest ( )
Generate random hash .
33,956
def mnemonic_phrase ( self , length : int = 12 ) -> str : words = self . __words [ 'normal' ] return ' ' . join ( self . random . choice ( words ) for _ in range ( length ) )
Generate pseudo mnemonic phrase .
33,957
def initialize_options ( self ) : self . paths = [ ] self . separators = ( ',' , ':' ) self . data_dir = join ( here , 'mimesis' , 'data' ) self . before_total = 0 self . after_total = 0 for root , _ , files in os . walk ( self . data_dir ) : for file in sorted ( files ) : if splitext ( file ) [ 1 ] == '.json' : self ....
Find all files of all locales .
33,958
def run ( self ) : for rel_path in sorted ( self . paths ) : file_path = join ( self . data_dir , rel_path ) self . minify ( file_path ) after = self . size_of ( self . after_total ) before = self . size_of ( self . before_total ) saved = self . size_of ( self . before_total - self . after_total ) template = '\nTotal: ...
Start json minimizer and exit when all json files were minimized .
33,959
def css ( self ) -> str : selector = self . random . choice ( CSS_SELECTORS ) css_sel = '{}{}' . format ( selector , self . __text . word ( ) ) cont_tag = self . random . choice ( list ( HTML_CONTAINER_TAGS . keys ( ) ) ) mrk_tag = self . random . choice ( HTML_MARKUP_TAGS ) base = '{}' . format ( self . random . choic...
Generate a random snippet of CSS .
33,960
def css_property ( self ) -> str : prop = self . random . choice ( list ( CSS_PROPERTIES . keys ( ) ) ) val = CSS_PROPERTIES [ prop ] if isinstance ( val , list ) : val = self . random . choice ( val ) elif val == 'color' : val = self . __text . hex_color ( ) elif val == 'size' : val = '{}{}' . format ( self . random ....
Generate a random snippet of CSS that assigns value to a property .
33,961
def html ( self ) -> str : tag_name = self . random . choice ( list ( HTML_CONTAINER_TAGS ) ) tag_attributes = list ( HTML_CONTAINER_TAGS [ tag_name ] ) k = self . random . randint ( 1 , len ( tag_attributes ) ) selected_attrs = self . random . sample ( tag_attributes , k = k ) attrs = [ ] for attr in selected_attrs : ...
Generate a random HTML tag with text inside and some attrs set .
33,962
def html_attribute_value ( self , tag : str = None , attribute : str = None ) -> str : if not tag : tag = self . random . choice ( list ( HTML_CONTAINER_TAGS . keys ( ) ) , ) if not attribute : attribute = self . random . choice ( list ( HTML_CONTAINER_TAGS [ tag ] ) , ) try : value = HTML_CONTAINER_TAGS [ tag ] [ attr...
Generate random value for specified HTML tag attribute .
33,963
def version ( self , calver : bool = False , pre_release : bool = False ) -> str : version = '{}.{}.{}' major , minor , patch = self . random . randints ( 3 , 0 , 10 ) if calver : if minor == 0 : minor += 1 if patch == 0 : patch += 1 major = self . random . randint ( 2016 , 2018 ) return version . format ( major , mino...
Generate version number .
33,964
def chemical_element ( self , name_only : bool = True ) -> Union [ dict , str ] : elements = self . _data [ 'chemical_element' ] nm , sm , an = self . random . choice ( elements ) . split ( '|' ) if not name_only : return { 'name' : nm . strip ( ) , 'symbol' : sm . strip ( ) , 'atomic_number' : an . strip ( ) , } retur...
Generate a random chemical element .
33,965
def cpf ( self , with_mask : bool = True ) -> str : def get_verifying_digit_cpf ( cpf , peso ) : soma = 0 for index , digit in enumerate ( cpf ) : soma += digit * ( peso - index ) resto = soma % 11 if resto == 0 or resto == 1 or resto >= 11 : return 0 return 11 - resto cpf_without_dv = [ self . random . randint ( 0 , 9...
Get a random CPF .
33,966
def cnpj ( self , with_mask : bool = True ) -> str : def get_verifying_digit_cnpj ( cnpj , peso ) : soma = 0 if peso == 5 : peso_list = [ 5 , 4 , 3 , 2 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 ] elif peso == 6 : peso_list = [ 6 , 5 , 4 , 3 , 2 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 ] for i , _ in enumerate ( cnpj ) : soma += peso_list...
Get a random CNPJ .
33,967
def romanized ( locale : str = '' ) -> Callable : def romanized_deco ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : try : alphabet = { s : s for s in letters + digits + punctuation } alphabet . update ( data . ROMANIZATION_DICT [ locale ] ) alphabet . update ( data . COMMON_LETTERS ) excep...
Romanize the Cyrillic text .
33,968
def _choice_from ( self , key : str ) -> str : data = self . _data [ key ] return self . random . choice ( data )
Choice random element .
33,969
def generate_sentence ( self ) -> str : sentences = self . _data [ 'sentence' ] sentence = [ self . random . choice ( sentences [ k ] ) for k in ( 'head' , 'p1' , 'p2' , 'tail' ) ] return '{0} {1} {2} {3}' . format ( * sentence )
Generate sentence from the parts .
33,970
def patronymic ( self , gender : Gender = None ) -> str : gender = self . _validate_enum ( gender , Gender ) patronymics = self . _data [ 'patronymic' ] [ gender ] return self . random . choice ( patronymics )
Generate random patronymic name .
33,971
def passport_series ( self , year : int = None ) -> str : if not year : year = self . random . randint ( 10 , 18 ) region = self . random . randint ( 1 , 99 ) return '{:02d} {}' . format ( region , year )
Generate random series of passport .
33,972
def snils ( self ) -> str : numbers = [ ] control_codes = [ ] for i in range ( 0 , 9 ) : numbers . append ( self . random . randint ( 0 , 9 ) ) for i in range ( 9 , 0 , - 1 ) : control_codes . append ( numbers [ 9 - i ] * i ) control_code = sum ( control_codes ) code = '' . join ( str ( number ) for number in numbers )...
Generate snils with special algorithm .
33,973
def inn ( self ) -> str : def control_sum ( nums : list , t : str ) -> int : digits = { 'n2' : [ 7 , 2 , 4 , 10 , 3 , 5 , 9 , 4 , 6 , 8 ] , 'n1' : [ 3 , 7 , 2 , 4 , 10 , 3 , 5 , 9 , 4 , 6 , 8 ] , } number = 0 length = digits [ t ] for i in range ( 0 , len ( length ) ) : number += nums [ i ] * length [ i ] return number...
Generate random but valid INN .
33,974
def ogrn ( self ) -> str : numbers = [ ] for _ in range ( 0 , 12 ) : numbers . append ( self . random . randint ( 1 if _ == 0 else 0 , 9 ) ) ogrn = '' . join ( [ str ( x ) for x in numbers ] ) check_sum = str ( int ( ogrn ) % 11 % 10 ) return '{}{}' . format ( ogrn , check_sum )
Generate random valid OGRN .
33,975
def kpp ( self ) -> str : tax_codes = [ '7700' , '7800' , '5000' , '0100' , '0200' , '0300' , '0500' , '0600' , '0700' , '0800' , '0900' , '1000' , '1100' , '1200' , '1300' , '1400' , '1500' , '1600' , '1700' , '1800' , '1900' , '2000' , '2100' , '2200' , '2300' , '2400' , '2500' , '2600' , '2700' , '2800' , '2900' , '...
Generate random KPP .
33,976
def cpu_frequency ( self ) -> str : return '{}GHz' . format ( self . random . uniform ( a = 1.5 , b = 4.3 , precision = 1 , ) , )
Get a random frequency of CPU .
33,977
def floats ( self , n : int = 2 ) -> List [ float ] : nums = [ self . random . random ( ) for _ in range ( 10 ** int ( n ) ) ] return nums
Generate a list of random float numbers .
33,978
def integers ( self , start : int = 0 , end : int = 10 , length : int = 10 ) -> List [ int ] : return self . random . randints ( length , start , end )
Generate a list of random integers .
33,979
def primes ( start : int = 1 , end : int = 999 ) -> List [ int ] : sieve_size = ( end // 2 - 1 ) if end % 2 == 0 else ( end // 2 ) sieve = [ True ] * sieve_size primes = [ ] if end >= 2 : primes . append ( 2 ) for i in range ( sieve_size ) : if sieve [ i ] : value_at_i = i * 2 + 3 primes . append ( value_at_i ) for j i...
Generate a list of prime numbers .
33,980
def digit ( self , to_bin : bool = False ) -> Union [ str , int ] : digit = self . random . randint ( 0 , 9 ) if to_bin : return bin ( digit ) return digit
Get a random digit .
33,981
def between ( self , minimum : int = 1 , maximum : int = 1000 ) -> int : return self . random . randint ( minimum , maximum )
Generate a random number between minimum and maximum .
33,982
def age ( self , minimum : int = 16 , maximum : int = 66 ) -> int : age = self . random . randint ( minimum , maximum ) self . _store [ 'age' ] = age return age
Get a random integer value .
33,983
def work_experience ( self , working_start_age : int = 22 ) -> int : age = self . _store [ 'age' ] if age == 0 : age = self . age ( ) return max ( age - working_start_age , 0 )
Get a work experience .
33,984
def name ( self , gender : Optional [ Gender ] = None ) -> str : key = self . _validate_enum ( gender , Gender ) names = self . _data [ 'names' ] . get ( key ) return self . random . choice ( names )
Generate a random name .
33,985
def surname ( self , gender : Optional [ Gender ] = None ) -> str : surnames = self . _data [ 'surnames' ] if isinstance ( surnames , dict ) : key = self . _validate_enum ( gender , Gender ) surnames = surnames [ key ] return self . random . choice ( surnames )
Generate a random surname .
33,986
def title ( self , gender : Optional [ Gender ] = None , title_type : Optional [ TitleType ] = None ) -> str : gender_key = self . _validate_enum ( gender , Gender ) title_key = self . _validate_enum ( title_type , TitleType ) titles = self . _data [ 'title' ] [ gender_key ] [ title_key ] return self . random . choice ...
Generate a random title for name .
33,987
def full_name ( self , gender : Optional [ Gender ] = None , reverse : bool = False ) -> str : if gender is None : gender = get_random_item ( Gender , rnd = self . random ) if gender and isinstance ( gender , Gender ) : gender = gender else : raise NonEnumerableError ( Gender ) fmt = '{1} {0}' if reverse else '{0} {1}'...
Generate a random full name .
33,988
def username ( self , template : Optional [ str ] = None ) -> str : MIN_DATE = 1800 MAX_DATE = 2070 DEFAULT_TEMPLATE = 'l.d' templates = ( 'U_d' , 'U.d' , 'U-d' , 'UU-d' , 'UU.d' , 'UU_d' , 'ld' , 'l-d' , 'Ud' , 'l.d' , 'l_d' , 'default' ) if template is None : template = self . random . choice ( templates ) if templat...
Generate username by template .
33,989
def password ( self , length : int = 8 , hashed : bool = False ) -> str : text = ascii_letters + digits + punctuation password = '' . join ( [ self . random . choice ( text ) for _ in range ( length ) ] ) if hashed : md5 = hashlib . md5 ( ) md5 . update ( password . encode ( ) ) return md5 . hexdigest ( ) else : return...
Generate a password or hash of password .
33,990
def email ( self , domains : Union [ tuple , list ] = None ) -> str : if not domains : domains = EMAIL_DOMAINS domain = self . random . choice ( domains ) name = self . username ( template = 'ld' ) return '{name}{domain}' . format ( name = name , domain = domain , )
Generate a random email .
33,991
def social_media_profile ( self , site : Optional [ SocialNetwork ] = None ) -> str : key = self . _validate_enum ( site , SocialNetwork ) website = SOCIAL_NETWORKS [ key ] url = 'https://www.' + website return url . format ( self . username ( ) )
Generate profile for random social network .
33,992
def gender ( self , iso5218 : bool = False , symbol : bool = False ) -> Union [ str , int ] : if iso5218 : return self . random . choice ( [ 0 , 1 , 2 , 9 ] ) if symbol : return self . random . choice ( GENDER_SYMBOLS ) return self . random . choice ( self . _data [ 'gender' ] )
Get a random gender .
33,993
def weight ( self , minimum : int = 38 , maximum : int = 90 ) -> int : weight = self . random . randint ( minimum , maximum ) return weight
Generate a random weight in Kg .
33,994
def occupation ( self ) -> str : jobs = self . _data [ 'occupation' ] return self . random . choice ( jobs )
Get a random job .
33,995
def political_views ( self ) -> str : views = self . _data [ 'political_views' ] return self . random . choice ( views )
Get a random political views .
33,996
def worldview ( self ) -> str : views = self . _data [ 'worldview' ] return self . random . choice ( views )
Get a random worldview .
33,997
def views_on ( self ) -> str : views = self . _data [ 'views_on' ] return self . random . choice ( views )
Get a random views on .
33,998
def nationality ( self , gender : Optional [ Gender ] = None ) -> str : nationalities = self . _data [ 'nationality' ] if isinstance ( nationalities , dict ) : key = self . _validate_enum ( gender , Gender ) nationalities = nationalities [ key ] return self . random . choice ( nationalities )
Get a random nationality .
33,999
def university ( self ) -> str : universities = self . _data [ 'university' ] return self . random . choice ( universities )
Get a random university .