idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
50,400 | def daily404summary ( date , return_format = None ) : uri = 'daily404summary' if date : try : uri = '/' . join ( [ uri , date . strftime ( "%Y-%m-%d" ) ] ) except AttributeError : uri = '/' . join ( [ uri , date ] ) return _get ( uri , return_format ) | Returns daily summary information of submitted 404 Error Page Information . |
50,401 | def daily404detail ( date , limit = None , return_format = None ) : uri = 'daily404detail' if date : try : uri = '/' . join ( [ uri , date . strftime ( "%Y-%m-%d" ) ] ) except AttributeError : uri = '/' . join ( [ uri , date ] ) if limit : uri = '/' . join ( [ uri , str ( limit ) ] ) return _get ( uri , return_format ) | Returns detail information of submitted 404 Error Page Information . |
50,402 | def glossary ( term = None , return_format = None ) : uri = 'glossary' if term : uri = '/' . join ( [ uri , term ] ) return _get ( uri , return_format ) | List of glossary terms and definitions . |
50,403 | def _append_path ( new_path ) : for path in sys . path : path = os . path . abspath ( path ) if new_path == path : return sys . path . append ( new_path ) | Given a path string append it to sys . path |
50,404 | def _caller_path ( index ) : module = None stack = inspect . stack ( ) while not module : if index >= len ( stack ) : raise RuntimeError ( "Cannot find import path" ) frame = stack [ index ] module = inspect . getmodule ( frame [ 0 ] ) index += 1 filename = module . __file__ path = os . path . dirname ( os . path . rea... | Get the caller s file path by the index of the stack does not work when the caller is stdin through a CLI python |
50,405 | def get_current_path ( index = 2 ) : try : path = _caller_path ( index ) except RuntimeError : path = os . getcwd ( ) return path | Get the caller s path to sys . path If the caller is a CLI through stdin the current working directory is used |
50,406 | def get_git_root ( index = 3 ) : path = get_current_path ( index = index ) while True : git_path = os . path . join ( path , '.git' ) if os . path . isdir ( git_path ) : return path if os . path . dirname ( path ) == path : raise RuntimeError ( "Cannot find git root" ) path = os . path . split ( path ) [ 0 ] | Get the path of the git root directory of the caller s file Raises a RuntimeError if a git repository cannot be found |
50,407 | def get_parent_path ( index = 2 ) : try : path = _caller_path ( index ) except RuntimeError : path = os . getcwd ( ) path = os . path . abspath ( os . path . join ( path , os . pardir ) ) return path | Get the caller s parent path to sys . path If the caller is a CLI through stdin the parent of the current working directory is used |
50,408 | def send_email ( self , send_to , attachment_paths = None , fail_silently = True , * args , ** kwargs ) : msg = self . get_message_object ( send_to , attachment_paths , * args , ** kwargs ) msg . content_subtype = self . content_subtype try : self . sent = msg . send ( ) except SMTPException , e : if not fail_silently ... | Sends email to recipient based on self object parameters . |
50,409 | def _tag ( element ) : tag = element . tag if tag [ 0 ] == "{" : uri , tag = tag [ 1 : ] . split ( "}" ) return tag | Return element . tag with xmlns stripped away . |
50,410 | def _uriPrefix ( element ) : i = element . tag . find ( '}' ) if i < 0 : return "" return element . tag [ : i + 1 ] | Return xmlns prefix of the given element . |
50,411 | def parseValue ( self , value ) : if self . isVector ( ) : return list ( map ( self . _pythonType , value . split ( ',' ) ) ) if self . typ == 'boolean' : return _parseBool ( value ) return self . _pythonType ( value ) | Parse the given value and return result . |
50,412 | def defaultExtension ( self ) : result = self . EXTERNAL_TYPES [ self . typ ] if not self . fileExtensions : return result if result in self . fileExtensions : return result return self . fileExtensions [ 0 ] | Return default extension for this parameter type checked against supported fileExtensions . If the default extension is not within fileExtensions return the first supported extension . |
50,413 | def define_symbol ( name , open_brace , comma , i , j , close_brace , variables , ** kwds ) : r if variables is None : return Symbol ( name + open_brace + str ( i + 1 ) + comma + str ( j + 1 ) + close_brace , ** kwds ) else : return Function ( name + open_brace + str ( i + 1 ) + comma + str ( j + 1 ) + close_brace , **... | r Define a nice symbol with matrix indices . |
50,414 | def cartesian_to_helicity ( vector , numeric = False ) : r if numeric : vector = list ( vector ) vector [ 0 ] = nparray ( vector [ 0 ] ) vector [ 1 ] = nparray ( vector [ 1 ] ) vector [ 2 ] = nparray ( vector [ 2 ] ) v = [ ( vector [ 0 ] - 1j * vector [ 1 ] ) / npsqrt ( 2 ) , vector [ 2 ] , - ( vector [ 0 ] + 1j * vect... | r This function takes vectors from the cartesian basis to the helicity basis . For instance we can check what are the vectors of the helicity basis . |
50,415 | def vector_element ( r , i , j ) : r return Matrix ( [ r [ p ] [ i , j ] for p in range ( 3 ) ] ) | r Extract an matrix element of a vector operator . |
50,416 | def define_frequencies ( Ne , explicitly_antisymmetric = False ) : u omega_level = [ Symbol ( 'omega_' + str ( i + 1 ) , real = True ) for i in range ( Ne ) ] if Ne > 9 : opening = "\\" comma = "," open_brace = "{" close_brace = "}" else : opening = r"" comma = "" open_brace = "" close_brace = "" omega = [ ] gamma = [ ... | u Define all frequencies omega_level omega gamma . |
50,417 | def lindblad_terms ( gamma , rho , Ne , verbose = 1 ) : u Nterms = 0 for i in range ( Ne ) : for j in range ( i ) : if gamma [ i , j ] != 0 : Nterms += 1 L = zeros ( Ne ) counter = 0 t0 = time ( ) for i in range ( Ne ) : for j in range ( i ) : if gamma [ i , j ] != 0 : counter += 1 sig = ket ( j + 1 , Ne ) * bra ( i + ... | u Return the Lindblad terms for decays gamma in matrix form . |
50,418 | def define_rho_vector ( rho , Ne ) : u rho_vect = [ ] for mu in range ( 1 , Ne ** 2 ) : i , j , s = IJ ( mu , Ne ) i = i - 1 j = j - 1 rho_vect += [ part_symbolic ( rho [ i , j ] , s ) ] return Matrix ( rho_vect ) | u Define the vectorized density matrix . |
50,419 | def calculate_A_b ( eqs , unfolding , verbose = 0 ) : u Ne = unfolding . Ne Nrho = unfolding . Nrho lower_triangular = unfolding . lower_triangular rho = define_density_matrix ( Ne , explicitly_hermitian = lower_triangular , normalized = unfolding . normalized ) rho_vect = unfolding ( rho ) if unfolding . real : ss_com... | u Calculate the equations in matrix form . |
50,420 | def phase_transformation ( Ne , Nl , r , Lij , omega_laser , phase ) : r ph = find_phase_transformation ( Ne , Nl , r , Lij ) return { phase [ i ] : sum ( [ ph [ i ] [ j ] * omega_laser [ j ] for j in range ( Nl ) ] ) for i in range ( Ne ) } | r Obtain a phase transformation to eliminate explicit time dependence . |
50,421 | def dot ( a , b ) : r if isinstance ( a , Mul ) : a = a . expand ( ) avect = 1 aivect = - 1 for ai , fact in enumerate ( a . args ) : if isinstance ( fact , Vector3D ) : avect = fact aivect = ai break acoef = a . args [ : aivect ] + a . args [ aivect + 1 : ] acoef = Mul ( * acoef ) return acoef * dot ( avect , b ) if i... | r Dot product of two 3d vectors . |
50,422 | def cross ( a , b ) : r if isinstance ( a , Mul ) : a = a . expand ( ) avect = 1 aivect = - 1 for ai , fact in enumerate ( a . args ) : if isinstance ( fact , Vector3D ) : avect = fact aivect = ai break acoef = a . args [ : aivect ] + a . args [ aivect + 1 : ] acoef = Mul ( * acoef ) return acoef * cross ( avect , b ) ... | r Cross product of two 3d vectors . |
50,423 | def write_settings ( settings ) : if not os . access ( DATA_DIR , os . W_OK ) : return False try : f = open ( DATA_DIR + os . sep + SETTINGS_FILE , 'w' ) f . writelines ( json . dumps ( settings , indent = 0 ) ) f . close ( ) os . chmod ( os . path . abspath ( DATA_DIR + os . sep + SETTINGS_FILE ) , 0o777 ) except IOEr... | Saves user s settings |
50,424 | def is_field_unique_by_group ( df , field_col , group_col ) : def num_unique ( x ) : return len ( pd . unique ( x ) ) num_distinct = df . groupby ( group_col ) [ field_col ] . agg ( num_unique ) return all ( num_distinct == 1 ) | Determine if field is constant by group in df |
50,425 | def _list_files_in_path ( path , pattern = "*.stan" ) : results = [ ] for dirname , subdirs , files in os . walk ( path ) : for name in files : if fnmatch ( name , pattern ) : results . append ( os . path . join ( dirname , name ) ) return ( results ) | indexes a directory of stan files returns as dictionary containing contents of files |
50,426 | def generate_random_perovskite ( lat = None ) : if not lat : lat = round ( random . uniform ( 3.5 , Perovskite_tilting . OCTAHEDRON_BOND_LENGTH_LIMIT * 2 ) , 3 ) A_site = random . choice ( Perovskite_Structure . A ) B_site = random . choice ( Perovskite_Structure . B ) Ci_site = random . choice ( Perovskite_Structure .... | This generates a random valid perovskite structure in ASE format . Useful for testing . Binary and organic perovskites are not considered . |
50,427 | def check_positive_integer ( name , value ) : try : value = int ( value ) is_positive = ( value > 0 ) except ValueError : raise ValueError ( '%s should be an integer; got %r' % ( name , value ) ) if is_positive : return value else : raise ValueError ( '%s should be positive; got %r' % ( name , value ) ) | Check a value is a positive integer . |
50,428 | def check_color_input ( value ) : value = value . lower ( ) if value . startswith ( '#' ) : value = value [ 1 : ] if len ( value ) != 6 : raise ValueError ( 'Color should be six hexadecimal digits, got %r (%s)' % ( value , len ( value ) ) ) if re . sub ( r'[a-f0-9]' , '' , value ) : raise ValueError ( 'Color should onl... | Check a value is a valid colour input . |
50,429 | def get_octahedra ( self , atoms , periodicity = 3 ) : octahedra = [ ] for n , i in enumerate ( atoms ) : found = [ ] if i . symbol in Perovskite_Structure . B : for m , j in enumerate ( self . virtual_atoms ) : if j . symbol in Perovskite_Structure . C and self . virtual_atoms . get_distance ( n , m ) <= self . OCTAHE... | Extract octahedra as lists of sequence numbers of corner atoms |
50,430 | def get_tiltplane ( self , sequence ) : sequence = sorted ( sequence , key = lambda x : self . virtual_atoms [ x ] . z ) in_plane = [ ] for i in range ( 0 , len ( sequence ) - 4 ) : if abs ( self . virtual_atoms [ sequence [ i ] ] . z - self . virtual_atoms [ sequence [ i + 1 ] ] . z ) < self . OCTAHEDRON_ATOMS_Z_DIFFE... | Extract the main tilting plane basing on Z coordinate |
50,431 | def register ( self , path , help_text = None , help_context = None ) : if path in self . _registry : raise AlreadyRegistered ( 'The template %s is already registered' % path ) self . _registry [ path ] = RegistrationItem ( path , help_text , help_context ) logger . debug ( "Registered email template %s" , path ) | Registers email template . |
50,432 | def get_registration ( self , path ) : if not self . is_registered ( path ) : raise NotRegistered ( "Email template not registered" ) return self . _registry [ path ] | Returns registration item for specified path . |
50,433 | def get_form_help_text ( self , path ) : try : form_help_text = self . get_registration ( path ) . as_form_help_text ( ) except NotRegistered : form_help_text = u"" return form_help_text | Returns text that can be used as form help text for creating email templates . |
50,434 | def report_build_messages ( self ) : if os . getenv ( 'TEAMCITY_VERSION' ) : tc_build_message_warning = "##teamcity[buildStatisticValue key='pepper8warnings' value='{}']\n" tc_build_message_error = "##teamcity[buildStatisticValue key='pepper8errors' value='{}']\n" stdout . write ( tc_build_message_warning . format ( se... | Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity and performs the adequate actions to report statistics . |
50,435 | def phase_transformation ( Ne , Nl , rm , xi , return_equations = False ) : E0 , omega_laser = define_laser_variables ( Nl ) theta = [ Symbol ( 'theta' + str ( i + 1 ) ) for i in range ( Ne ) ] if type ( xi ) == list : xi = np . array ( [ [ [ xi [ l ] [ i , j ] for j in range ( Ne ) ] for i in range ( Ne ) ] for l in r... | Returns a phase transformation theta_i . |
50,436 | def define_simplification ( omega_level , xi , Nl ) : try : Ne = len ( omega_level ) except : Ne = omega_level . shape [ 0 ] om = omega_level [ 0 ] iu = 0 Neu = 1 omega_levelu = [ om ] d = { } di = { 0 : 0 } for i in range ( Ne ) : if omega_level [ i ] != om : iu += 1 om = omega_level [ i ] Neu += 1 omega_levelu += [ o... | Return a simplifying function its inverse and simplified frequencies . |
50,437 | def find_omega_min ( omega_levelu , Neu , Nl , xiu ) : r omega_min = [ ] iu0 = [ ] ju0 = [ ] for l in range ( Nl ) : omegasl = [ ] for iu in range ( Neu ) : for ju in range ( iu ) : if xiu [ l , iu , ju ] == 1 : omegasl += [ ( omega_levelu [ iu ] - omega_levelu [ ju ] , iu , ju ) ] omegasl = list ( sorted ( omegasl ) )... | r Find the smallest transition frequency for each field . |
50,438 | def detunings_indices ( Neu , Nl , xiu ) : r pairs = [ ] for l in range ( Nl ) : ind = [ ] for iu in range ( Neu ) : for ju in range ( iu ) : if xiu [ l , iu , ju ] == 1 : ind += [ ( iu , ju ) ] pairs += [ ind ] return pairs | r Get the indices of the transitions of all fields . |
50,439 | def detunings_code ( Neu , Nl , pairs , omega_levelu , iu0 , ju0 ) : r code_det = "" for l in range ( Nl ) : for pair in pairs [ l ] : iu , ju = pair code_det += " delta" + str ( l + 1 ) code_det += "_" + str ( iu + 1 ) code_det += "_" + str ( ju + 1 ) code_det += " = detuning_knob[" + str ( l ) + "]" corr = - omega... | r Get the code to calculate the simplified detunings . |
50,440 | def detunings_combinations ( pairs ) : r def iter ( pairs , combs , l ) : combs_n = [ ] for i in range ( len ( combs ) ) : for j in range ( len ( pairs [ l ] ) ) : combs_n += [ combs [ i ] + [ pairs [ l ] [ j ] ] ] return combs_n Nl = len ( pairs ) combs = [ [ pairs [ 0 ] [ k ] ] for k in range ( len ( pairs [ 0 ] ) ) ... | r Return all combinations of detunings . |
50,441 | def detunings_rewrite ( expr , combs , omega_laser , symb_omega_levelu , omega_levelu , iu0 , ju0 ) : r Nl = len ( omega_laser ) Neu = len ( symb_omega_levelu ) a = [ diff ( expr , omega_laser [ l ] ) for l in range ( Nl ) ] success = False for comb in combs : expr_try = 0 for l in range ( Nl ) : expr_try += a [ l ] * ... | r Rewrite a symbolic expression in terms of allowed transition detunings . |
50,442 | def term_code ( mu , nu , coef , matrix_form , rhouv_isconjugated , linear = True ) : r if coef == 0 : return "" coef = str ( coef ) ini = coef . find ( "E_{0" ) fin = coef . find ( "}" ) if ini != - 1 : l = int ( coef [ ini + 4 : fin ] ) coef = coef [ : ini ] + "Ep[" + str ( l - 1 ) + "]" + coef [ fin + 1 : ] coef = c... | r Get code to calculate a linear term . |
50,443 | def observable ( operator , rho , unfolding , complex = False ) : r if len ( rho . shape ) == 2 : return np . array ( [ observable ( operator , i , unfolding ) for i in rho ] ) Ne = unfolding . Ne Mu = unfolding . Mu obs = 0 if unfolding . normalized : rho11 = 1 - sum ( [ rho [ Mu ( 1 , i , i ) ] for i in range ( 1 , N... | r Return an observable ammount . |
50,444 | def electric_succeptibility ( l , Ep , epsilonp , rm , n , rho , unfolding , part = 0 ) : r epsilonm = epsilonp . conjugate ( ) rp = np . array ( [ rm [ i ] . transpose ( ) . conjugate ( ) for i in range ( 3 ) ] ) if part == 1 : op = cartesian_dot_product ( rp , epsilonm [ 0 ] ) op += cartesian_dot_product ( rm , epsil... | r Return the electric succeptibility for a given field . |
50,445 | def radiated_intensity ( rho , i , j , epsilonp , rm , omega_level , xi , N , D , unfolding ) : r def inij ( i , j , ilist , jlist ) : if ( i in ilist ) and ( j in jlist ) : return 1 else : return 0 rm = np . array ( rm ) Nl = xi . shape [ 0 ] Ne = xi . shape [ 1 ] aux = define_simplification ( omega_level , xi , Nl ) ... | r Return the radiated intensity in a given direction . |
50,446 | def inverse ( self , rhov , time_derivative = False ) : r Ne = self . Ne Nrho = self . Nrho IJ = self . IJ if isinstance ( rhov , np . ndarray ) : rho = np . zeros ( ( Ne , Ne ) , complex ) numeric = True elif isinstance ( rhov , sympy . Matrix ) : rho = sympy . zeros ( Ne , Ne ) numeric = False for mu in range ( Nrho ... | r Fold a vector into a matrix . |
50,447 | def eplotter ( task , data ) : results , color , fdata = [ ] , None , [ ] if task == 'optstory' : color = '#CC0000' clickable = True for n , i in enumerate ( data ) : fdata . append ( [ n , i [ 4 ] ] ) fdata = array ( fdata ) fdata [ : , 1 ] -= min ( fdata [ : , 1 ] ) fdata = fdata . tolist ( ) elif task == 'convergenc... | eplotter is like bdplotter but less complicated |
50,448 | def popenCLIExecutable ( command , ** kwargs ) : cliExecutable = command [ 0 ] ma = re_slicerSubPath . search ( cliExecutable ) if ma : wrapper = os . path . join ( cliExecutable [ : ma . start ( ) ] , 'Slicer' ) if sys . platform . startswith ( 'win' ) : wrapper += '.exe' if os . path . exists ( wrapper ) : command = ... | Wrapper around subprocess . Popen constructor that tries to detect Slicer CLI modules and launches them through the Slicer launcher in order to prevent potential DLL dependency issues . |
50,449 | def _candidate_filenames ( ) : while True : random_stub = '' . join ( [ random . choice ( string . ascii_letters + string . digits ) for _ in range ( 5 ) ] ) yield 'specktre_%s.png' % random_stub | Generates filenames of the form specktre_123AB . png . |
50,450 | def draw_tiling ( coord_generator , filename ) : im = Image . new ( 'L' , size = ( CANVAS_WIDTH , CANVAS_HEIGHT ) ) for shape in coord_generator ( CANVAS_WIDTH , CANVAS_HEIGHT ) : ImageDraw . Draw ( im ) . polygon ( shape , outline = 'white' ) im . save ( filename ) | Given a coordinate generator and a filename render those coordinates in a new image and save them to the file . |
50,451 | def trace ( self , msg , * args , ** kwargs ) : if self . isEnabledFor ( TRACE ) : self . _log ( TRACE , msg , args , ** kwargs ) | Log msg % args with severity TRACE . |
50,452 | def get_state ( cls , clz ) : if clz not in cls . __shared_state : cls . __shared_state [ clz ] = ( clz . init_state ( ) if hasattr ( clz , "init_state" ) else { } ) return cls . __shared_state [ clz ] | Retrieve the state of a given Class . |
50,453 | def define_density_matrix ( Ne , explicitly_hermitian = False , normalized = False , variables = None ) : r if Ne > 9 : comma = "," name = r"\rho" open_brace = "_{" close_brace = "}" else : comma = "" name = "rho" open_brace = "" close_brace = "" rho = [ ] for i in range ( Ne ) : row_rho = [ ] for j in range ( Ne ) : i... | r Return a symbolic density matrix . |
50,454 | def define_laser_variables ( Nl , real_amplitudes = False , variables = None ) : r if variables is None : E0 = [ Symbol ( r"E_0^" + str ( l + 1 ) , real = real_amplitudes ) for l in range ( Nl ) ] else : E0 = [ Function ( r"E_0^" + str ( l + 1 ) , real = real_amplitudes ) ( * variables ) for l in range ( Nl ) ] omega_l... | r Return the amplitudes and frequencies of Nl fields . |
50,455 | def complex_matrix_plot ( A , logA = False , normalize = False , plot = True , ** kwds ) : r N = len ( A [ 0 ] ) if logA : Anew = [ ] for i in range ( N ) : row = [ ] for j in range ( N ) : if A [ i ] [ j ] != 0 : row += [ log ( log ( A [ i ] [ j ] ) ) ] else : row += [ 0.0 ] Anew += [ row ] A = Anew [ : ] if normalize... | r A function to plot complex matrices . |
50,456 | def bar_chart_mf ( data , path_name ) : N = len ( data ) ind = np . arange ( N ) width = 0.8 fig , ax = pyplot . subplots ( ) rects1 = ax . bar ( ind , data , width , color = 'g' ) ax . set_ylabel ( 'Population' ) ax . set_xticks ( ind + width / 2 ) labs = [ 'm=' + str ( i ) for i in range ( - N / 2 + 1 , N / 2 + 1 ) ]... | Make a bar chart for data on MF quantities . |
50,457 | def draw_plane_wave_3d ( ax , beam , dist_to_center = 0 ) : Ex = [ ] Ey = [ ] Ez = [ ] k = [ cos ( beam . phi ) * sin ( beam . theta ) , sin ( beam . phi ) * sin ( beam . theta ) , cos ( beam . theta ) ] kx , ky , kz = k Nt = 1000 tstep = 7 * pi / 4 / ( Nt - 1 ) alpha = beam . alpha beta = beam . beta phi = beam . phi ... | Draw the polarization of a plane wave . |
50,458 | def draw_lasers_3d ( ax , lasers , name = None , distances = None , lim = None ) : if distances is None : distances = [ 1.0 for i in range ( len ( lasers ) ) ] for i in range ( len ( lasers ) ) : if type ( lasers [ i ] ) == PlaneWave : draw_plane_wave_3d ( ax , lasers [ i ] , distances [ i ] ) elif type ( lasers [ i ] ... | Draw MOT lasers in 3d . |
50,459 | def rotate_and_traslate ( cur , alpha , v0 ) : r if len ( cur ) > 2 or ( type ( cur [ 0 ] [ 0 ] ) in [ list , tuple ] ) : cur_list = cur [ : ] for i in range ( len ( cur_list ) ) : curi = cur_list [ i ] curi = rotate_and_traslate ( curi , alpha , v0 ) cur_list [ i ] = curi return cur_list else : x0 , y0 = cur rot = np ... | r Rotate and translate a curve . |
50,460 | def mirror ( ax , p0 , alpha = 0 , size = 2.54 , width = 0.5 , format = None ) : r if format is None : format = 'k-' x0 = [ size / 2 , - size / 2 , - size / 2 , size / 2 , size / 2 ] y0 = [ 0 , 0 , - width , - width , 0 ] x1 = [ size / 2 , size / 2 - width ] y1 = [ 0 , - width ] x2 = [ - size / 2 + width , - size / 2 ]... | r Draw a mirror . |
50,461 | def eye ( ax , p0 , size = 1.0 , alpha = 0 , format = None , ** kwds ) : r if format is None : format = 'k-' N = 100 ang0 = pi - 3 * pi / 16 angf = pi + 3 * pi / 16 angstep = ( angf - ang0 ) / ( N - 1 ) x1 = [ size * ( cos ( i * angstep + ang0 ) + 1 ) for i in range ( N ) ] y1 = [ size * sin ( i * angstep + ang0 ) for ... | r Draw an eye . |
50,462 | def beam_splitter ( ax , p0 , size = 2.54 , alpha = 0 , format = None , ** kwds ) : r if format is None : format = 'k-' a = size / 2 x0 = [ a , - a , - a , a , a , - a ] y0 = [ a , a , - a , - a , a , - a ] cur_list = [ ( x0 , y0 ) ] cur_list = rotate_and_traslate ( cur_list , alpha , p0 ) for curi in cur_list : ax . p... | r Draw a beam splitter . |
50,463 | def simple_beam_splitter ( ax , p0 , size = 2.54 , width = 0.1 , alpha = 0 , format = None , ** kwds ) : r if format is None : format = 'k-' a = size / 2 b = width / 2 x0 = [ a , - a , - a , a , a ] y0 = [ b , b , - b , - b , b ] cur_list = [ ( x0 , y0 ) ] cur_list = rotate_and_traslate ( cur_list , alpha , p0 ) for cu... | r Draw a simple beam splitter . |
50,464 | def draw_arith ( ax , p0 , size = 1 , alpha = 0 , arith = None , format = None , fontsize = 10 , ** kwds ) : r if format is None : format = 'k-' a = size / 2.0 x0 = [ 0 , 2.5 * a , 0 , 0 ] y0 = [ a , 0 , - a , a ] cur_list = [ ( x0 , y0 ) ] cur_list = rotate_and_traslate ( cur_list , alpha , p0 ) for curi in cur_list :... | r Draw an arithmetic operator . |
50,465 | def draw_state ( ax , p , text = '' , l = 0.5 , alignment = 'left' , label_displacement = 1.0 , fontsize = 25 , atoms = None , atoms_h = 0.125 , atoms_size = 5 , ** kwds ) : r ax . plot ( [ p [ 0 ] - l / 2.0 , p [ 0 ] + l / 2.0 ] , [ p [ 1 ] , p [ 1 ] ] , color = 'black' , ** kwds ) if text != '' : if alignment == 'lef... | r Draw a quantum state for energy level diagrams . |
50,466 | def decay ( ax , p0 , pf , A , n , format = None , ** kwds ) : r if format is None : format = 'k-' T = sqrt ( ( p0 [ 0 ] - pf [ 0 ] ) ** 2 + ( p0 [ 1 ] - pf [ 1 ] ) ** 2 ) alpha = atan2 ( pf [ 1 ] - p0 [ 1 ] , pf [ 0 ] - p0 [ 0 ] ) x = [ i * T / 400.0 for i in range ( 401 ) ] y = [ A * sin ( xi * 2 * pi * n / T ) for x... | r Draw a spontaneous decay as a wavy line . |
50,467 | def dup2 ( a , b , timeout = 3 ) : dup_err = None for i in range ( int ( 10 * timeout ) ) : try : return os . dup2 ( a , b ) except OSError as e : dup_err = e if e . errno == errno . EBUSY : time . sleep ( 0.1 ) else : raise if dup_err : raise dup_err | Like os . dup2 but retry on EBUSY |
50,468 | def push_filters ( self , new_filters ) : t = self . tokenizer for f in new_filters : t = f ( t ) self . tokenizer = t | Add a filter to the tokenizer chain . |
50,469 | def check ( self , text ) : for word , pos in self . tokenizer ( text ) : correct = self . dictionary . check ( word ) if correct : continue yield word , self . dictionary . suggest ( word ) if self . suggest else [ ] return | Yields bad words and suggested alternate spellings . |
50,470 | def all_nodes_that_receive ( service , service_configuration = None , run_only = False , deploy_to_only = False ) : assert not ( run_only and deploy_to_only ) if service_configuration is None : service_configuration = read_services_configuration ( ) runs_on = service_configuration [ service ] [ 'runs_on' ] deployed_to ... | If run_only returns only the services that are in the runs_on list . If deploy_to_only returns only the services in the deployed_to list . If neither both are returned duplicates stripped . Results are always sorted . |
50,471 | def precision_and_scale ( x ) : if isinstance ( x , Decimal ) : precision = len ( x . as_tuple ( ) . digits ) scale = - 1 * x . as_tuple ( ) . exponent if scale < 0 : precision -= scale scale = 0 return ( precision , scale ) max_digits = 14 int_part = int ( abs ( x ) ) magnitude = 1 if int_part == 0 else int ( math . l... | From a float decide what precision and scale are needed to represent it . |
50,472 | def best_representative ( d1 , d2 ) : if hasattr ( d2 , 'strip' ) and not d2 . strip ( ) : return d1 if d1 is None : return d2 elif d2 is None : return d1 preference = ( datetime . datetime , bool , int , Decimal , float , str ) worst_pref = 0 worst = '' for coerced in ( d1 , d2 ) : pref = preference . index ( type ( c... | Given two objects each coerced to the most specific type possible return the one of the least restrictive type . |
50,473 | def best_coercable ( data ) : preference = ( datetime . datetime , bool , int , Decimal , float , str ) worst_pref = 0 worst = '' for datum in data : coerced = coerce_to_specific ( datum ) pref = preference . index ( type ( coerced ) ) if pref > worst_pref : worst_pref = pref worst = coerced elif pref == worst_pref : i... | Given an iterable of scalar data returns the datum representing the most specific data type the list overall can be coerced into preferring datetimes then bools then integers then decimals then floats then strings . |
50,474 | def sqla_datatype_for ( datum ) : try : if len ( _complex_enough_to_be_date . findall ( datum ) ) > 1 : dateutil . parser . parse ( datum ) return sa . DATETIME except ( TypeError , ValueError ) : pass try : ( prec , scale ) = precision_and_scale ( datum ) return sa . DECIMAL ( prec , scale ) except TypeError : return ... | Given a scalar Python value picks an appropriate SQLAlchemy data type . |
50,475 | def generate ( args = None , namespace = None , file = None ) : if hasattr ( args , 'split' ) : args = args . split ( ) args = parser . parse_args ( args , namespace ) set_logging ( args ) logging . info ( str ( args ) ) if args . dialect in ( 'pg' , 'pgsql' , 'postgres' ) : args . dialect = 'postgresql' if args . dial... | Genereate DDL from data sources named . |
50,476 | def ddl ( self , dialect = None , creates = True , drops = True ) : dialect = self . _dialect ( dialect ) creator = CreateTable ( self . table ) . compile ( mock_engines [ dialect ] ) creator = "\n" . join ( l for l in str ( creator ) . splitlines ( ) if l . strip ( ) ) comments = "\n\n" . join ( self . _comment_wrappe... | Returns SQL to define the table . |
50,477 | def sqlalchemy ( self , is_top = True ) : table_def = self . table_backref_remover . sub ( '' , self . table . __repr__ ( ) ) constraint_defs = [ ] for constraint in self . table . constraints : if isinstance ( constraint , sa . sql . schema . UniqueConstraint ) : col_list = ', ' . join ( "'%s'" % c . name for c in con... | Dumps Python code to set up the table s SQLAlchemy model |
50,478 | def _prep_datum ( self , datum , dialect , col , needs_conversion ) : if datum is None or ( needs_conversion and not str ( datum ) . strip ( ) ) : return 'NULL' pytype = self . columns [ col ] [ 'pytype' ] if needs_conversion : if pytype == datetime . datetime : datum = dateutil . parser . parse ( datum ) elif pytype =... | Puts a value in proper format for a SQL string |
50,479 | def _id_fieldname ( fieldnames , table_name = '' ) : templates = [ '%s_%%s' % table_name , '%s' , '_%s' ] for stub in [ 'id' , 'num' , 'no' , 'number' ] : for t in templates : if t % stub in fieldnames : return t % stub | Finds the field name from a dict likeliest to be its unique ID |
50,480 | def unnest_child_dict ( parent , key , parent_name = '' ) : val = parent [ key ] name = "%s['%s']" % ( parent_name , key ) logging . debug ( "Unnesting dict %s" % name ) id = _id_fieldname ( val , parent_name ) if id : logging . debug ( "%s is %s's ID" % ( id , key ) ) if len ( val ) <= 2 : logging . debug ( 'Removing ... | If parent dictionary has a key whose val is a dict unnest val s fields into parent and remove key . |
50,481 | def parse ( data ) : reader = io . BytesIO ( data ) headers = [ ] while reader . tell ( ) < len ( data ) : h = Header ( ) h . tag = int . from_bytes ( reader . read ( 2 ) , byteorder = 'big' , signed = False ) h . taglen = int . from_bytes ( reader . read ( 2 ) , byteorder = 'big' , signed = False ) h . tagdata = reade... | returns a list of header tags |
50,482 | def to_tgt ( self ) : enc_part = EncryptedData ( { 'etype' : 1 , 'cipher' : b'' } ) tgt_rep = { } tgt_rep [ 'pvno' ] = krb5_pvno tgt_rep [ 'msg-type' ] = MESSAGE_TYPE . KRB_AS_REP . value tgt_rep [ 'crealm' ] = self . server . realm . to_string ( ) tgt_rep [ 'cname' ] = self . client . to_asn1 ( ) [ 0 ] tgt_rep [ 'tick... | Returns the native format of an AS_REP message and the sessionkey in EncryptionKey native format |
50,483 | def from_kirbidir ( directory_path ) : cc = CCACHE ( ) dir_path = os . path . join ( os . path . abspath ( directory_path ) , '*.kirbi' ) for filename in glob . glob ( dir_path ) : with open ( filename , 'rb' ) as f : kirbidata = f . read ( ) kirbi = KRBCRED . load ( kirbidata ) . native cc . add_kirbi ( kirbi ) return... | Iterates trough all . kirbi files in a given directory and converts all of them into one CCACHE object |
50,484 | def to_file ( self , filename ) : with open ( filename , 'wb' ) as f : f . write ( self . to_bytes ( ) ) | Writes the contents of the CCACHE object to a file |
50,485 | def print_table ( lines , separate_head = True ) : widths = [ ] for line in lines : for i , size in enumerate ( [ len ( x ) for x in line ] ) : while i >= len ( widths ) : widths . append ( 0 ) if size > widths [ i ] : widths [ i ] = size print_string = "" for i , width in enumerate ( widths ) : print_string += "{" + s... | Prints a formatted table given a 2 dimensional array |
50,486 | def get_key_for_enctype ( self , etype ) : if etype == EncryptionType . AES256_CTS_HMAC_SHA1_96 : if self . kerberos_key_aes_256 : return bytes . fromhex ( self . kerberos_key_aes_256 ) if self . password is not None : salt = ( self . domain . upper ( ) + self . username ) . encode ( ) return string_to_key ( Enctype . ... | Returns the encryption key bytes for the enctryption type . |
50,487 | def run ( self , realm , users ) : existing_users = [ ] for user in users : logging . debug ( 'Probing user %s' % user ) req = KerberosUserEnum . construct_tgt_req ( realm , user ) rep = self . ksoc . sendrecv ( req . dump ( ) , throw = False ) if rep . name != 'KRB_ERROR' : existing_users . append ( user ) elif rep . ... | Requests a TGT in the name of the users specified in users . Returns a list of usernames that are in the domain . |
50,488 | def from_tgt ( ksoc , tgt , key ) : kc = KerbrosComm ( None , ksoc ) kc . kerberos_TGT = tgt kc . kerberos_cipher_type = key [ 'keytype' ] kc . kerberos_session_key = Key ( kc . kerberos_cipher_type , key [ 'keyvalue' ] ) kc . kerberos_cipher = _enctype_table [ kc . kerberos_cipher_type ] return kc | Sets up the kerberos object from tgt and the session key . Use this function when pulling the TGT from ccache file . |
50,489 | def get_TGS ( self , spn_user , override_etype = None ) : logger . debug ( 'Constructing TGS request for user %s' % spn_user . get_formatted_pname ( ) ) now = datetime . datetime . utcnow ( ) kdc_req_body = { } kdc_req_body [ 'kdc-options' ] = KDCOptions ( set ( [ 'forwardable' , 'renewable' , 'renewable_ok' , 'canonic... | Requests a TGS ticket for the specified user . Retruns the TGS ticket end the decrpyted encTGSRepPart . |
50,490 | def minimise ( table , target_length , check_for_aliases = True ) : if check_for_aliases : if len ( set ( e . mask for e in table ) ) == 1 and len ( table ) == len ( set ( e . key for e in table ) ) : check_for_aliases = False new_table = list ( ) for i , entry in enumerate ( table ) : if not _is_defaultable ( i , entr... | Remove from the routing table any entries which could be replaced by default routing . |
50,491 | def _is_defaultable ( i , entry , table , check_for_aliases = True ) : if ( len ( entry . sources ) == 1 and len ( entry . route ) == 1 and None not in entry . sources ) : source = next ( iter ( entry . sources ) ) sink = next ( iter ( entry . route ) ) if source . is_link and sink . is_link : if source . opposite is s... | Determine if an entry may be removed from a routing table and be replaced by a default route . |
50,492 | def table_is_subset_of ( entries_a , entries_b ) : common_xs = get_common_xs ( entries_b ) for entry in expand_entries ( entries_a , ignore_xs = common_xs ) : for other_entry in entries_b : if other_entry . mask & entry . key == other_entry . key : if other_entry . route == entry . route : break else : return False els... | Check that every key matched by every entry in one table results in the same route when checked against the other table . |
50,493 | def expand_entry ( entry , ignore_xs = 0x0 ) : xs = ( ~ entry . key & ~ entry . mask ) & ~ ignore_xs for bit in ( 1 << i for i in range ( 31 , - 1 , - 1 ) ) : if bit & xs : entry_0 = RoutingTableEntry ( entry . route , entry . key , entry . mask | bit , entry . sources ) for new_entry in expand_entry ( entry_0 , ignore... | Turn all Xs which are not marked in ignore_xs into 0 \ s and 1 \ s . |
50,494 | def expand_entries ( entries , ignore_xs = None ) : if ignore_xs is None : ignore_xs = get_common_xs ( entries ) seen_keys = set ( { } ) for entry in entries : for new_entry in expand_entry ( entry , ignore_xs ) : if new_entry . key in seen_keys : warnings . warn ( "Table is not orthogonal: Key {:#010x} matches " "mult... | Turn all Xs which are not ignored in all entries into 0 s and 1 s . |
50,495 | def get_common_xs ( entries ) : key = 0x00000000 mask = 0x00000000 for entry in entries : key |= entry . key mask |= entry . mask return ( ~ ( key | mask ) ) & 0xffffffff | Return a mask of where there are Xs in all routing table entries . |
50,496 | def slices_overlap ( slice_a , slice_b ) : assert slice_a . step is None assert slice_b . step is None return max ( slice_a . start , slice_b . start ) < min ( slice_a . stop , slice_b . stop ) | Test if the ranges covered by a pair of slices overlap . |
50,497 | def concentric_hexagons ( radius , start = ( 0 , 0 ) ) : x , y = start yield ( x , y ) for r in range ( 1 , radius + 1 ) : y -= 1 for dx , dy in [ ( 1 , 1 ) , ( 0 , 1 ) , ( - 1 , 0 ) , ( - 1 , - 1 ) , ( 0 , - 1 ) , ( 1 , 0 ) ] : for _ in range ( r ) : yield ( x , y ) x += dx y += dy | A generator which produces coordinates of concentric rings of hexagons . |
50,498 | def spinn5_eth_coords ( width , height , root_x = 0 , root_y = 0 ) : root_x %= 12 root_x %= 12 w = ( ( width + 11 ) // 12 ) * 12 h = ( ( height + 11 ) // 12 ) * 12 for x in range ( 0 , w , 12 ) : for y in range ( 0 , h , 12 ) : for dx , dy in ( ( 0 , 0 ) , ( 4 , 8 ) , ( 8 , 4 ) ) : nx = ( x + dx + root_x ) % w ny = ( y... | Generate a list of board coordinates with Ethernet connectivity in a SpiNNaker machine . |
50,499 | def spinn5_local_eth_coord ( x , y , w , h , root_x = 0 , root_y = 0 ) : dx , dy = SPINN5_ETH_OFFSET [ ( y - root_y ) % 12 ] [ ( x - root_x ) % 12 ] return ( ( x + int ( dx ) ) % w ) , ( ( y + int ( dy ) ) % h ) | Get the coordinates of a chip s local ethernet connected chip . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.