idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
238,800 | def _createBitpattern ( functioncode , value ) : _checkFunctioncode ( functioncode , [ 5 , 15 ] ) _checkInt ( value , minvalue = 0 , maxvalue = 1 , description = 'inputvalue' ) if functioncode == 5 : if value == 0 : return '\x00\x00' else : return '\xff\x00' elif functioncode == 15 : if value == 0 : return '\x00' else ... | Create the bit pattern that is used for writing single bits . |
238,801 | def _twosComplement ( x , bits = 16 ) : _checkInt ( bits , minvalue = 0 , description = 'number of bits' ) _checkInt ( x , description = 'input' ) upperlimit = 2 ** ( bits - 1 ) - 1 lowerlimit = - 2 ** ( bits - 1 ) if x > upperlimit or x < lowerlimit : raise ValueError ( 'The input value is out of range. Given value is... | Calculate the two s complement of an integer . |
238,802 | def _setBitOn ( x , bitNum ) : _checkInt ( x , minvalue = 0 , description = 'input value' ) _checkInt ( bitNum , minvalue = 0 , description = 'bitnumber' ) return x | ( 1 << bitNum ) | Set bit bitNum to True . |
238,803 | def _calculateCrcString ( inputstring ) : _checkString ( inputstring , description = 'input CRC string' ) register = 0xFFFF for char in inputstring : register = ( register >> 8 ) ^ _CRC16TABLE [ ( register ^ ord ( char ) ) & 0xFF ] return _numToTwoByteString ( register , LsbFirst = True ) | Calculate CRC - 16 for Modbus . |
238,804 | def _calculateLrcString ( inputstring ) : _checkString ( inputstring , description = 'input LRC string' ) register = 0 for character in inputstring : register += ord ( character ) lrc = ( ( register ^ 0xFF ) + 1 ) & 0xFF lrcString = _numToOneByteString ( lrc ) return lrcString | Calculate LRC for Modbus . |
238,805 | def _checkMode ( mode ) : if not isinstance ( mode , str ) : raise TypeError ( 'The {0} should be a string. Given: {1!r}' . format ( "mode" , mode ) ) if mode not in [ MODE_RTU , MODE_ASCII ] : raise ValueError ( "Unreconized Modbus mode given. Must be 'rtu' or 'ascii' but {0!r} was given." . format ( mode ) ) | Check that the Modbus mode is valie . |
238,806 | def _checkFunctioncode ( functioncode , listOfAllowedValues = [ ] ) : FUNCTIONCODE_MIN = 1 FUNCTIONCODE_MAX = 127 _checkInt ( functioncode , FUNCTIONCODE_MIN , FUNCTIONCODE_MAX , description = 'functioncode' ) if listOfAllowedValues is None : return if not isinstance ( listOfAllowedValues , list ) : raise TypeError ( '... | Check that the given functioncode is in the listOfAllowedValues . |
238,807 | def _checkResponseByteCount ( payload ) : POSITION_FOR_GIVEN_NUMBER = 0 NUMBER_OF_BYTES_TO_SKIP = 1 _checkString ( payload , minlength = 1 , description = 'payload' ) givenNumberOfDatabytes = ord ( payload [ POSITION_FOR_GIVEN_NUMBER ] ) countedNumberOfDatabytes = len ( payload ) - NUMBER_OF_BYTES_TO_SKIP if givenNumbe... | Check that the number of bytes as given in the response is correct . |
238,808 | def _checkResponseRegisterAddress ( payload , registeraddress ) : _checkString ( payload , minlength = 2 , description = 'payload' ) _checkRegisteraddress ( registeraddress ) BYTERANGE_FOR_STARTADDRESS = slice ( 0 , 2 ) bytesForStartAddress = payload [ BYTERANGE_FOR_STARTADDRESS ] receivedStartAddress = _twoByteStringT... | Check that the start adress as given in the response is correct . |
238,809 | def _checkResponseNumberOfRegisters ( payload , numberOfRegisters ) : _checkString ( payload , minlength = 4 , description = 'payload' ) _checkInt ( numberOfRegisters , minvalue = 1 , maxvalue = 0xFFFF , description = 'numberOfRegisters' ) BYTERANGE_FOR_NUMBER_OF_REGISTERS = slice ( 2 , 4 ) bytesForNumberOfRegisters = ... | Check that the number of written registers as given in the response is correct . |
238,810 | def _checkResponseWriteData ( payload , writedata ) : _checkString ( payload , minlength = 4 , description = 'payload' ) _checkString ( writedata , minlength = 2 , maxlength = 2 , description = 'writedata' ) BYTERANGE_FOR_WRITEDATA = slice ( 2 , 4 ) receivedWritedata = payload [ BYTERANGE_FOR_WRITEDATA ] if receivedWri... | Check that the write data as given in the response is correct . |
238,811 | def _checkString ( inputstring , description , minlength = 0 , maxlength = None ) : if not isinstance ( description , str ) : raise TypeError ( 'The description should be a string. Given: {0!r}' . format ( description ) ) if not isinstance ( inputstring , str ) : raise TypeError ( 'The {0} should be a string. Given: {1... | Check that the given string is valid . |
238,812 | def _checkInt ( inputvalue , minvalue = None , maxvalue = None , description = 'inputvalue' ) : if not isinstance ( description , str ) : raise TypeError ( 'The description should be a string. Given: {0!r}' . format ( description ) ) if not isinstance ( inputvalue , ( int , long ) ) : raise TypeError ( 'The {0} must be... | Check that the given integer is valid . |
238,813 | def _checkNumerical ( inputvalue , minvalue = None , maxvalue = None , description = 'inputvalue' ) : if not isinstance ( description , str ) : raise TypeError ( 'The description should be a string. Given: {0!r}' . format ( description ) ) if not isinstance ( inputvalue , ( int , long , float ) ) : raise TypeError ( 'T... | Check that the given numerical value is valid . |
238,814 | def _checkBool ( inputvalue , description = 'inputvalue' ) : _checkString ( description , minlength = 1 , description = 'description string' ) if not isinstance ( inputvalue , bool ) : raise TypeError ( 'The {0} must be boolean. Given: {1!r}' . format ( description , inputvalue ) ) | Check that the given inputvalue is a boolean . |
238,815 | def _getDiagnosticString ( ) : text = '\n## Diagnostic output from minimalmodbus ## \n\n' text += 'Minimalmodbus version: ' + __version__ + '\n' text += 'Minimalmodbus status: ' + __status__ + '\n' text += 'File name (with relative path): ' + __file__ + '\n' text += 'Full file path: ' + os . path . abspath ( __file__ )... | Generate a diagnostic string showing the module version the platform current directory etc . |
238,816 | def read_bit ( self , registeraddress , functioncode = 2 ) : _checkFunctioncode ( functioncode , [ 1 , 2 ] ) return self . _genericCommand ( functioncode , registeraddress ) | Read one bit from the slave . |
238,817 | def write_bit ( self , registeraddress , value , functioncode = 5 ) : _checkFunctioncode ( functioncode , [ 5 , 15 ] ) _checkInt ( value , minvalue = 0 , maxvalue = 1 , description = 'input value' ) self . _genericCommand ( functioncode , registeraddress , value ) | Write one bit to the slave . |
238,818 | def read_register ( self , registeraddress , numberOfDecimals = 0 , functioncode = 3 , signed = False ) : _checkFunctioncode ( functioncode , [ 3 , 4 ] ) _checkInt ( numberOfDecimals , minvalue = 0 , maxvalue = 10 , description = 'number of decimals' ) _checkBool ( signed , description = 'signed' ) return self . _gener... | Read an integer from one 16 - bit register in the slave possibly scaling it . |
238,819 | def write_register ( self , registeraddress , value , numberOfDecimals = 0 , functioncode = 16 , signed = False ) : _checkFunctioncode ( functioncode , [ 6 , 16 ] ) _checkInt ( numberOfDecimals , minvalue = 0 , maxvalue = 10 , description = 'number of decimals' ) _checkBool ( signed , description = 'signed' ) _checkNum... | Write an integer to one 16 - bit register in the slave possibly scaling it . |
238,820 | def read_float ( self , registeraddress , functioncode = 3 , numberOfRegisters = 2 ) : _checkFunctioncode ( functioncode , [ 3 , 4 ] ) _checkInt ( numberOfRegisters , minvalue = 2 , maxvalue = 4 , description = 'number of registers' ) return self . _genericCommand ( functioncode , registeraddress , numberOfRegisters = ... | Read a floating point number from the slave . |
238,821 | def write_float ( self , registeraddress , value , numberOfRegisters = 2 ) : _checkNumerical ( value , description = 'input value' ) _checkInt ( numberOfRegisters , minvalue = 2 , maxvalue = 4 , description = 'number of registers' ) self . _genericCommand ( 16 , registeraddress , value , numberOfRegisters = numberOfReg... | Write a floating point number to the slave . |
238,822 | def read_string ( self , registeraddress , numberOfRegisters = 16 , functioncode = 3 ) : _checkFunctioncode ( functioncode , [ 3 , 4 ] ) _checkInt ( numberOfRegisters , minvalue = 1 , description = 'number of registers for read string' ) return self . _genericCommand ( functioncode , registeraddress , numberOfRegisters... | Read a string from the slave . |
238,823 | def write_string ( self , registeraddress , textstring , numberOfRegisters = 16 ) : _checkInt ( numberOfRegisters , minvalue = 1 , description = 'number of registers for write string' ) _checkString ( textstring , 'input string' , minlength = 1 , maxlength = 2 * numberOfRegisters ) self . _genericCommand ( 16 , registe... | Write a string to the slave . |
238,824 | def write_registers ( self , registeraddress , values ) : if not isinstance ( values , list ) : raise TypeError ( 'The "values parameter" must be a list. Given: {0!r}' . format ( values ) ) _checkInt ( len ( values ) , minvalue = 1 , description = 'length of input list' ) self . _genericCommand ( 16 , registeraddress ,... | Write integers to 16 - bit registers in the slave . |
238,825 | def _communicate ( self , request , number_of_bytes_to_read ) : _checkString ( request , minlength = 1 , description = 'request' ) _checkInt ( number_of_bytes_to_read ) if self . debug : _print_out ( '\nMinimalModbus debug mode. Writing to instrument (expecting {} bytes back): {!r} ({})' . format ( number_of_bytes_to_r... | Talk to the slave via a serial port . |
238,826 | def _playsoundWin ( sound , block = True ) : from ctypes import c_buffer , windll from random import random from time import sleep from sys import getfilesystemencoding def winCommand ( * command ) : buf = c_buffer ( 255 ) command = ' ' . join ( command ) . encode ( getfilesystemencoding ( ) ) errorCode = int ( windll ... | Utilizes windll . winmm . Tested and known to work with MP3 and WAVE on Windows 7 with Python 2 . 7 . Probably works with more file formats . Probably works on Windows XP thru Windows 10 . Probably works with all versions of Python . |
238,827 | def _playsoundOSX ( sound , block = True ) : from AppKit import NSSound from Foundation import NSURL from time import sleep if '://' not in sound : if not sound . startswith ( '/' ) : from os import getcwd sound = getcwd ( ) + '/' + sound sound = 'file://' + sound url = NSURL . URLWithString_ ( sound ) nssound = NSSoun... | Utilizes AppKit . NSSound . Tested and known to work with MP3 and WAVE on OS X 10 . 11 with Python 2 . 7 . Probably works with anything QuickTime supports . Probably works on OS X 10 . 5 and newer . Probably works with all versions of Python . |
238,828 | def _playsoundNix ( sound , block = True ) : if not block : raise NotImplementedError ( "block=False cannot be used on this platform yet" ) import os try : from urllib . request import pathname2url except ImportError : from urllib import pathname2url import gi gi . require_version ( 'Gst' , '1.0' ) from gi . repository... | Play a sound using GStreamer . |
238,829 | def remove_rows_matching ( df , column , match ) : df = df . copy ( ) mask = df [ column ] . values != match return df . iloc [ mask , : ] | Return a DataFrame with rows where column values match match are removed . |
238,830 | def remove_rows_containing ( df , column , match ) : df = df . copy ( ) mask = [ match not in str ( v ) for v in df [ column ] . values ] return df . iloc [ mask , : ] | Return a DataFrame with rows where column values containing match are removed . |
238,831 | def filter_localization_probability ( df , threshold = 0.75 ) : df = df . copy ( ) localization_probability_mask = df [ 'Localization prob' ] . values >= threshold return df . iloc [ localization_probability_mask , : ] | Remove rows with a localization probability below 0 . 75 |
238,832 | def minimum_valid_values_in_any_group ( df , levels = None , n = 1 , invalid = np . nan ) : df = df . copy ( ) if levels is None : if 'Group' in df . columns . names : levels = [ df . columns . names . index ( 'Group' ) ] if invalid is np . nan : dfx = ~ np . isnan ( df ) else : dfx = df != invalid dfc = dfx . astype (... | Filter DataFrame by at least n valid values in at least one group . |
238,833 | def search ( df , match , columns = [ 'Proteins' , 'Protein names' , 'Gene names' ] ) : df = df . copy ( ) dft = df . reset_index ( ) mask = np . zeros ( ( dft . shape [ 0 ] , ) , dtype = bool ) idx = [ 'Proteins' , 'Protein names' , 'Gene names' ] for i in idx : if i in dft . columns : mask = mask | np . array ( [ mat... | Search for a given string in a set of columns in a processed DataFrame . |
238,834 | def filter_select_columns_intensity ( df , prefix , columns ) : return df . filter ( regex = '^(%s.+|%s)$' % ( prefix , '|' . join ( columns ) ) ) | Filter dataframe to include specified columns retaining any Intensity columns . |
238,835 | def filter_intensity ( df , label = "" , with_multiplicity = False ) : label += ".*__\d" if with_multiplicity else "" dft = df . filter ( regex = "^(?!Intensity).*$" ) dfi = df . filter ( regex = '^(.*Intensity.*%s.*__\d)$' % label ) return pd . concat ( [ dft , dfi ] , axis = 1 ) | Filter to include only the Intensity values with optional specified label excluding other Intensity measurements but retaining all other columns . |
238,836 | def filter_ratio ( df , label = "" , with_multiplicity = False ) : label += ".*__\d" if with_multiplicity else "" dft = df . filter ( regex = "^(?!Ratio).*$" ) dfr = df . filter ( regex = '^(.*Ratio.*%s)$' % label ) return pd . concat ( [ dft , dfr ] , axis = 1 ) | Filter to include only the Ratio values with optional specified label excluding other Intensity measurements but retaining all other columns . |
238,837 | def read_perseus ( f ) : df = pd . read_csv ( f , delimiter = '\t' , header = [ 0 , 1 , 2 , 3 ] , low_memory = False ) df . columns = pd . MultiIndex . from_tuples ( [ ( x , ) for x in df . columns . get_level_values ( 0 ) ] ) return df | Load a Perseus processed data table |
238,838 | def write_perseus ( f , df ) : FIELD_TYPE_MAP = { 'Amino acid' : 'C' , 'Charge' : 'C' , 'Reverse' : 'C' , 'Potential contaminant' : 'C' , 'Multiplicity' : 'C' , 'Localization prob' : 'N' , 'PEP' : 'N' , 'Score' : 'N' , 'Delta score' : 'N' , 'Score for localization' : 'N' , 'Mass error [ppm]' : 'N' , 'Intensity' : 'N' ,... | Export a dataframe to Perseus ; recreating the format |
238,839 | def write_phosphopath_ratio ( df , f , a , * args , ** kwargs ) : timepoint_idx = kwargs . get ( 'timepoint_idx' , None ) proteins = [ get_protein_id ( k ) for k in df . index . get_level_values ( 'Proteins' ) ] amino_acids = df . index . get_level_values ( 'Amino acid' ) positions = _get_positions ( df ) multiplicity ... | Write out the data frame ratio between two groups protein - Rsite - multiplicity - timepoint ID Ratio Q13619 - S10 - 1 - 1 0 . 5 Q9H3Z4 - S10 - 1 - 1 0 . 502 Q6GQQ9 - S100 - 1 - 1 0 . 504 Q86YP4 - S100 - 1 - 1 0 . 506 Q9H307 - S100 - 1 - 1 0 . 508 Q8NEY1 - S1000 - 1 - 1 0 . 51 Q13541 - S101 - 1 - 1 0 . 512 O95785 - S10... |
238,840 | def write_r ( df , f , sep = "," , index_join = "@" , columns_join = "." ) : df = df . copy ( ) df . index = [ "@" . join ( [ str ( s ) for s in v ] ) for v in df . index . values ] df . columns = [ "." . join ( [ str ( s ) for s in v ] ) for v in df . index . values ] df . to_csv ( f , sep = sep ) | Export dataframe in a format easily importable to R |
238,841 | def gaussian ( df , width = 0.3 , downshift = - 1.8 , prefix = None ) : df = df . copy ( ) imputed = df . isnull ( ) if prefix : mask = np . array ( [ l . startswith ( prefix ) for l in df . columns . values ] ) mycols = np . arange ( 0 , df . shape [ 1 ] ) [ mask ] else : mycols = np . arange ( 0 , df . shape [ 1 ] ) ... | Impute missing values by drawing from a normal distribution |
238,842 | def _pca_scores ( scores , pc1 = 0 , pc2 = 1 , fcol = None , ecol = None , marker = 'o' , markersize = 30 , label_scores = None , show_covariance_ellipse = True , optimize_label_iter = OPTIMIZE_LABEL_ITER_DEFAULT , ** kwargs ) : fig = plt . figure ( figsize = ( 8 , 8 ) ) ax = fig . add_subplot ( 1 , 1 , 1 ) levels = [ ... | Plot a scores plot for two principal components as AxB scatter plot . |
238,843 | def modifiedaminoacids ( df , kind = 'pie' ) : colors = [ '#6baed6' , '#c6dbef' , '#bdbdbd' ] total_aas , quants = analysis . modifiedaminoacids ( df ) df = pd . DataFrame ( ) for a , n in quants . items ( ) : df [ a ] = [ n ] df . sort_index ( axis = 1 , inplace = True ) if kind == 'bar' or kind == 'both' : ax1 = df .... | Generate a plot of relative numbers of modified amino acids in source DataFrame . |
238,844 | def venn ( df1 , df2 , df3 = None , labels = None , ix1 = None , ix2 = None , ix3 = None , return_intersection = False , fcols = None ) : try : import matplotlib_venn as mplv except ImportError : raise ImportError ( "To plot venn diagrams, install matplotlib-venn package: pip install matplotlib-venn" ) plt . gcf ( ) . ... | Plot a 2 or 3 - part venn diagram showing the overlap between 2 or 3 pandas DataFrames . |
238,845 | def sitespeptidesproteins ( df , labels = None , colors = None , site_localization_probability = 0.75 ) : fig = plt . figure ( figsize = ( 4 , 6 ) ) ax = fig . add_subplot ( 1 , 1 , 1 ) shift = 0.5 values = analysis . sitespeptidesproteins ( df , site_localization_probability ) if labels is None : labels = [ 'Sites (Cl... | Plot the number of sites peptides and proteins in the dataset . |
238,846 | def _areadist ( ax , v , xr , c , bins = 100 , by = None , alpha = 1 , label = None ) : y , x = np . histogram ( v [ ~ np . isnan ( v ) ] , bins ) x = x [ : - 1 ] if by is None : by = np . zeros ( ( bins , ) ) ax . fill_between ( x , y , by , facecolor = c , alpha = alpha , label = label ) return y | Plot the histogram distribution but as an area plot |
238,847 | def hierarchical_timecourse ( df , cluster_cols = True , cluster_rows = False , n_col_clusters = False , n_row_clusters = False , fcol = None , z_score = 0 , method = 'ward' , cmap = cm . PuOr_r , return_clusters = False , rdistance_fn = distance . pdist , cdistance_fn = distance . pdist , xlabel = 'Timepoint' , ylabel... | Hierarchical clustering of samples across timecourse experiment . |
238,848 | def subtract_column_median ( df , prefix = 'Intensity ' ) : df = df . copy ( ) df . replace ( [ np . inf , - np . inf ] , np . nan , inplace = True ) mask = [ l . startswith ( prefix ) for l in df . columns . values ] df . iloc [ : , mask ] = df . iloc [ : , mask ] - df . iloc [ : , mask ] . median ( axis = 0 ) return ... | Apply column - wise normalisation to expression columns . |
238,849 | def get_protein_id_list ( df , level = 0 ) : protein_list = [ ] for s in df . index . get_level_values ( level ) : protein_list . extend ( get_protein_ids ( s ) ) return list ( set ( protein_list ) ) | Return a complete list of shortform IDs from a DataFrame |
238,850 | def hierarchical_match ( d , k , default = None ) : if d is None : return default if type ( k ) != list and type ( k ) != tuple : k = [ k ] for n , _ in enumerate ( k ) : key = tuple ( k [ 0 : len ( k ) - n ] ) if len ( key ) == 1 : key = key [ 0 ] try : d [ key ] except : pass else : return d [ key ] return default | Match a key against a dict simplifying element at a time |
238,851 | def calculate_s0_curve ( s0 , minpval , maxpval , minratio , maxratio , curve_interval = 0.1 ) : mminpval = - np . log10 ( minpval ) mmaxpval = - np . log10 ( maxpval ) maxpval_adjust = mmaxpval - mminpval ax0 = ( s0 + maxpval_adjust * minratio ) / maxpval_adjust edge_offset = ( maxratio - ax0 ) % curve_interval max_x ... | Calculate s0 curve for volcano plot . |
238,852 | def correlation ( df , rowvar = False ) : df = df . copy ( ) maskv = np . ma . masked_where ( np . isnan ( df . values ) , df . values ) cdf = np . ma . corrcoef ( maskv , rowvar = False ) cdf = pd . DataFrame ( np . array ( cdf ) ) cdf . columns = df . columns cdf . index = df . columns cdf = cdf . sort_index ( level ... | Calculate column - wise Pearson correlations using numpy . ma . corrcoef |
238,853 | def pca ( df , n_components = 2 , mean_center = False , ** kwargs ) : if not sklearn : assert ( 'This library depends on scikit-learn (sklearn) to perform PCA analysis' ) from sklearn . decomposition import PCA df = df . copy ( ) df [ np . isnan ( df ) ] = 0 if mean_center : mean = np . mean ( df . values , axis = 0 ) ... | Principal Component Analysis based on sklearn . decomposition . PCA |
238,854 | def plsda ( df , a , b , n_components = 2 , mean_center = False , scale = True , ** kwargs ) : if not sklearn : assert ( 'This library depends on scikit-learn (sklearn) to perform PLS-DA' ) from sklearn . cross_decomposition import PLSRegression df = df . copy ( ) df [ np . isnan ( df ) ] = 0 if mean_center : mean = np... | Partial Least Squares Discriminant Analysis based on sklearn . cross_decomposition . PLSRegression |
238,855 | def enrichment_from_evidence ( dfe , modification = "Phospho (STY)" ) : dfe = dfe . reset_index ( ) . set_index ( 'Experiment' ) dfe [ 'Modifications' ] = np . array ( [ modification in m for m in dfe [ 'Modifications' ] ] ) dfe = dfe . set_index ( 'Modifications' , append = True ) dfes = dfe . sum ( axis = 0 , level =... | Calculate relative enrichment of peptide modifications from evidence . txt . |
238,856 | def enrichment_from_msp ( dfmsp , modification = "Phospho (STY)" ) : dfmsp [ 'Modifications' ] = np . array ( [ modification in m for m in dfmsp [ 'Modifications' ] ] ) dfmsp = dfmsp . set_index ( [ 'Modifications' ] ) dfmsp = dfmsp . filter ( regex = 'Intensity ' ) dfmsp [ dfmsp == 0 ] = np . nan df_r = dfmsp . sum ( ... | Calculate relative enrichment of peptide modifications from modificationSpecificPeptides . txt . |
238,857 | def sitespeptidesproteins ( df , site_localization_probability = 0.75 ) : sites = filters . filter_localization_probability ( df , site_localization_probability ) [ 'Sequence window' ] peptides = set ( df [ 'Sequence window' ] ) proteins = set ( [ str ( p ) . split ( ';' ) [ 0 ] for p in df [ 'Proteins' ] ] ) return le... | Generate summary count of modified sites peptides and proteins in a processed dataset DataFrame . |
238,858 | def modifiedaminoacids ( df ) : amino_acids = list ( df [ 'Amino acid' ] . values ) aas = set ( amino_acids ) quants = { } for aa in aas : quants [ aa ] = amino_acids . count ( aa ) total_aas = len ( amino_acids ) return total_aas , quants | Calculate the number of modified amino acids in supplied DataFrame . |
238,859 | def build_index_from_design ( df , design , remove_prefix = None , types = None , axis = 1 , auto_convert_numeric = True , unmatched_columns = 'index' ) : df = df . copy ( ) if 'Label' not in design . index . names : design = design . set_index ( 'Label' ) if remove_prefix is None : remove_prefix = [ ] if type ( remove... | Build a MultiIndex from a design table . |
238,860 | def build_index_from_labels ( df , indices , remove_prefix = None , types = None , axis = 1 ) : df = df . copy ( ) if remove_prefix is None : remove_prefix = [ ] if types is None : types = { } idx = [ df . index , df . columns ] [ axis ] indexes = [ ] for l in idx . get_level_values ( 0 ) : for s in remove_prefix : l =... | Build a MultiIndex from a list of labels and matching regex |
238,861 | def combine_expression_columns ( df , columns_to_combine , remove_combined = True ) : df = df . copy ( ) for ca , cb in columns_to_combine : df [ "%s_(x+y)/2_%s" % ( ca , cb ) ] = ( df [ ca ] + df [ cb ] ) / 2 if remove_combined : for ca , cb in columns_to_combine : df . drop ( [ ca , cb ] , inplace = True , axis = 1 )... | Combine expression columns calculating the mean for 2 columns |
238,862 | def expand_side_table ( df ) : df = df . copy ( ) idx = df . index . names df . reset_index ( inplace = True ) def strip_multiplicity ( df ) : df . columns = [ c [ : - 4 ] for c in df . columns ] return df def strip_multiple ( s ) : for sr in [ ' 1' , ' 2' , ' 3' ] : if s . endswith ( sr ) : s = s [ : - 4 ] return s ba... | Perform equivalent of expand side table in Perseus by folding Multiplicity columns down onto duplicate rows |
238,863 | def apply_experimental_design ( df , f , prefix = 'Intensity ' ) : df = df . copy ( ) edt = pd . read_csv ( f , sep = '\t' , header = 0 ) edt . set_index ( 'Experiment' , inplace = True ) new_column_labels = [ ] for l in df . columns . values : try : l = edt . loc [ l . replace ( prefix , '' ) ] [ 'Name' ] except ( Ind... | Load the experimental design template from MaxQuant and use it to apply the label names to the data columns . |
238,864 | def transform_expression_columns ( df , fn = np . log2 , prefix = 'Intensity ' ) : df = df . copy ( ) mask = np . array ( [ l . startswith ( prefix ) for l in df . columns . values ] ) df . iloc [ : , mask ] = fn ( df . iloc [ : , mask ] ) df . replace ( [ np . inf , - np . inf ] , np . nan , inplace = True ) return df | Apply transformation to expression columns . |
238,865 | def fold_columns_to_rows ( df , levels_from = 2 ) : df = df . copy ( ) df . reset_index ( inplace = True , drop = True ) df = df . T a = [ list ( set ( df . index . get_level_values ( i ) ) ) for i in range ( 0 , levels_from ) ] combinations = list ( itertools . product ( * a ) ) names = df . index . names [ : levels_f... | Take a levels from the columns and fold down into the row index . This destroys the existing index ; existing rows will appear as columns under the new column index |
238,866 | def args ( self , args ) : self . _args = args self . _logger . log ( 'debug' , 'Args set to {}' . format ( args ) ) | Set additional arguments to be passed to the fitness function |
238,867 | def minimize ( self , minimize ) : self . _minimize = minimize self . _logger . log ( 'debug' , 'Minimize set to {}' . format ( minimize ) ) | Configures the ABC to minimize fitness function return value or derived score |
238,868 | def num_employers ( self , num_employers ) : if num_employers < 2 : self . _logger . log ( 'warn' , 'Two employers are needed: setting to two' ) num_employers = 2 self . _num_employers = num_employers self . _logger . log ( 'debug' , 'Number of employers set to {}' . format ( num_employers ) ) self . _limit = num_emplo... | Sets the number of employer bees ; at least two are required |
238,869 | def processes ( self , processes ) : if self . _processes > 1 : self . _pool . close ( ) self . _pool . join ( ) self . _pool = multiprocessing . Pool ( processes ) else : self . _pool = None self . _logger . log ( 'debug' , 'Number of processes set to {}' . format ( processes ) ) | Set the number of concurrent processes the ABC will utilize for fitness function evaluation ; if < = 1 single process is used |
238,870 | def infer_process_count ( self ) : try : self . processes = multiprocessing . cpu_count ( ) except NotImplementedError : self . _logger . log ( 'error' , 'Could infer CPU count, setting number of processes back to 4' ) self . processes = 4 | Infers the number of CPU cores in the current system sets the number of concurrent processes accordingly |
238,871 | def create_employers ( self ) : self . __verify_ready ( True ) employers = [ ] for i in range ( self . _num_employers ) : employer = EmployerBee ( self . __gen_random_values ( ) ) if self . _processes <= 1 : employer . error = self . _fitness_fxn ( employer . values , ** self . _args ) employer . score = employer . get... | Generate employer bees . This should be called directly after the ABC is initialized . |
238,872 | def run_iteration ( self ) : self . _employer_phase ( ) self . _calc_probability ( ) self . _onlooker_phase ( ) self . _check_positions ( ) | Runs a single iteration of the ABC ; employer phase - > probability calculation - > onlooker phase - > check positions |
238,873 | def _calc_probability ( self ) : self . _logger . log ( 'debug' , 'Calculating bee probabilities' ) self . __verify_ready ( ) self . _total_score = 0 for employer in self . _employers : self . _total_score += employer . score if self . __update ( employer . score , employer . values , employer . error ) : self . _logge... | Determines the probability that each bee will be chosen during the onlooker phase ; also determines if a new best - performing bee is found |
238,874 | def _merge_bee ( self , bee ) : random_dimension = randint ( 0 , len ( self . _value_ranges ) - 1 ) second_bee = randint ( 0 , self . _num_employers - 1 ) while ( bee . id == self . _employers [ second_bee ] . id ) : second_bee = randint ( 0 , self . _num_employers - 1 ) new_bee = deepcopy ( bee ) new_bee . values [ ra... | Shifts a random value for a supplied bee with in accordance with another random bee s value |
238,875 | def _move_bee ( self , bee , new_values ) : score = np . nan_to_num ( new_values [ 0 ] ) if bee . score > score : bee . failed_trials += 1 else : bee . values = new_values [ 1 ] bee . score = score bee . error = new_values [ 2 ] bee . failed_trials = 0 self . _logger . log ( 'debug' , 'Bee assigned to new merged positi... | Moves a bee to a new position if new fitness score is better than the bee s current fitness score |
238,876 | def __update ( self , score , values , error ) : if self . _minimize : if self . _best_score is None or score > self . _best_score : self . _best_score = score self . _best_values = values . copy ( ) self . _best_error = error self . _logger . log ( 'debug' , 'New best food source memorized: {}' . format ( self . _best... | Update the best score and values if the given score is better than the current best score |
238,877 | def __gen_random_values ( self ) : values = [ ] if self . _value_ranges is None : self . _logger . log ( 'crit' , 'Must set the type/range of possible values' ) raise RuntimeError ( "Must set the type/range of possible values" ) else : for t in self . _value_ranges : if t [ 0 ] == 'int' : values . append ( randint ( t ... | Generate random values based on supplied value ranges |
238,878 | def __verify_ready ( self , creating = False ) : if len ( self . _value_ranges ) == 0 : self . _logger . log ( 'crit' , 'Attribute value_ranges must have at least one value' ) raise RuntimeWarning ( 'Attribute value_ranges must have at least one value' ) if len ( self . _employers ) == 0 and creating is False : self . ... | Some cleanup ensures that everything is set up properly to avoid random errors during execution |
238,879 | def import_settings ( self , filename ) : if not os . path . isfile ( filename ) : self . _logger . log ( 'error' , 'File: {} not found, continuing with default settings' . format ( filename ) ) else : with open ( filename , 'r' ) as jsonFile : data = json . load ( jsonFile ) self . _value_ranges = data [ 'valueRanges'... | Import settings from a JSON file |
238,880 | def save_settings ( self , filename ) : data = dict ( ) data [ 'valueRanges' ] = self . _value_ranges data [ 'best_values' ] = [ str ( value ) for value in self . _best_values ] data [ 'minimize' ] = self . _minimize data [ 'num_employers' ] = self . _num_employers data [ 'best_score' ] = str ( self . _best_score ) dat... | Save settings to a JSON file |
238,881 | def get_score ( self , error = None ) : if error is not None : self . error = error if self . error >= 0 : return 1 / ( self . error + 1 ) else : return 1 + abs ( self . error ) | Calculate bee s fitness score given a value returned by the fitness function |
238,882 | def create_elb_dns ( self , regionspecific = False ) : if regionspecific : dns_elb = self . generated . dns ( ) [ 'elb_region' ] else : dns_elb = self . generated . dns ( ) [ 'elb' ] dns_elb_aws = find_elb ( name = self . app_name , env = self . env , region = self . region ) zone_ids = get_dns_zone_ids ( env = self . ... | Create dns entries in route53 . |
238,883 | def create_failover_dns ( self , primary_region = 'us-east-1' ) : dns_record = self . generated . dns ( ) [ 'global' ] zone_ids = get_dns_zone_ids ( env = self . env , facing = self . elb_subnet ) elb_dns_aws = find_elb ( name = self . app_name , env = self . env , region = self . region ) elb_dns_zone_id = find_elb_dn... | Create dns entries in route53 for multiregion failover setups . |
238,884 | def format_listeners ( elb_settings = None , env = 'dev' , region = 'us-east-1' ) : LOG . debug ( 'ELB settings:\n%s' , elb_settings ) credential = get_env_credential ( env = env ) account = credential [ 'accountId' ] listeners = [ ] if 'ports' in elb_settings : for listener in elb_settings [ 'ports' ] : cert_name = fo... | Format ELB Listeners into standard list . |
238,885 | def format_cert_name ( env = '' , account = '' , region = '' , certificate = None ) : cert_name = None if certificate : if certificate . startswith ( 'arn' ) : LOG . info ( "Full ARN provided...skipping lookup." ) cert_name = certificate else : generated_cert_name = generate_custom_cert_name ( env , region , account , ... | Format the SSL certificate name into ARN for ELB . |
238,886 | def generate_custom_cert_name ( env = '' , region = '' , account = '' , certificate = None ) : cert_name = None template_kwargs = { 'account' : account , 'name' : certificate } try : rendered_template = get_template ( template_file = 'infrastructure/iam/tlscert_naming.json.j2' , ** template_kwargs ) tlscert_dict = json... | Generate a custom TLS Cert name based on a template . |
238,887 | def main ( ) : logging . basicConfig ( format = LOGGING_FORMAT ) log = logging . getLogger ( __name__ ) parser = argparse . ArgumentParser ( ) add_debug ( parser ) add_app ( parser ) add_env ( parser ) add_properties ( parser ) args = parser . parse_args ( ) logging . getLogger ( __package__ . split ( "." ) [ 0 ] ) . s... | Send Slack notification to a configured channel . |
238,888 | def main ( ) : logging . basicConfig ( format = LOGGING_FORMAT ) parser = argparse . ArgumentParser ( description = main . __doc__ ) add_debug ( parser ) add_app ( parser ) args = parser . parse_args ( ) if args . debug == logging . DEBUG : logging . getLogger ( __package__ . split ( '.' ) [ 0 ] ) . setLevel ( args . d... | Attempt to fully destroy AWS Resources for a Spinnaker Application . |
238,889 | def check_provider_healthcheck ( settings , default_provider = 'Discovery' ) : ProviderHealthCheck = collections . namedtuple ( 'ProviderHealthCheck' , [ 'providers' , 'has_healthcheck' ] ) eureka_enabled = settings [ 'app' ] [ 'eureka_enabled' ] providers = settings [ 'asg' ] [ 'provider_healthcheck' ] LOG . debug ( '... | Set Provider Health Check when specified . |
238,890 | def get_template_name ( env , pipeline_type ) : pipeline_base = 'pipeline/pipeline' template_name_format = '{pipeline_base}' if env . startswith ( 'prod' ) : template_name_format = template_name_format + '_{env}' else : template_name_format = template_name_format + '_stages' if pipeline_type != 'ec2' : template_name_fo... | Generates the correct template name based on pipeline type |
238,891 | def ec2_pipeline_setup ( generated = None , project = '' , settings = None , env = '' , pipeline_type = '' , region = '' , region_subnets = None , ) : data = copy . deepcopy ( settings ) user_data = generate_encoded_user_data ( env = env , region = region , generated = generated , group_name = project , pipeline_type =... | Handles ec2 pipeline data setup |
238,892 | def create_pipeline ( self ) : pipelines = self . settings [ 'pipeline' ] [ 'pipeline_files' ] self . log . info ( 'Uploading manual Pipelines: %s' , pipelines ) lookup = FileLookup ( git_short = self . generated . gitlab ( ) [ 'main' ] , runway_dir = self . runway_dir ) for json_file in pipelines : json_dict = lookup ... | Use JSON files to create Pipelines . |
238,893 | def main ( ) : logging . basicConfig ( format = LOGGING_FORMAT ) log = logging . getLogger ( __name__ ) parser = argparse . ArgumentParser ( ) add_debug ( parser ) add_app ( parser ) add_properties ( parser ) parser . add_argument ( '-b' , '--base' , help = 'Base AMI name to use, e.g. fedora, tomcat' ) parser . add_arg... | Creates a pipeline in Spinnaker |
238,894 | def convert_ini ( config_dict ) : config_lines = [ ] for env , configs in sorted ( config_dict . items ( ) ) : for resource , app_properties in sorted ( configs . items ( ) ) : try : for app_property , value in sorted ( app_properties . items ( ) ) : variable = '{env}_{resource}_{app_property}' . format ( env = env , r... | Convert _config_dict_ into a list of INI formatted strings . |
238,895 | def write_variables ( app_configs = None , out_file = '' , git_short = '' ) : generated = gogoutils . Generator ( * gogoutils . Parser ( git_short ) . parse_url ( ) , formats = APP_FORMATS ) json_configs = { } for env , configs in app_configs . items ( ) : if env != 'pipeline' : instance_profile = generated . iam ( ) [... | Append _application . json_ configs to _out_file_ . exports and . json . |
238,896 | def get_sns_subscriptions ( app_name , env , region ) : session = boto3 . Session ( profile_name = env , region_name = region ) sns_client = session . client ( 'sns' ) lambda_alias_arn = get_lambda_alias_arn ( app = app_name , account = env , region = region ) lambda_subscriptions = [ ] subscriptions = sns_client . lis... | List SNS lambda subscriptions . |
238,897 | def destroy_cloudwatch_log_event ( app = '' , env = 'dev' , region = '' ) : session = boto3 . Session ( profile_name = env , region_name = region ) cloudwatch_client = session . client ( 'logs' ) cloudwatch_client . delete_subscription_filter ( logGroupName = '/aws/lambda/awslimitchecker' , filterName = app ) return Tr... | Destroy Cloudwatch log event . |
238,898 | def get_accounts ( self , provider = 'aws' ) : url = '{gate}/credentials' . format ( gate = API_URL ) response = requests . get ( url , verify = GATE_CA_BUNDLE , cert = GATE_CLIENT_CERT ) assert response . ok , 'Failed to get accounts: {0}' . format ( response . text ) all_accounts = response . json ( ) self . log . de... | Get Accounts added to Spinnaker . |
238,899 | def create_app ( self ) : self . appinfo [ 'accounts' ] = self . get_accounts ( ) self . log . debug ( 'Pipeline Config\n%s' , pformat ( self . pipeline_config ) ) self . log . debug ( 'App info:\n%s' , pformat ( self . appinfo ) ) jsondata = self . retrieve_template ( ) wait_for_task ( jsondata ) self . log . info ( "... | Send a POST to spinnaker to create a new application with class variables . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.