query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Accepts the current edit for this label .
def acceptEdit ( self ) : if not self . _lineEdit : return self . setText ( self . _lineEdit . text ( ) ) self . _lineEdit . hide ( ) if not self . signalsBlocked ( ) : self . editingFinished . emit ( self . _lineEdit . text ( ) )
11,400
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlabel.py#L32-L43
[ "def", "_generate_noise_temporal", "(", "stimfunction_tr", ",", "tr_duration", ",", "dimensions", ",", "template", ",", "mask", ",", "noise_dict", ")", ":", "# Set up common parameters", "# How many TRs are there", "trs", "=", "len", "(", "stimfunction_tr", ")", "# What time points are sampled by a TR?", "timepoints", "=", "list", "(", "np", ".", "linspace", "(", "0", ",", "(", "trs", "-", "1", ")", "*", "tr_duration", ",", "trs", ")", ")", "# Preset the volume", "noise_volume", "=", "np", ".", "zeros", "(", "(", "dimensions", "[", "0", "]", ",", "dimensions", "[", "1", "]", ",", "dimensions", "[", "2", "]", ",", "trs", ")", ")", "# Generate the drift noise", "if", "noise_dict", "[", "'drift_sigma'", "]", "!=", "0", ":", "# Calculate the drift time course", "noise", "=", "_generate_noise_temporal_drift", "(", "trs", ",", "tr_duration", ",", ")", "# Create a volume with the drift properties", "volume", "=", "np", ".", "ones", "(", "dimensions", ")", "# Combine the volume and noise", "noise_volume", "+=", "np", ".", "multiply", ".", "outer", "(", "volume", ",", "noise", ")", "*", "noise_dict", "[", "'drift_sigma'", "]", "# Generate the physiological noise", "if", "noise_dict", "[", "'physiological_sigma'", "]", "!=", "0", ":", "# Calculate the physiological time course", "noise", "=", "_generate_noise_temporal_phys", "(", "timepoints", ",", ")", "# Create a brain shaped volume with similar smoothing properties", "volume", "=", "_generate_noise_spatial", "(", "dimensions", "=", "dimensions", ",", "mask", "=", "mask", ",", "fwhm", "=", "noise_dict", "[", "'fwhm'", "]", ",", ")", "# Combine the volume and noise", "noise_volume", "+=", "np", ".", "multiply", ".", "outer", "(", "volume", ",", "noise", ")", "*", "noise_dict", "[", "'physiological_sigma'", "]", "# Generate the AR noise", "if", "noise_dict", "[", "'auto_reg_sigma'", "]", "!=", "0", ":", "# Calculate the AR time course volume", "noise", "=", "_generate_noise_temporal_autoregression", "(", "timepoints", ",", "noise_dict", ",", "dimensions", ",", "mask", ",", ")", "# Combine the volume and noise", "noise_volume", "+=", "noise", "*", "noise_dict", "[", "'auto_reg_sigma'", "]", "# Generate the task related noise", "if", "noise_dict", "[", "'task_sigma'", "]", "!=", "0", "and", "np", ".", "sum", "(", "stimfunction_tr", ")", ">", "0", ":", "# Calculate the task based noise time course", "noise", "=", "_generate_noise_temporal_task", "(", "stimfunction_tr", ",", ")", "# Create a brain shaped volume with similar smoothing properties", "volume", "=", "_generate_noise_spatial", "(", "dimensions", "=", "dimensions", ",", "mask", "=", "mask", ",", "fwhm", "=", "noise_dict", "[", "'fwhm'", "]", ",", ")", "# Combine the volume and noise", "noise_volume", "+=", "np", ".", "multiply", ".", "outer", "(", "volume", ",", "noise", ")", "*", "noise_dict", "[", "'task_sigma'", "]", "# Finally, z score each voxel so things mix nicely", "noise_volume", "=", "stats", ".", "zscore", "(", "noise_volume", ",", "3", ")", "# If it is a nan it is because you just divided by zero (since some", "# voxels are zeros in the template)", "noise_volume", "[", "np", ".", "isnan", "(", "noise_volume", ")", "]", "=", "0", "return", "noise_volume" ]
Begins editing for the label .
def beginEdit ( self ) : if not self . _lineEdit : return self . aboutToEdit . emit ( ) self . _lineEdit . setText ( self . editText ( ) ) self . _lineEdit . show ( ) self . _lineEdit . selectAll ( ) self . _lineEdit . setFocus ( )
11,401
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlabel.py#L45-L57
[ "def", "sample", "(", "program", ":", "Union", "[", "circuits", ".", "Circuit", ",", "schedules", ".", "Schedule", "]", ",", "*", ",", "noise", ":", "devices", ".", "NoiseModel", "=", "devices", ".", "NO_NOISE", ",", "param_resolver", ":", "Optional", "[", "study", ".", "ParamResolver", "]", "=", "None", ",", "repetitions", ":", "int", "=", "1", ",", "dtype", ":", "Type", "[", "np", ".", "number", "]", "=", "np", ".", "complex64", ")", "->", "study", ".", "TrialResult", ":", "# State vector simulation is much faster, but only works if no randomness.", "if", "noise", "==", "devices", ".", "NO_NOISE", "and", "protocols", ".", "has_unitary", "(", "program", ")", ":", "return", "sparse_simulator", ".", "Simulator", "(", "dtype", "=", "dtype", ")", ".", "run", "(", "program", "=", "program", ",", "param_resolver", "=", "param_resolver", ",", "repetitions", "=", "repetitions", ")", "return", "density_matrix_simulator", ".", "DensityMatrixSimulator", "(", "dtype", "=", "dtype", ",", "noise", "=", "noise", ")", ".", "run", "(", "program", "=", "program", ",", "param_resolver", "=", "param_resolver", ",", "repetitions", "=", "repetitions", ")" ]
Cancels the edit for this label .
def rejectEdit ( self ) : if self . _lineEdit : self . _lineEdit . hide ( ) self . editingCancelled . emit ( )
11,402
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlabel.py#L122-L128
[ "def", "sample", "(", "program", ":", "Union", "[", "circuits", ".", "Circuit", ",", "schedules", ".", "Schedule", "]", ",", "*", ",", "noise", ":", "devices", ".", "NoiseModel", "=", "devices", ".", "NO_NOISE", ",", "param_resolver", ":", "Optional", "[", "study", ".", "ParamResolver", "]", "=", "None", ",", "repetitions", ":", "int", "=", "1", ",", "dtype", ":", "Type", "[", "np", ".", "number", "]", "=", "np", ".", "complex64", ")", "->", "study", ".", "TrialResult", ":", "# State vector simulation is much faster, but only works if no randomness.", "if", "noise", "==", "devices", ".", "NO_NOISE", "and", "protocols", ".", "has_unitary", "(", "program", ")", ":", "return", "sparse_simulator", ".", "Simulator", "(", "dtype", "=", "dtype", ")", ".", "run", "(", "program", "=", "program", ",", "param_resolver", "=", "param_resolver", ",", "repetitions", "=", "repetitions", ")", "return", "density_matrix_simulator", ".", "DensityMatrixSimulator", "(", "dtype", "=", "dtype", ",", "noise", "=", "noise", ")", ".", "run", "(", "program", "=", "program", ",", "param_resolver", "=", "param_resolver", ",", "repetitions", "=", "repetitions", ")" ]
Returns an escape for a terminal text formatting type or a list of types .
def typeseq ( types ) : ret = "" for t in types : ret += termcap . get ( fmttypes [ t ] ) return ret
11,403
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L117-L131
[ "def", "dispersion_ranking_NN", "(", "self", ",", "nnm", ",", "num_norm_avg", "=", "50", ")", ":", "self", ".", "knn_avg", "(", "nnm", ")", "D_avg", "=", "self", ".", "adata", ".", "layers", "[", "'X_knn_avg'", "]", "mu", ",", "var", "=", "sf", ".", "mean_variance_axis", "(", "D_avg", ",", "axis", "=", "0", ")", "dispersions", "=", "np", ".", "zeros", "(", "var", ".", "size", ")", "dispersions", "[", "mu", ">", "0", "]", "=", "var", "[", "mu", ">", "0", "]", "/", "mu", "[", "mu", ">", "0", "]", "self", ".", "adata", ".", "var", "[", "'spatial_dispersions'", "]", "=", "dispersions", ".", "copy", "(", ")", "ma", "=", "np", ".", "sort", "(", "dispersions", ")", "[", "-", "num_norm_avg", ":", "]", ".", "mean", "(", ")", "dispersions", "[", "dispersions", ">=", "ma", "]", "=", "ma", "weights", "=", "(", "(", "dispersions", "/", "dispersions", ".", "max", "(", ")", ")", "**", "0.5", ")", ".", "flatten", "(", ")", "self", ".", "adata", ".", "var", "[", "'weights'", "]", "=", "weights", "return", "weights" ]
Returns a color code number given the color name .
def nametonum ( name ) : code = colorcodes . get ( name ) if code is None : raise ValueError ( "%s is not a valid color name." % name ) else : return code
11,404
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L133-L141
[ "def", "StartGuiSession", "(", "self", ")", ":", "from", "UcsBase", "import", "WriteUcsWarning", ",", "UcsUtils", ",", "UcsValidationException", "import", "urllib", ",", "tempfile", ",", "fileinput", ",", "os", ",", "subprocess", ",", "platform", "osSupport", "=", "[", "\"Windows\"", ",", "\"Linux\"", ",", "\"Microsoft\"", "]", "if", "platform", ".", "system", "(", ")", "not", "in", "osSupport", ":", "raise", "UcsValidationException", "(", "\"Currently works with Windows OS and Ubuntu\"", ")", "# raise Exception(\"Currently works with Windows OS and Ubuntu\")", "try", ":", "javawsPath", "=", "UcsUtils", ".", "GetJavaInstallationPath", "(", ")", "# print r\"%s\" %(javawsPath)", "if", "javawsPath", "!=", "None", ":", "url", "=", "\"%s/ucsm/ucsm.jnlp\"", "%", "(", "self", ".", "Uri", "(", ")", ")", "source", "=", "urllib", ".", "urlopen", "(", "url", ")", ".", "read", "(", ")", "jnlpdir", "=", "tempfile", ".", "gettempdir", "(", ")", "jnlpfile", "=", "os", ".", "path", ".", "join", "(", "jnlpdir", ",", "\"temp.jnlp\"", ")", "if", "os", ".", "path", ".", "exists", "(", "jnlpfile", ")", ":", "os", ".", "remove", "(", "jnlpfile", ")", "jnlpFH", "=", "open", "(", "jnlpfile", ",", "\"w+\"", ")", "jnlpFH", ".", "write", "(", "source", ")", "jnlpFH", ".", "close", "(", ")", "for", "line", "in", "fileinput", ".", "input", "(", "jnlpfile", ",", "inplace", "=", "1", ")", ":", "if", "re", ".", "search", "(", "r'^\\s*</resources>\\s*$'", ",", "line", ")", ":", "print", "'\\t<property name=\"log.show.encrypted\" value=\"true\"/>'", "print", "line", ",", "subprocess", ".", "call", "(", "[", "javawsPath", ",", "jnlpfile", "]", ")", "if", "os", ".", "path", ".", "exists", "(", "jnlpfile", ")", ":", "os", ".", "remove", "(", "jnlpfile", ")", "else", ":", "return", "None", "except", "Exception", ",", "err", ":", "fileinput", ".", "close", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "jnlpfile", ")", ":", "os", ".", "remove", "(", "jnlpfile", ")", "raise" ]
Returns the forground color terminal escape sequence for the given color code number or color name .
def fgseq ( code ) : if isinstance ( code , str ) : code = nametonum ( code ) if code == - 1 : return "" s = termcap . get ( 'setaf' , code ) or termcap . get ( 'setf' , code ) return s
11,405
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L143-L154
[ "def", "checkIsConsistent", "(", "self", ")", ":", "if", "is_an_array", "(", "self", ".", "mask", ")", "and", "self", ".", "mask", ".", "shape", "!=", "self", ".", "data", ".", "shape", ":", "raise", "ConsistencyError", "(", "\"Shape mismatch mask={}, data={}\"", ".", "format", "(", "self", ".", "mask", ".", "shape", "!=", "self", ".", "data", ".", "shape", ")", ")" ]
Returns the background color terminal escape sequence for the given color code number .
def bgseq ( code ) : if isinstance ( code , str ) : code = nametonum ( code ) if code == - 1 : return "" s = termcap . get ( 'setab' , code ) or termcap . get ( 'setb' , code ) return s
11,406
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L156-L167
[ "def", "checkIsConsistent", "(", "self", ")", ":", "if", "is_an_array", "(", "self", ".", "mask", ")", "and", "self", ".", "mask", ".", "shape", "!=", "self", ".", "data", ".", "shape", ":", "raise", "ConsistencyError", "(", "\"Shape mismatch mask={}, data={}\"", ".", "format", "(", "self", ".", "mask", ".", "shape", "!=", "self", ".", "data", ".", "shape", ")", ")" ]
Creates a text styling from a descriptor
def parse ( self , descriptor ) : fg = descriptor . get ( 'fg' ) bg = descriptor . get ( 'bg' ) types = descriptor . get ( 'fmt' ) ret = "" if fg : ret += fgseq ( fg ) if bg : ret += bgseq ( bg ) if types : t = typeseq ( types ) if t : ret += t # wew, strings and bytes, what's a guy to do! reset = resetseq ( ) if not isinstance ( reset , six . text_type ) : reset = reset . decode ( 'utf-8' ) def ret_func ( msg ) : if not isinstance ( msg , six . text_type ) : msg = msg . decode ( 'utf-8' ) return ret + msg + reset self . decorator = ret_func
11,407
https://github.com/Gbps/fastlog/blob/8edb2327d72191510302c4654ffaa1691fe31277/fastlog/term.py#L78-L113
[ "def", "_check_missing_manifests", "(", "self", ",", "segids", ")", ":", "manifest_paths", "=", "[", "self", ".", "_manifest_path", "(", "segid", ")", "for", "segid", "in", "segids", "]", "with", "Storage", "(", "self", ".", "vol", ".", "layer_cloudpath", ",", "progress", "=", "self", ".", "vol", ".", "progress", ")", "as", "stor", ":", "exists", "=", "stor", ".", "files_exist", "(", "manifest_paths", ")", "dne", "=", "[", "]", "for", "path", ",", "there", "in", "exists", ".", "items", "(", ")", ":", "if", "not", "there", ":", "(", "segid", ",", ")", "=", "re", ".", "search", "(", "r'(\\d+):0$'", ",", "path", ")", ".", "groups", "(", ")", "dne", ".", "append", "(", "segid", ")", "return", "dne" ]
Saves the data to the profile before closing .
def accept ( self ) : if ( not self . uiNameTXT . text ( ) ) : QMessageBox . information ( self , 'Invalid Name' , 'You need to supply a name for your layout.' ) return prof = self . profile ( ) if ( not prof ) : prof = XViewProfile ( ) prof . setName ( nativestring ( self . uiNameTXT . text ( ) ) ) prof . setVersion ( self . uiVersionSPN . value ( ) ) prof . setDescription ( nativestring ( self . uiDescriptionTXT . toPlainText ( ) ) ) prof . setIcon ( self . uiIconBTN . filepath ( ) ) super ( XViewProfileDialog , self ) . accept ( )
11,408
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofiledialog.py#L35-L54
[ "def", "_solver", "(", "self", ")", ":", "if", "self", ".", "_stored_solver", "is", "not", "None", ":", "return", "self", ".", "_stored_solver", "track", "=", "o", ".", "CONSTRAINT_TRACKING_IN_SOLVER", "in", "self", ".", "state", ".", "options", "approximate_first", "=", "o", ".", "APPROXIMATE_FIRST", "in", "self", ".", "state", ".", "options", "if", "o", ".", "STRINGS_ANALYSIS", "in", "self", ".", "state", ".", "options", ":", "if", "'smtlib_cvc4'", "in", "backend_manager", ".", "backends", ".", "_backends_by_name", ":", "our_backend", "=", "backend_manager", ".", "backends", ".", "smtlib_cvc4", "elif", "'smtlib_z3'", "in", "backend_manager", ".", "backends", ".", "_backends_by_name", ":", "our_backend", "=", "backend_manager", ".", "backends", ".", "smtlib_z3", "elif", "'smtlib_abc'", "in", "backend_manager", ".", "backends", ".", "_backends_by_name", ":", "our_backend", "=", "backend_manager", ".", "backends", ".", "smtlib_abc", "else", ":", "raise", "ValueError", "(", "\"Could not find suitable string solver!\"", ")", "if", "o", ".", "COMPOSITE_SOLVER", "in", "self", ".", "state", ".", "options", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "SolverComposite", "(", "template_solver_string", "=", "claripy", ".", "SolverCompositeChild", "(", "backend", "=", "our_backend", ",", "track", "=", "track", ")", ")", "elif", "o", ".", "ABSTRACT_SOLVER", "in", "self", ".", "state", ".", "options", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "SolverVSA", "(", ")", "elif", "o", ".", "SYMBOLIC", "in", "self", ".", "state", ".", "options", "and", "o", ".", "REPLACEMENT_SOLVER", "in", "self", ".", "state", ".", "options", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "SolverReplacement", "(", "auto_replace", "=", "False", ")", "elif", "o", ".", "SYMBOLIC", "in", "self", ".", "state", ".", "options", "and", "o", ".", "CACHELESS_SOLVER", "in", "self", ".", "state", ".", "options", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "SolverCacheless", "(", "track", "=", "track", ")", "elif", "o", ".", "SYMBOLIC", "in", "self", ".", "state", ".", "options", "and", "o", ".", "COMPOSITE_SOLVER", "in", "self", ".", "state", ".", "options", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "SolverComposite", "(", "track", "=", "track", ")", "elif", "o", ".", "SYMBOLIC", "in", "self", ".", "state", ".", "options", "and", "any", "(", "opt", "in", "self", ".", "state", ".", "options", "for", "opt", "in", "o", ".", "approximation", ")", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "SolverHybrid", "(", "track", "=", "track", ",", "approximate_first", "=", "approximate_first", ")", "elif", "o", ".", "HYBRID_SOLVER", "in", "self", ".", "state", ".", "options", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "SolverHybrid", "(", "track", "=", "track", ",", "approximate_first", "=", "approximate_first", ")", "elif", "o", ".", "SYMBOLIC", "in", "self", ".", "state", ".", "options", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "Solver", "(", "track", "=", "track", ")", "else", ":", "self", ".", "_stored_solver", "=", "claripy", ".", "SolverConcrete", "(", ")", "return", "self", ".", "_stored_solver" ]
Brings up a web browser with the address in a Google map .
def browseMaps ( self ) : url = self . urlTemplate ( ) params = urllib . urlencode ( { self . urlQueryKey ( ) : self . location ( ) } ) url = url % { 'params' : params } webbrowser . open ( url )
11,409
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xlocationwidget.py#L79-L87
[ "def", "get_correlation_table", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ",", "caption", "=", "\"Parameter Correlations\"", ",", "label", "=", "\"tab:parameter_correlations\"", ")", ":", "parameters", ",", "cor", "=", "self", ".", "get_correlations", "(", "chain", "=", "chain", ",", "parameters", "=", "parameters", ")", "return", "self", ".", "_get_2d_latex_table", "(", "parameters", ",", "cor", ",", "caption", ",", "label", ")" ]
Initializes chrome in headless mode
def _initialize_chrome_driver ( self ) : try : print ( colored ( '\nInitializing Headless Chrome...\n' , 'yellow' ) ) self . _initialize_chrome_options ( ) self . _chromeDriver = webdriver . Chrome ( chrome_options = self . _chromeOptions ) self . _chromeDriver . maximize_window ( ) print ( colored ( '\nHeadless Chrome Initialized.' , 'green' ) ) except Exception as exception : print ( colored ( 'Error - Driver Initialization: ' + format ( exception ) ) , 'red' )
11,410
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L72-L86
[ "def", "find", "(", "self", ",", "path", ")", ":", "p", "=", "[", "re", ".", "sub", "(", "'[\\[\\]]'", ",", "''", ",", "w", ")", "for", "w", "in", "PyVDF", ".", "__RE_Path_Seperator", ".", "findall", "(", "path", ")", "]", "array", "=", "self", ".", "getData", "(", ")", "for", "c", "in", "p", ":", "try", ":", "array", "=", "array", "[", "c", "]", "except", "KeyError", ":", "return", "''", "return", "array" ]
Searches across Google Image Search with the specified image query and downloads the specified count of images
def extract_images ( self , imageQuery , imageCount = 100 , destinationFolder = './' , threadCount = 4 ) : # Initialize the chrome driver self . _initialize_chrome_driver ( ) # Initialize the image download parameters self . _imageQuery = imageQuery self . _imageCount = imageCount self . _destinationFolder = destinationFolder self . _threadCount = threadCount self . _get_image_urls ( ) self . _create_storage_folder ( ) self . _download_images ( ) # Print the final message specifying the total count of images downloaded print ( colored ( '\n\nImages Downloaded: ' + str ( self . _imageCounter ) + ' of ' + str ( self . _imageCount ) + ' in ' + format_timespan ( self . _downloadProgressBar . data ( ) [ 'total_seconds_elapsed' ] ) + '\n' , 'green' ) ) # Terminate the chrome instance self . _chromeDriver . close ( ) self . _reset_helper_variables ( )
11,411
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L129-L164
[ "def", "pad", "(", "self", ",", "pad_length", ")", ":", "self", ".", "pianoroll", "=", "np", ".", "pad", "(", "self", ".", "pianoroll", ",", "(", "(", "0", ",", "pad_length", ")", ",", "(", "0", ",", "0", ")", ")", ",", "'constant'", ")" ]
Retrieves the image URLS corresponding to the image query
def _get_image_urls ( self ) : print ( colored ( '\nRetrieving Image URLs...' , 'yellow' ) ) _imageQuery = self . _imageQuery . replace ( ' ' , '+' ) self . _chromeDriver . get ( 'https://www.google.co.in/search?q=' + _imageQuery + '&newwindow=1&source=lnms&tbm=isch' ) while self . _imageURLsExtractedCount <= self . _imageCount : self . _extract_image_urls ( ) self . _page_scroll_down ( ) # Slice the list of image URLs to contain the exact number of image # URLs that have been requested # self._imageURLs = self._imageURLs[:self._imageCount] print ( colored ( 'Image URLs retrieved.' , 'green' ) )
11,412
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L177-L195
[ "def", "getWorkersName", "(", "data", ")", ":", "names", "=", "[", "fichier", "for", "fichier", "in", "data", ".", "keys", "(", ")", "]", "names", ".", "sort", "(", ")", "try", ":", "names", ".", "remove", "(", "\"broker\"", ")", "except", "ValueError", ":", "pass", "return", "names" ]
Retrieves image URLs from the current page
def _extract_image_urls ( self ) : resultsPage = self . _chromeDriver . page_source resultsPageSoup = BeautifulSoup ( resultsPage , 'html.parser' ) images = resultsPageSoup . find_all ( 'div' , class_ = 'rg_meta' ) images = [ json . loads ( image . contents [ 0 ] ) for image in images ] [ self . _imageURLs . append ( image [ 'ou' ] ) for image in images ] self . _imageURLsExtractedCount += len ( images )
11,413
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L197-L208
[ "def", "_ion_equals", "(", "a", ",", "b", ",", "timestamp_comparison_func", ",", "recursive_comparison_func", ")", ":", "for", "a", ",", "b", "in", "(", "(", "a", ",", "b", ")", ",", "(", "b", ",", "a", ")", ")", ":", "# Ensures that operand order does not matter.", "if", "isinstance", "(", "a", ",", "_IonNature", ")", ":", "if", "isinstance", "(", "b", ",", "_IonNature", ")", ":", "# Both operands have _IonNature. Their IonTypes and annotations must be equivalent.", "eq", "=", "a", ".", "ion_type", "is", "b", ".", "ion_type", "and", "_annotations_eq", "(", "a", ",", "b", ")", "else", ":", "# Only one operand has _IonNature. It cannot be equivalent to the other operand if it has annotations.", "eq", "=", "not", "a", ".", "ion_annotations", "if", "eq", ":", "if", "isinstance", "(", "a", ",", "IonPyList", ")", ":", "return", "_sequences_eq", "(", "a", ",", "b", ",", "recursive_comparison_func", ")", "elif", "isinstance", "(", "a", ",", "IonPyDict", ")", ":", "return", "_structs_eq", "(", "a", ",", "b", ",", "recursive_comparison_func", ")", "elif", "isinstance", "(", "a", ",", "IonPyTimestamp", ")", ":", "return", "timestamp_comparison_func", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "IonPyNull", ")", ":", "return", "isinstance", "(", "b", ",", "IonPyNull", ")", "or", "(", "b", "is", "None", "and", "a", ".", "ion_type", "is", "IonType", ".", "NULL", ")", "elif", "isinstance", "(", "a", ",", "IonPySymbol", ")", "or", "(", "isinstance", "(", "a", ",", "IonPyText", ")", "and", "a", ".", "ion_type", "is", "IonType", ".", "SYMBOL", ")", ":", "return", "_symbols_eq", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "IonPyDecimal", ")", ":", "return", "_decimals_eq", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "IonPyFloat", ")", ":", "return", "_floats_eq", "(", "a", ",", "b", ")", "else", ":", "return", "a", "==", "b", "return", "False", "# Reaching this point means that neither operand has _IonNature.", "for", "a", ",", "b", "in", "(", "(", "a", ",", "b", ")", ",", "(", "b", ",", "a", ")", ")", ":", "# Ensures that operand order does not matter.", "if", "isinstance", "(", "a", ",", "list", ")", ":", "return", "_sequences_eq", "(", "a", ",", "b", ",", "recursive_comparison_func", ")", "elif", "isinstance", "(", "a", ",", "dict", ")", ":", "return", "_structs_eq", "(", "a", ",", "b", ",", "recursive_comparison_func", ")", "elif", "isinstance", "(", "a", ",", "datetime", ")", ":", "return", "timestamp_comparison_func", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "SymbolToken", ")", ":", "return", "_symbols_eq", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "Decimal", ")", ":", "return", "_decimals_eq", "(", "a", ",", "b", ")", "elif", "isinstance", "(", "a", ",", "float", ")", ":", "return", "_floats_eq", "(", "a", ",", "b", ")", "return", "a", "==", "b" ]
Scrolls down to get the next set of images
def _page_scroll_down ( self ) : # Scroll down to request the next set of images self . _chromeDriver . execute_script ( 'window.scroll(0, document.body.clientHeight)' ) # Wait for the images to load completely time . sleep ( self . WAIT_TIME ) # Check if the button - 'Show More Results' is visible # If yes, click it and request more messages # This step helps is avoiding duplicate image URLS from being captured try : self . _chromeDriver . find_element_by_id ( 'smb' ) . click ( ) except ElementNotVisibleException as error : pass
11,414
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L210-L226
[ "def", "write_csv", "(", "self", ",", "path", "=", "None", ")", ":", "# Sort the Sections", "self", ".", "sort_sections", "(", "[", "'Root'", ",", "'Contacts'", ",", "'Documentation'", ",", "'References'", ",", "'Resources'", ",", "'Citations'", ",", "'Schema'", "]", ")", "# Sort Terms in the root section", "# Re-wrap the description and abstract", "if", "self", ".", "description", ":", "self", ".", "description", "=", "self", ".", "description", "if", "self", ".", "abstract", ":", "self", ".", "description", "=", "self", ".", "abstract", "t", "=", "self", "[", "'Root'", "]", ".", "get_or_new_term", "(", "'Root.Modified'", ")", "t", ".", "value", "=", "datetime_now", "(", ")", "self", ".", "sort_by_term", "(", ")", "return", "super", "(", ")", ".", "write_csv", "(", "str", "(", "path", ")", ")" ]
Downloads the images from the retrieved image URLs and stores in the specified destination folder . Multiprocessing is being used to minimize the download time
def _download_images ( self ) : print ( '\nDownloading Images for the Query: ' + self . _imageQuery ) try : self . _initialize_progress_bar ( ) # Initialize and assign work to the threads in the threadpool threadPool = Pool ( self . _threadCount ) threadPool . map ( self . _download_image , self . _imageURLs ) threadPool . close ( ) threadPool . join ( ) # Download each image individually # [self._download_image(imageURL) for imageURL in self._imageURLs] self . _downloadProgressBar . finish ( ) except Exception as exception : print ( 'Error - Image Download: ' + format ( exception ) )
11,415
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L228-L253
[ "def", "same_types", "(", "self", ",", "index1", ",", "index2", ")", ":", "try", ":", "same", "=", "self", ".", "table", "[", "index1", "]", ".", "type", "==", "self", ".", "table", "[", "index2", "]", ".", "type", "!=", "SharedData", ".", "TYPES", ".", "NO_TYPE", "except", "Exception", ":", "self", ".", "error", "(", ")", "return", "same" ]
Initializes the progress bar
def _initialize_progress_bar ( self ) : widgets = [ 'Download: ' , Percentage ( ) , ' ' , Bar ( ) , ' ' , AdaptiveETA ( ) , ' ' , FileTransferSpeed ( ) ] self . _downloadProgressBar = ProgressBar ( widgets = widgets , max_value = self . _imageCount ) . start ( )
11,416
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L255-L262
[ "def", "get_model_indexes", "(", "model", ",", "add_reserver_flag", "=", "True", ")", ":", "import", "uliweb", ".", "orm", "as", "orm", "from", "sqlalchemy", ".", "engine", ".", "reflection", "import", "Inspector", "indexes", "=", "[", "]", "engine", "=", "model", ".", "get_engine", "(", ")", ".", "engine", "insp", "=", "Inspector", ".", "from_engine", "(", "engine", ")", "for", "index", "in", "insp", ".", "get_indexes", "(", "model", ".", "tablename", ")", ":", "d", "=", "{", "}", "d", "[", "'name'", "]", "=", "index", "[", "'name'", "]", "d", "[", "'unique'", "]", "=", "index", "[", "'unique'", "]", "d", "[", "'fields'", "]", "=", "index", "[", "'column_names'", "]", "if", "add_reserver_flag", ":", "d", "[", "'_reserved'", "]", "=", "True", "indexes", ".", "append", "(", "d", ")", "return", "indexes" ]
Downloads an image file from the given image URL
def _download_image ( self , imageURL ) : # If the required count of images have been download, # refrain from downloading the remainder of the images if ( self . _imageCounter >= self . _imageCount ) : return try : imageResponse = requests . get ( imageURL ) # Generate image file name as <_imageQuery>_<_imageCounter>.<extension> imageType , imageEncoding = mimetypes . guess_type ( imageURL ) if imageType is not None : imageExtension = mimetypes . guess_extension ( imageType ) else : imageExtension = mimetypes . guess_extension ( imageResponse . headers [ 'Content-Type' ] ) imageFileName = self . _imageQuery . replace ( ' ' , '_' ) + '_' + str ( self . _imageCounter ) + imageExtension imageFileName = os . path . join ( self . _storageFolder , imageFileName ) image = Image . open ( BytesIO ( imageResponse . content ) ) image . save ( imageFileName ) self . _imageCounter += 1 self . _downloadProgressBar . update ( self . _imageCounter ) except Exception as exception : pass
11,417
https://github.com/Stryker0301/google-image-extractor/blob/bd227f3f77cc82603b9ad7798c9af9fed6724a05/giextractor.py#L264-L301
[ "def", "app_start_up_time", "(", "self", ",", "package", ":", "str", ")", "->", "str", ":", "output", ",", "_", "=", "self", ".", "_execute", "(", "'-s'", ",", "self", ".", "device_sn", ",", "'shell'", ",", "'am'", ",", "'start'", ",", "'-W'", ",", "package", ")", "return", "re", ".", "findall", "(", "'TotalTime: \\d+'", ",", "output", ")", "[", "0", "]" ]
Increments the main progress bar by amount .
def increment ( self , amount = 1 ) : self . _primaryProgressBar . setValue ( self . value ( ) + amount ) QApplication . instance ( ) . processEvents ( )
11,418
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xloaderwidget.py#L195-L200
[ "def", "make_random_models_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "None", ")", ":", "prng", "=", "check_random_state", "(", "random_state", ")", "sources", "=", "Table", "(", ")", "for", "param_name", ",", "(", "lower", ",", "upper", ")", "in", "param_ranges", ".", "items", "(", ")", ":", "# Generate a column for every item in param_ranges, even if it", "# is not in the model (e.g. flux). However, such columns will", "# be ignored when rendering the image.", "sources", "[", "param_name", "]", "=", "prng", ".", "uniform", "(", "lower", ",", "upper", ",", "n_sources", ")", "return", "sources" ]
Increments the sub - progress bar by amount .
def incrementSub ( self , amount = 1 ) : self . _subProgressBar . setValue ( self . subValue ( ) + amount ) QApplication . instance ( ) . processEvents ( )
11,419
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xloaderwidget.py#L202-L207
[ "def", "_send_to_timeseries", "(", "self", ",", "message", ")", ":", "logging", ".", "debug", "(", "\"MESSAGE=\"", "+", "str", "(", "message", ")", ")", "result", "=", "None", "try", ":", "ws", "=", "self", ".", "_get_websocket", "(", ")", "ws", ".", "send", "(", "json", ".", "dumps", "(", "message", ")", ")", "result", "=", "ws", ".", "recv", "(", ")", "except", "(", "websocket", ".", "WebSocketConnectionClosedException", ",", "Exception", ")", "as", "e", ":", "logging", ".", "debug", "(", "\"Connection failed, will try again.\"", ")", "logging", ".", "debug", "(", "e", ")", "ws", "=", "self", ".", "_get_websocket", "(", "reuse", "=", "False", ")", "ws", ".", "send", "(", "json", ".", "dumps", "(", "message", ")", ")", "result", "=", "ws", ".", "recv", "(", ")", "logging", ".", "debug", "(", "\"RESULT=\"", "+", "str", "(", "result", ")", ")", "return", "result" ]
Assigns the renderer for this chart to the current selected renderer .
def assignRenderer ( self , action ) : name = nativestring ( action . text ( ) ) . split ( ' ' ) [ 0 ] self . _renderer = XChartRenderer . plugin ( name ) self . uiTypeBTN . setDefaultAction ( action ) self . recalculate ( )
11,420
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchart.py#L235-L243
[ "def", "get_entity_info", "(", "pdb_id", ")", ":", "out", "=", "get_info", "(", "pdb_id", ",", "url_root", "=", "'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId='", ")", "out", "=", "to_dict", "(", "out", ")", "return", "remove_at_sign", "(", "out", "[", "'entityInfo'", "]", "[", "'PDB'", "]", ")" ]
Recalculates the information for this chart .
def recalculate ( self ) : if not ( self . isVisible ( ) and self . renderer ( ) ) : return # update dynamic range if self . _dataChanged : for axis in self . axes ( ) : if axis . useDynamicRange ( ) : axis . calculateRange ( self . values ( axis . name ( ) ) ) self . _dataChanged = False # recalculate the main grid xaxis = self . horizontalAxis ( ) yaxis = self . verticalAxis ( ) renderer = self . renderer ( ) xvisible = xaxis is not None and self . showXAxis ( ) and renderer . showXAxis ( ) yvisible = yaxis is not None and self . showYAxis ( ) and renderer . showYAxis ( ) self . uiXAxisVIEW . setVisible ( xvisible ) self . uiYAxisVIEW . setVisible ( yvisible ) # calculate the main view view = self . uiChartVIEW chart_scene = view . scene ( ) chart_scene . setSceneRect ( 0 , 0 , view . width ( ) - 2 , view . height ( ) - 2 ) rect = renderer . calculate ( chart_scene , xaxis , yaxis ) # recalculate the xaxis if xaxis and self . showXAxis ( ) and renderer . showXAxis ( ) : view = self . uiXAxisVIEW scene = view . scene ( ) scene . setSceneRect ( 0 , 0 , rect . width ( ) , view . height ( ) ) scene . invalidate ( ) # render the yaxis if yaxis and self . showYAxis ( ) and renderer . showYAxis ( ) : view = self . uiYAxisVIEW scene = view . scene ( ) scene . setSceneRect ( 0 , 0 , view . width ( ) , rect . height ( ) ) scene . invalidate ( ) # recalculate the items renderer . calculateDatasets ( chart_scene , self . axes ( ) , self . datasets ( ) ) chart_scene . invalidate ( )
11,421
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchart.py#L369-L420
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Synchronizes the various scrollbars within this chart .
def syncScrollbars ( self ) : chart_hbar = self . uiChartVIEW . horizontalScrollBar ( ) chart_vbar = self . uiChartVIEW . verticalScrollBar ( ) x_hbar = self . uiXAxisVIEW . horizontalScrollBar ( ) x_vbar = self . uiXAxisVIEW . verticalScrollBar ( ) y_hbar = self . uiYAxisVIEW . horizontalScrollBar ( ) y_vbar = self . uiYAxisVIEW . verticalScrollBar ( ) x_hbar . setRange ( chart_hbar . minimum ( ) , chart_hbar . maximum ( ) ) x_hbar . setValue ( chart_hbar . value ( ) ) x_vbar . setValue ( 0 ) chart_vbar . setRange ( y_vbar . minimum ( ) , y_vbar . maximum ( ) ) chart_vbar . setValue ( y_vbar . value ( ) ) y_hbar . setValue ( 4 )
11,422
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchart/xchart.py#L692-L712
[ "def", "register", "(", "self", ")", ":", "register_url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/register\"", "register_headers", "=", "{", "\"apikey\"", ":", "str", "(", "self", ".", "owner_api_key", ")", ",", "\"resourceID\"", ":", "str", "(", "self", ".", "entity_id", ")", ",", "\"serviceType\"", ":", "\"publish,subscribe,historicData\"", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "get", "(", "register_url", ",", "{", "}", ",", "headers", "=", "register_headers", ")", "response", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "if", "\"APIKey\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "=", "json", ".", "loads", "(", "response", "[", ":", "-", "331", "]", "+", "\"}\"", ")", "# Temporary fix to a middleware bug, should be removed in future", "response", "[", "\"Registration\"", "]", "=", "\"success\"", "else", ":", "response", "=", "json", ".", "loads", "(", "response", ")", "response", "[", "\"Registration\"", "]", "=", "\"failure\"", "return", "response" ]
Deregisters a node service or check
async def deregister ( self , node , * , check = None , service = None , write_token = None ) : entry = { } if isinstance ( node , str ) : entry [ "Node" ] = node else : for k in ( "Datacenter" , "Node" , "CheckID" , "ServiceID" , "WriteRequest" ) : if k in node : entry [ k ] = node [ k ] service_id = extract_attr ( service , keys = [ "ServiceID" , "ID" ] ) check_id = extract_attr ( check , keys = [ "CheckID" , "ID" ] ) if service_id and not check_id : entry [ "ServiceID" ] = service_id elif service_id and check_id : entry [ "CheckID" ] = "%s:%s" % ( service_id , check_id ) elif not service_id and check_id : entry [ "CheckID" ] = check_id if write_token : entry [ "WriteRequest" ] = { "Token" : extract_attr ( write_token , keys = [ "ID" ] ) } response = await self . _api . put ( "/v1/catalog/deregister" , data = entry ) return response . status == 200
11,423
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/catalog_endpoint.py#L193-L266
[ "async", "def", "load_varint", "(", "reader", ")", ":", "buffer", "=", "_UINT_BUFFER", "await", "reader", ".", "areadinto", "(", "buffer", ")", "width", "=", "int_mark_to_size", "(", "buffer", "[", "0", "]", "&", "PortableRawSizeMark", ".", "MASK", ")", "result", "=", "buffer", "[", "0", "]", "shift", "=", "8", "for", "_", "in", "range", "(", "width", "-", "1", ")", ":", "await", "reader", ".", "areadinto", "(", "buffer", ")", "result", "+=", "buffer", "[", "0", "]", "<<", "shift", "shift", "+=", "8", "return", "result", ">>", "2" ]
Lists nodes in a given DC
async def nodes ( self , * , dc = None , near = None , watch = None , consistency = None ) : params = { "dc" : dc , "near" : near } response = await self . _api . get ( "/v1/catalog/nodes" , params = params , watch = watch , consistency = consistency ) return consul ( response )
11,424
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/catalog_endpoint.py#L288-L328
[ "def", "_restart_session", "(", "self", ",", "session", ")", ":", "# remove old session key, if socket is None, that means the", "# session was closed by user and there is no need to restart.", "if", "session", ".", "socket", "is", "not", "None", ":", "self", ".", "log", ".", "info", "(", "\"Attempting restart session for Monitor Id %s.\"", "%", "session", ".", "monitor_id", ")", "del", "self", ".", "sessions", "[", "session", ".", "socket", ".", "fileno", "(", ")", "]", "session", ".", "stop", "(", ")", "session", ".", "start", "(", ")", "self", ".", "sessions", "[", "session", ".", "socket", ".", "fileno", "(", ")", "]", "=", "session" ]
Lists services in a given DC
async def services ( self , * , dc = None , watch = None , consistency = None ) : params = { "dc" : dc } response = await self . _api . get ( "/v1/catalog/services" , params = params , watch = watch , consistency = consistency ) return consul ( response )
11,425
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/catalog_endpoint.py#L330-L360
[ "def", "_restart_session", "(", "self", ",", "session", ")", ":", "# remove old session key, if socket is None, that means the", "# session was closed by user and there is no need to restart.", "if", "session", ".", "socket", "is", "not", "None", ":", "self", ".", "log", ".", "info", "(", "\"Attempting restart session for Monitor Id %s.\"", "%", "session", ".", "monitor_id", ")", "del", "self", ".", "sessions", "[", "session", ".", "socket", ".", "fileno", "(", ")", "]", "session", ".", "stop", "(", ")", "session", ".", "start", "(", ")", "self", ".", "sessions", "[", "session", ".", "socket", ".", "fileno", "(", ")", "]", "=", "session" ]
Prompts the user to create a new profile .
def createProfile ( self , profile = None , clearLayout = True ) : if profile : prof = profile elif not self . viewWidget ( ) or clearLayout : prof = XViewProfile ( ) else : prof = self . viewWidget ( ) . saveProfile ( ) blocked = self . signalsBlocked ( ) self . blockSignals ( False ) changed = self . editProfile ( prof ) self . blockSignals ( blocked ) if not changed : return act = self . addProfile ( prof ) act . setChecked ( True ) # update the interface if self . viewWidget ( ) and ( profile or clearLayout ) : self . viewWidget ( ) . restoreProfile ( prof ) if not self . signalsBlocked ( ) : self . profileCreated . emit ( prof ) self . profilesChanged . emit ( )
11,426
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofiletoolbar.py#L164-L192
[ "def", "delete_attachments", "(", "self", ",", "volumeID", ",", "attachmentsID", ")", ":", "log", ".", "debug", "(", "\"deleting attachments from volume '{}': {}\"", ".", "format", "(", "volumeID", ",", "attachmentsID", ")", ")", "rawVolume", "=", "self", ".", "_req_raw_volume", "(", "volumeID", ")", "insID", "=", "[", "a", "[", "'id'", "]", "for", "a", "in", "rawVolume", "[", "'_source'", "]", "[", "'_attachments'", "]", "]", "# check that all requested file are present", "for", "id", "in", "attachmentsID", ":", "if", "id", "not", "in", "insID", ":", "raise", "NotFoundException", "(", "\"could not found attachment '{}' of the volume '{}'\"", ".", "format", "(", "id", ",", "volumeID", ")", ")", "for", "index", ",", "id", "in", "enumerate", "(", "attachmentsID", ")", ":", "rawVolume", "[", "'_source'", "]", "[", "'_attachments'", "]", ".", "pop", "(", "insID", ".", "index", "(", "id", ")", ")", "self", ".", "_db", ".", "modify_book", "(", "volumeID", ",", "rawVolume", "[", "'_source'", "]", ",", "version", "=", "rawVolume", "[", "'_version'", "]", ")" ]
Updates the remove enabled baesd on the current number of line widgets .
def updateRemoveEnabled ( self ) : lineWidgets = self . lineWidgets ( ) count = len ( lineWidgets ) state = self . minimumCount ( ) < count for widget in lineWidgets : widget . setRemoveEnabled ( state )
11,427
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xquerybuilderwidget/xquerybuilderwidget.py#L289-L298
[ "def", "verify_ocsp", "(", "cls", ",", "certificate", ",", "issuer", ")", ":", "return", "OCSPVerifier", "(", "certificate", ",", "issuer", ",", "cls", ".", "get_ocsp_url", "(", ")", ",", "cls", ".", "get_ocsp_responder_certificate_path", "(", ")", ")", ".", "verify", "(", ")" ]
Updates the query line items to match the latest rule options .
def updateRules ( self ) : terms = sorted ( self . _rules . keys ( ) ) for child in self . lineWidgets ( ) : child . setTerms ( terms )
11,428
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xquerybuilderwidget/xquerybuilderwidget.py#L300-L306
[ "def", "vnormg", "(", "v", ",", "ndim", ")", ":", "v", "=", "stypes", ".", "toDoubleVector", "(", "v", ")", "ndim", "=", "ctypes", ".", "c_int", "(", "ndim", ")", "return", "libspice", ".", "vnormg_c", "(", "v", ",", "ndim", ")" ]
Emits that the current profile has changed .
def handleProfileChange ( self ) : # restore the profile settings prof = self . currentProfile ( ) vwidget = self . viewWidget ( ) if vwidget : prof . restore ( vwidget ) if not self . signalsBlocked ( ) : self . currentProfileChanged . emit ( self . currentProfile ( ) )
11,429
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofilemanager.py#L89-L100
[ "def", "volumes_delete", "(", "storage_pool", ",", "logger", ")", ":", "try", ":", "for", "vol_name", "in", "storage_pool", ".", "listVolumes", "(", ")", ":", "try", ":", "vol", "=", "storage_pool", ".", "storageVolLookupByName", "(", "vol_name", ")", "vol", ".", "delete", "(", "0", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volume %s.\"", ",", "vol_name", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volumes.\"", ")" ]
Displays the options menu . If the option menu policy is set to CustomContextMenu then the optionMenuRequested signal will be emitted otherwise the default context menu will be displayed .
def showOptionsMenu ( self ) : point = QPoint ( 0 , self . _optionsButton . height ( ) ) global_point = self . _optionsButton . mapToGlobal ( point ) # prompt the custom context menu if self . optionsMenuPolicy ( ) == Qt . CustomContextMenu : if not self . signalsBlocked ( ) : self . optionsMenuRequested . emit ( global_point ) return # use the default context menu menu = XViewProfileManagerMenu ( self ) menu . exec_ ( global_point )
11,430
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xviewwidget/xviewprofilemanager.py#L235-L252
[ "def", "complete_upload", "(", "self", ")", ":", "xml", "=", "self", ".", "to_xml", "(", ")", "return", "self", ".", "bucket", ".", "complete_multipart_upload", "(", "self", ".", "key_name", ",", "self", ".", "id", ",", "xml", ")" ]
Prompts the user for the filepath to save and then saves the image .
def accept ( self ) : filetypes = 'PNG Files (*.png);;JPG Files (*.jpg);;All Files (*.*)' filename = QFileDialog . getSaveFileName ( None , 'Save Snapshot' , self . filepath ( ) , filetypes ) if type ( filename ) == tuple : filename = filename [ 0 ] filename = nativestring ( filename ) if not filename : self . reject ( ) else : self . setFilepath ( filename ) self . save ( )
11,431
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L46-L64
[ "def", "thickness_hydrostatic_from_relative_humidity", "(", "pressure", ",", "temperature", ",", "relative_humidity", ",", "*", "*", "kwargs", ")", ":", "bottom", "=", "kwargs", ".", "pop", "(", "'bottom'", ",", "None", ")", "depth", "=", "kwargs", ".", "pop", "(", "'depth'", ",", "None", ")", "mixing", "=", "mixing_ratio_from_relative_humidity", "(", "relative_humidity", ",", "temperature", ",", "pressure", ")", "return", "thickness_hydrostatic", "(", "pressure", ",", "temperature", ",", "mixing", "=", "mixing", ",", "bottom", "=", "bottom", ",", "depth", "=", "depth", ")" ]
Rejects the snapshot and closes the widget .
def reject ( self ) : if self . hideWindow ( ) : self . hideWindow ( ) . show ( ) self . close ( ) self . deleteLater ( )
11,432
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L144-L152
[ "def", "parse_general_name", "(", "name", ")", ":", "name", "=", "force_text", "(", "name", ")", "typ", "=", "None", "match", "=", "GENERAL_NAME_RE", ".", "match", "(", "name", ")", "if", "match", "is", "not", "None", ":", "typ", ",", "name", "=", "match", ".", "groups", "(", ")", "typ", "=", "typ", ".", "lower", "(", ")", "if", "typ", "is", "None", ":", "if", "re", ".", "match", "(", "'[a-z0-9]{2,}://'", ",", "name", ")", ":", "# Looks like a URI", "try", ":", "return", "x509", ".", "UniformResourceIdentifier", "(", "name", ")", "except", "Exception", ":", "# pragma: no cover - this really accepts anything", "pass", "if", "'@'", "in", "name", ":", "# Looks like an Email address", "try", ":", "return", "x509", ".", "RFC822Name", "(", "validate_email", "(", "name", ")", ")", "except", "Exception", ":", "pass", "if", "name", ".", "strip", "(", ")", ".", "startswith", "(", "'/'", ")", ":", "# maybe it's a dirname?", "return", "x509", ".", "DirectoryName", "(", "x509_name", "(", "name", ")", ")", "# Try to parse this as IPAddress/Network", "try", ":", "return", "x509", ".", "IPAddress", "(", "ip_address", "(", "name", ")", ")", "except", "ValueError", ":", "pass", "try", ":", "return", "x509", ".", "IPAddress", "(", "ip_network", "(", "name", ")", ")", "except", "ValueError", ":", "pass", "# Try to encode as domain name. DNSName() does not validate the domain name, but this check will fail.", "if", "name", ".", "startswith", "(", "'*.'", ")", ":", "idna", ".", "encode", "(", "name", "[", "2", ":", "]", ")", "elif", "name", ".", "startswith", "(", "'.'", ")", ":", "idna", ".", "encode", "(", "name", "[", "1", ":", "]", ")", "else", ":", "idna", ".", "encode", "(", "name", ")", "# Almost anything passes as DNS name, so this is our default fallback", "return", "x509", ".", "DNSName", "(", "name", ")", "if", "typ", "==", "'uri'", ":", "return", "x509", ".", "UniformResourceIdentifier", "(", "name", ")", "elif", "typ", "==", "'email'", ":", "return", "x509", ".", "RFC822Name", "(", "validate_email", "(", "name", ")", ")", "elif", "typ", "==", "'ip'", ":", "try", ":", "return", "x509", ".", "IPAddress", "(", "ip_address", "(", "name", ")", ")", "except", "ValueError", ":", "pass", "try", ":", "return", "x509", ".", "IPAddress", "(", "ip_network", "(", "name", ")", ")", "except", "ValueError", ":", "pass", "raise", "ValueError", "(", "'Could not parse IP address.'", ")", "elif", "typ", "==", "'rid'", ":", "return", "x509", ".", "RegisteredID", "(", "x509", ".", "ObjectIdentifier", "(", "name", ")", ")", "elif", "typ", "==", "'othername'", ":", "regex", "=", "\"(.*);(.*):(.*)\"", "if", "re", ".", "match", "(", "regex", ",", "name", ")", "is", "not", "None", ":", "oid", ",", "asn_typ", ",", "val", "=", "re", ".", "match", "(", "regex", ",", "name", ")", ".", "groups", "(", ")", "oid", "=", "x509", ".", "ObjectIdentifier", "(", "oid", ")", "if", "asn_typ", "==", "'UTF8'", ":", "val", "=", "val", ".", "encode", "(", "'utf-8'", ")", "elif", "asn_typ", "==", "'OctetString'", ":", "val", "=", "bytes", "(", "bytearray", ".", "fromhex", "(", "val", ")", ")", "val", "=", "OctetString", "(", "val", ")", ".", "dump", "(", ")", "else", ":", "raise", "ValueError", "(", "'Unsupported ASN type in otherName: %s'", "%", "asn_typ", ")", "val", "=", "force_bytes", "(", "val", ")", "return", "x509", ".", "OtherName", "(", "oid", ",", "val", ")", "else", ":", "raise", "ValueError", "(", "'Incorrect otherName format: %s'", "%", "name", ")", "elif", "typ", "==", "'dirname'", ":", "return", "x509", ".", "DirectoryName", "(", "x509_name", "(", "name", ")", ")", "else", ":", "# Try to encode the domain name. DNSName() does not validate the domain name, but this", "# check will fail.", "if", "name", ".", "startswith", "(", "'*.'", ")", ":", "idna", ".", "encode", "(", "name", "[", "2", ":", "]", ")", "elif", "name", ".", "startswith", "(", "'.'", ")", ":", "idna", ".", "encode", "(", "name", "[", "1", ":", "]", ")", "else", ":", "idna", ".", "encode", "(", "name", ")", "return", "x509", ".", "DNSName", "(", "name", ")" ]
Saves the snapshot based on the current region .
def save ( self ) : # close down the snapshot widget if self . hideWindow ( ) : self . hideWindow ( ) . hide ( ) self . hide ( ) QApplication . processEvents ( ) time . sleep ( 1 ) # create the pixmap to save wid = QApplication . desktop ( ) . winId ( ) if not self . _region . isNull ( ) : x = self . _region . x ( ) y = self . _region . y ( ) w = self . _region . width ( ) h = self . _region . height ( ) else : x = self . x ( ) y = self . y ( ) w = self . width ( ) h = self . height ( ) pixmap = QPixmap . grabWindow ( wid , x , y , w , h ) pixmap . save ( self . filepath ( ) ) self . close ( ) self . deleteLater ( ) if self . hideWindow ( ) : self . hideWindow ( ) . show ( )
11,433
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L162-L194
[ "def", "_load_secure_params", "(", "self", ")", ":", "self", ".", "tcex", ".", "log", ".", "info", "(", "'Loading secure params.'", ")", "# Retrieve secure params and inject them into sys.argv", "r", "=", "self", ".", "tcex", ".", "session", ".", "get", "(", "'/internal/job/execution/parameters'", ")", "# check for bad status code and response that is not JSON", "if", "not", "r", ".", "ok", "or", "r", ".", "headers", ".", "get", "(", "'content-type'", ")", "!=", "'application/json'", ":", "err", "=", "r", ".", "text", "or", "r", ".", "reason", "self", ".", "tcex", ".", "exit", "(", "1", ",", "'Error retrieving secure params from API ({}).'", ".", "format", "(", "err", ")", ")", "# return secure params", "return", "r", ".", "json", "(", ")", ".", "get", "(", "'inputs'", ",", "{", "}", ")" ]
Shows this widget and hides the specified window if necessary .
def show ( self ) : super ( XSnapshotWidget , self ) . show ( ) if self . hideWindow ( ) : self . hideWindow ( ) . hide ( ) QApplication . processEvents ( )
11,434
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xsnapshotwidget.py#L196-L204
[ "def", "__parseThunks", "(", "self", ",", "thunkRVA", ",", "importSection", ")", ":", "offset", "=", "to_offset", "(", "thunkRVA", ",", "importSection", ")", "table_offset", "=", "0", "thunks", "=", "[", "]", "while", "True", ":", "thunk", "=", "IMAGE_THUNK_DATA", ".", "from_buffer", "(", "importSection", ".", "raw", ",", "offset", ")", "offset", "+=", "sizeof", "(", "IMAGE_THUNK_DATA", ")", "if", "thunk", ".", "Ordinal", "==", "0", ":", "break", "thunkData", "=", "ThunkData", "(", "header", "=", "thunk", ",", "rva", "=", "table_offset", "+", "thunkRVA", ",", "ordinal", "=", "None", ",", "importByName", "=", "None", ")", "if", "to_offset", "(", "thunk", ".", "AddressOfData", ",", "importSection", ")", ">", "0", "and", "to_offset", "(", "thunk", ".", "AddressOfData", ",", "importSection", ")", "<", "len", "(", "self", ".", "_bytes", ")", ":", "self", ".", "__parseThunkData", "(", "thunkData", ",", "importSection", ")", "thunks", ".", "append", "(", "thunkData", ")", "table_offset", "+=", "4", "return", "thunks" ]
Constructs the keyphrases table containing their matching scores in a set of texts .
def keyphrases_table ( keyphrases , texts , similarity_measure = None , synonimizer = None , language = consts . Language . ENGLISH ) : similarity_measure = similarity_measure or relevance . ASTRelevanceMeasure ( ) text_titles = texts . keys ( ) text_collection = texts . values ( ) similarity_measure . set_text_collection ( text_collection , language ) i = 0 keyphrases_prepared = { keyphrase : utils . prepare_text ( keyphrase ) for keyphrase in keyphrases } total_keyphrases = len ( keyphrases ) total_scores = len ( text_collection ) * total_keyphrases res = { } for keyphrase in keyphrases : if not keyphrase : continue res [ keyphrase ] = { } for j in xrange ( len ( text_collection ) ) : i += 1 logging . progress ( "Calculating matching scores" , i , total_scores ) res [ keyphrase ] [ text_titles [ j ] ] = similarity_measure . relevance ( keyphrases_prepared [ keyphrase ] , text = j , synonimizer = synonimizer ) logging . clear ( ) return res
11,435
https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/applications.py#L11-L56
[ "def", "sample_normal", "(", "mean", ",", "var", ",", "rng", ")", ":", "ret", "=", "numpy", ".", "sqrt", "(", "var", ")", "*", "rng", ".", "randn", "(", "*", "mean", ".", "shape", ")", "+", "mean", "return", "ret" ]
Constructs the keyphrases relation graph based on the given texts corpus .
def keyphrases_graph ( keyphrases , texts , referral_confidence = 0.6 , relevance_threshold = 0.25 , support_threshold = 1 , similarity_measure = None , synonimizer = None , language = consts . Language . ENGLISH ) : similarity_measure = similarity_measure or relevance . ASTRelevanceMeasure ( ) # Keyphrases table table = keyphrases_table ( keyphrases , texts , similarity_measure , synonimizer , language ) # Dictionary { "keyphrase" => set(names of texts containing "keyphrase") } keyphrase_texts = { keyphrase : set ( [ text for text in texts if table [ keyphrase ] [ text ] >= relevance_threshold ] ) for keyphrase in keyphrases } # Initializing the graph object with nodes graph = { "nodes" : [ { "id" : i , "label" : keyphrase , "support" : len ( keyphrase_texts [ keyphrase ] ) } for i , keyphrase in enumerate ( keyphrases ) ] , "edges" : [ ] , "referral_confidence" : referral_confidence , "relevance_threshold" : relevance_threshold , "support_threshold" : support_threshold } # Removing nodes with small support after we've numbered all nodes graph [ "nodes" ] = [ n for n in graph [ "nodes" ] if len ( keyphrase_texts [ n [ "label" ] ] ) >= support_threshold ] # Creating edges # NOTE(msdubov): permutations(), unlike combinations(), treats (1,2) and (2,1) as different for i1 , i2 in itertools . permutations ( range ( len ( graph [ "nodes" ] ) ) , 2 ) : node1 = graph [ "nodes" ] [ i1 ] node2 = graph [ "nodes" ] [ i2 ] confidence = ( float ( len ( keyphrase_texts [ node1 [ "label" ] ] & keyphrase_texts [ node2 [ "label" ] ] ) ) / max ( len ( keyphrase_texts [ node1 [ "label" ] ] ) , 1 ) ) if confidence >= referral_confidence : graph [ "edges" ] . append ( { "source" : node1 [ "id" ] , "target" : node2 [ "id" ] , "confidence" : confidence } ) return graph
11,436
https://github.com/mikhaildubov/AST-text-analysis/blob/055ad8d2492c100bbbaa25309ec1074bdf1dfaa5/east/applications.py#L59-L149
[ "def", "GetExtractionStatusUpdateCallback", "(", "self", ")", ":", "if", "self", ".", "_mode", "==", "self", ".", "MODE_LINEAR", ":", "return", "self", ".", "_PrintExtractionStatusUpdateLinear", "if", "self", ".", "_mode", "==", "self", ".", "MODE_WINDOW", ":", "return", "self", ".", "_PrintExtractionStatusUpdateWindow", "return", "None" ]
Like the regular decode function but this one raises an HTTPUnicodeError if errors is strict .
def _decode_unicode ( value , charset , errors ) : fallback = None if errors . startswith ( 'fallback:' ) : fallback = errors [ 9 : ] errors = 'strict' try : return value . decode ( charset , errors ) except UnicodeError , e : if fallback is not None : return value . decode ( fallback , 'replace' ) from werkzeug . exceptions import HTTPUnicodeError raise HTTPUnicodeError ( str ( e ) )
11,437
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_internal.py#L12-L25
[ "def", "need_rejoin", "(", "self", ")", ":", "if", "not", "self", ".", "_subscription", ".", "partitions_auto_assigned", "(", ")", ":", "return", "False", "if", "self", ".", "_auto_assign_all_partitions", "(", ")", ":", "return", "False", "# we need to rejoin if we performed the assignment and metadata has changed", "if", "(", "self", ".", "_assignment_snapshot", "is", "not", "None", "and", "self", ".", "_assignment_snapshot", "!=", "self", ".", "_metadata_snapshot", ")", ":", "return", "True", "# we need to join if our subscription has changed since the last join", "if", "(", "self", ".", "_joined_subscription", "is", "not", "None", "and", "self", ".", "_joined_subscription", "!=", "self", ".", "_subscription", ".", "subscription", ")", ":", "return", "True", "return", "super", "(", "ConsumerCoordinator", ",", "self", ")", ".", "need_rejoin", "(", ")" ]
Handles a drop event .
def dropEvent ( self , event ) : url = event . mimeData ( ) . urls ( ) [ 0 ] url_path = nativestring ( url . toString ( ) ) # download an icon from the web if ( not url_path . startswith ( 'file:' ) ) : filename = os . path . basename ( url_path ) temp_path = os . path . join ( nativestring ( QDir . tempPath ( ) ) , filename ) try : urllib . urlretrieve ( url_path , temp_path ) except IOError : return self . setFilepath ( temp_path ) else : self . setFilepath ( url_path . replace ( 'file://' , '' ) )
11,438
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xiconbutton.py#L90-L109
[ "def", "_load_bundle_map", "(", "self", ")", ":", "bundle_map", "=", "{", "}", "next_href", "=", "None", "has_next", "=", "True", "while", "has_next", ":", "bundles", "=", "self", ".", "clarify_client", ".", "get_bundle_list", "(", "href", "=", "next_href", ",", "embed_items", "=", "True", ")", "items", "=", "get_embedded_items", "(", "bundles", ")", "for", "item", "in", "items", ":", "bc_video_id", "=", "item", ".", "get", "(", "'external_id'", ")", "if", "bc_video_id", "is", "not", "None", "and", "len", "(", "bc_video_id", ")", ">", "0", ":", "bundle_map", "[", "bc_video_id", "]", "=", "item", "next_href", "=", "get_link_href", "(", "bundles", ",", "'next'", ")", "if", "next_href", "is", "None", ":", "has_next", "=", "False", "return", "bundle_map" ]
Picks the image file to use for this icon path .
def pickFilepath ( self ) : filepath = QFileDialog . getOpenFileName ( self , 'Select Image File' , QDir . currentPath ( ) , self . fileTypes ( ) ) if type ( filepath ) == tuple : filepath = nativestring ( filepath [ 0 ] ) if ( filepath ) : self . setFilepath ( filepath )
11,439
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xiconbutton.py#L111-L124
[ "def", "RunValidationOutputToConsole", "(", "feed", ",", "options", ")", ":", "accumulator", "=", "CountingConsoleProblemAccumulator", "(", "options", ".", "error_types_ignore_list", ")", "problems", "=", "transitfeed", ".", "ProblemReporter", "(", "accumulator", ")", "_", ",", "exit_code", "=", "RunValidation", "(", "feed", ",", "options", ",", "problems", ")", "return", "exit_code" ]
Fires a new event
async def fire ( self , name , payload = None , * , dc = None , node = None , service = None , tag = None ) : params = { "dc" : dc , "node" : extract_pattern ( node ) , "service" : extract_pattern ( service ) , "tag" : extract_pattern ( tag ) } payload = encode_value ( payload ) if payload else None response = await self . _api . put ( "/v1/event/fire" , name , data = payload , params = params , headers = { "Content-Type" : "application/octet-stream" } ) result = format_event ( response . body ) return result
11,440
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/event_endpoint.py#L10-L53
[ "def", "get_available_symbols", "(", "*", "*", "kwargs", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "WNG_MSG", "%", "(", "\"get_available_symbols\"", ",", "\"refdata.get_symbols\"", ")", ")", "_ALL_SYMBOLS_URL", "=", "\"https://api.iextrading.com/1.0/ref-data/symbols\"", "handler", "=", "_IEXBase", "(", "*", "*", "kwargs", ")", "response", "=", "handler", ".", "_execute_iex_query", "(", "_ALL_SYMBOLS_URL", ")", "if", "not", "response", ":", "raise", "IEXQueryError", "(", "\"Could not download all symbols\"", ")", "else", ":", "return", "response" ]
Lists the most recent events an agent has seen
async def items ( self , name = None , * , watch = None ) : path = "/v1/event/list" params = { "name" : name } response = await self . _api . get ( path , params = params , watch = watch ) results = [ format_event ( data ) for data in response . body ] return consul ( results , meta = extract_meta ( response . headers ) )
11,441
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/event_endpoint.py#L55-L84
[ "def", "_max_weight_operator", "(", "ops", ":", "Iterable", "[", "PauliTerm", "]", ")", "->", "Union", "[", "None", ",", "PauliTerm", "]", ":", "mapping", "=", "dict", "(", ")", "# type: Dict[int, str]", "for", "op", "in", "ops", ":", "for", "idx", ",", "op_str", "in", "op", ":", "if", "idx", "in", "mapping", ":", "if", "mapping", "[", "idx", "]", "!=", "op_str", ":", "return", "None", "else", ":", "mapping", "[", "idx", "]", "=", "op_str", "op", "=", "functools", ".", "reduce", "(", "mul", ",", "(", "PauliTerm", "(", "op", ",", "q", ")", "for", "q", ",", "op", "in", "mapping", ".", "items", "(", ")", ")", ",", "sI", "(", ")", ")", "return", "op" ]
Updates the ui to show the latest record values .
def updateRecordValues ( self ) : record = self . record ( ) if not record : return # update the record information tree = self . treeWidget ( ) if not isinstance ( tree , XTreeWidget ) : return for column in record . schema ( ) . columns ( ) : c = tree . column ( column . displayName ( ) ) if c == - 1 : continue elif tree . isColumnHidden ( c ) : continue else : val = record . recordValue ( column . name ( ) ) self . updateColumnValue ( column , val , c ) # update the record state information if not record . isRecord ( ) : self . addRecordState ( XOrbRecordItem . State . New ) elif record . isModified ( ) : self . addRecordState ( XOrbRecordItem . State . Modified )
11,442
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbtreewidget/xorbrecorditem.py#L288-L318
[ "def", "upload_cbn_dir", "(", "dir_path", ",", "manager", ")", ":", "t", "=", "time", ".", "time", "(", ")", "for", "jfg_path", "in", "os", ".", "listdir", "(", "dir_path", ")", ":", "if", "not", "jfg_path", ".", "endswith", "(", "'.jgf'", ")", ":", "continue", "path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "jfg_path", ")", "log", ".", "info", "(", "'opening %s'", ",", "path", ")", "with", "open", "(", "path", ")", "as", "f", ":", "cbn_jgif_dict", "=", "json", ".", "load", "(", "f", ")", "graph", "=", "pybel", ".", "from_cbn_jgif", "(", "cbn_jgif_dict", ")", "out_path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "jfg_path", ".", "replace", "(", "'.jgf'", ",", "'.bel'", ")", ")", "with", "open", "(", "out_path", ",", "'w'", ")", "as", "o", ":", "pybel", ".", "to_bel", "(", "graph", ",", "o", ")", "strip_annotations", "(", "graph", ")", "enrich_pubmed_citations", "(", "manager", "=", "manager", ",", "graph", "=", "graph", ")", "pybel", ".", "to_database", "(", "graph", ",", "manager", "=", "manager", ")", "log", ".", "info", "(", "''", ")", "log", ".", "info", "(", "'done in %.2f'", ",", "time", ".", "time", "(", ")", "-", "t", ")" ]
Extras the 4 bits XORS the message data and does table lookups .
def extract_bits ( self , val ) : # Step one, extract the Most significant 4 bits of the CRC register thisval = self . high >> 4 # XOR in the Message Data into the extracted bits thisval = thisval ^ val # Shift the CRC Register left 4 bits self . high = ( self . high << 4 ) | ( self . low >> 4 ) self . high = self . high & constants . BYTEMASK # force char self . low = self . low << 4 self . low = self . low & constants . BYTEMASK # force char # Do the table lookups and XOR the result into the CRC tables self . high = self . high ^ self . LookupHigh [ thisval ] self . high = self . high & constants . BYTEMASK # force char self . low = self . low ^ self . LookupLow [ thisval ] self . low = self . low & constants . BYTEMASK
11,443
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L37-L52
[ "def", "_remove_player", "(", "self", ",", "player_id", ")", ":", "player", "=", "self", ".", "_mpris_players", ".", "get", "(", "player_id", ")", "if", "player", ":", "if", "player", ".", "get", "(", "\"subscription\"", ")", ":", "player", "[", "\"subscription\"", "]", ".", "disconnect", "(", ")", "del", "self", ".", "_mpris_players", "[", "player_id", "]" ]
Calculates a CRC
def run ( self , message ) : for value in message : self . update ( value ) return [ self . low , self . high ]
11,444
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L59-L63
[ "def", "remove_option_regexp", "(", "self", ",", "section", ",", "option", ",", "expr", ")", ":", "if", "not", "section", "or", "section", "==", "self", ".", "DEFAULTSECT", ":", "sectdict", "=", "self", ".", "_defaults", "else", ":", "try", ":", "sectdict", "=", "self", ".", "_sections", "[", "section", "]", "except", "KeyError", ":", "raise", "NoSectionError", "(", "# pylint: disable=undefined-variable", "salt", ".", "utils", ".", "stringutils", ".", "to_str", "(", "section", ")", ")", "option", "=", "self", ".", "optionxform", "(", "option", ")", "if", "option", "not", "in", "sectdict", ":", "return", "False", "regexp", "=", "re", ".", "compile", "(", "expr", ")", "if", "isinstance", "(", "sectdict", "[", "option", "]", ",", "list", ")", ":", "new_list", "=", "[", "x", "for", "x", "in", "sectdict", "[", "option", "]", "if", "not", "regexp", ".", "search", "(", "x", ")", "]", "# Revert back to a list if we removed all but one item", "if", "len", "(", "new_list", ")", "==", "1", ":", "new_list", "=", "new_list", "[", "0", "]", "existed", "=", "new_list", "!=", "sectdict", "[", "option", "]", "if", "existed", ":", "del", "sectdict", "[", "option", "]", "sectdict", "[", "option", "]", "=", "new_list", "del", "new_list", "else", ":", "existed", "=", "bool", "(", "regexp", ".", "search", "(", "sectdict", "[", "option", "]", ")", ")", "if", "existed", ":", "del", "sectdict", "[", "option", "]", "return", "existed" ]
Forms a message payload excluding CRC
def _hm_form_message ( self , thermostat_id , protocol , source , function , start , payload ) : if protocol == constants . HMV3_ID : start_low = ( start & constants . BYTEMASK ) start_high = ( start >> 8 ) & constants . BYTEMASK if function == constants . FUNC_READ : payload_length = 0 length_low = ( constants . RW_LENGTH_ALL & constants . BYTEMASK ) length_high = ( constants . RW_LENGTH_ALL >> 8 ) & constants . BYTEMASK else : payload_length = len ( payload ) length_low = ( payload_length & constants . BYTEMASK ) length_high = ( payload_length >> 8 ) & constants . BYTEMASK msg = [ thermostat_id , 10 + payload_length , source , function , start_low , start_high , length_low , length_high ] if function == constants . FUNC_WRITE : msg = msg + payload type ( msg ) return msg else : assert 0 , "Un-supported protocol found %s" % protocol
11,445
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L80-L117
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Forms a message payload including CRC
def _hm_form_message_crc ( self , thermostat_id , protocol , source , function , start , payload ) : data = self . _hm_form_message ( thermostat_id , protocol , source , function , start , payload ) crc = CRC16 ( ) data = data + crc . run ( data ) return data
11,446
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L119-L133
[ "def", "_openResources", "(", "self", ")", ":", "try", ":", "rate", ",", "data", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "self", ".", "_fileName", ",", "mmap", "=", "True", ")", "except", "Exception", "as", "ex", ":", "logger", ".", "warning", "(", "ex", ")", "logger", ".", "warning", "(", "\"Unable to read wav with memmory mapping. Trying without now.\"", ")", "rate", ",", "data", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "self", ".", "_fileName", ",", "mmap", "=", "False", ")", "self", ".", "_array", "=", "data", "self", ".", "attributes", "[", "'rate'", "]", "=", "rate" ]
Verifies message appears legal
def _hm_verify_message_crc_uk ( self , thermostat_id , protocol , source , expectedFunction , expectedLength , datal ) : # expectedLength only used for read msgs as always 7 for write badresponse = 0 if protocol == constants . HMV3_ID : checksum = datal [ len ( datal ) - 2 : ] rxmsg = datal [ : len ( datal ) - 2 ] crc = CRC16 ( ) # Initialises the CRC expectedchecksum = crc . run ( rxmsg ) if expectedchecksum == checksum : logging . info ( "CRC is correct" ) else : logging . error ( "CRC is INCORRECT" ) serror = "Incorrect CRC" sys . stderr . write ( serror ) badresponse += 1 dest_addr = datal [ 0 ] frame_len_l = datal [ 1 ] frame_len_h = datal [ 2 ] frame_len = ( frame_len_h << 8 ) | frame_len_l source_addr = datal [ 3 ] func_code = datal [ 4 ] if ( dest_addr != 129 and dest_addr != 160 ) : logging . info ( "dest_addr is ILLEGAL" ) serror = "Illegal Dest Addr: %s\n" % ( dest_addr ) sys . stderr . write ( serror ) badresponse += 1 if dest_addr != thermostat_id : logging . info ( "dest_addr is INCORRECT" ) serror = "Incorrect Dest Addr: %s\n" % ( dest_addr ) sys . stderr . write ( serror ) badresponse += 1 if ( source_addr < 1 or source_addr > 32 ) : logging . info ( "source_addr is ILLEGAL" ) serror = "Illegal Src Addr: %s\n" % ( source_addr ) sys . stderr . write ( serror ) badresponse += 1 if source_addr != source : logging . info ( "source addr is INCORRECT" ) serror = "Incorrect Src Addr: %s\n" % ( source_addr ) sys . stderr . write ( serror ) badresponse += 1 if ( func_code != constants . FUNC_WRITE and func_code != constants . FUNC_READ ) : logging . info ( "Func Code is UNKNWON" ) serror = "Unknown Func Code: %s\n" % ( func_code ) sys . stderr . write ( serror ) badresponse += 1 if func_code != expectedFunction : logging . info ( "Func Code is UNEXPECTED" ) serror = "Unexpected Func Code: %s\n" % ( func_code ) sys . stderr . write ( serror ) badresponse += 1 if ( func_code == constants . FUNC_WRITE and frame_len != 7 ) : # Reply to Write is always 7 long logging . info ( "response length is INCORRECT" ) serror = "Incorrect length: %s\n" % ( frame_len ) sys . stderr . write ( serror ) badresponse += 1 if len ( datal ) != frame_len : logging . info ( "response length MISMATCHES header" ) serror = "Mismatch length: %s %s\n" % ( len ( datal ) , frame_len ) sys . stderr . write ( serror ) badresponse += 1 # if (func_code == constants.FUNC_READ and # expectedLength !=len(datal) ): # # Read response length is wrong # logging.info("response length # not EXPECTED value") # logging.info("Got %s when expecting %s", # len(datal), expectedLength) # logging.info("Data is:\n %s", datal) # s = "Incorrect length: %s\n" % (frame_len) # sys.stderr.write(s) # badresponse += 1 if ( badresponse == 0 ) : return True else : return False else : assert 0 , "Un-supported protocol found %s" % protocol
11,447
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L135-L238
[ "def", "load", "(", "cls", ",", "fname", ",", "args", ")", ":", "if", "args", ".", "type", "==", "JSON", ":", "if", "fname", ".", "endswith", "(", "'.bz2'", ")", ":", "open_", "=", "bz2", ".", "open", "else", ":", "open_", "=", "open", "if", "args", ".", "progress", ":", "print", "(", "'Loading JSON data...'", ")", "with", "open_", "(", "fname", ",", "'rt'", ")", "as", "fp", ":", "storage", "=", "JsonStorage", ".", "load", "(", "fp", ")", "else", ":", "storage", "=", "SqliteStorage", ".", "load", "(", "fname", ")", "if", "args", ".", "settings", "is", "not", "None", ":", "extend", "(", "storage", ".", "settings", ",", "args", ".", "settings", ")", "return", "cls", ".", "from_storage", "(", "storage", ")" ]
This is the only interface to the serial connection .
def _hm_send_msg ( self , message ) : try : serial_message = message self . conn . write ( serial_message ) # Write a string except serial . SerialTimeoutException : serror = "Write timeout error: \n" sys . stderr . write ( serror ) # Now wait for reply byteread = self . conn . read ( 159 ) # NB max return is 75 in 5/2 mode or 159 in 7day mode datal = list ( byteread ) return datal
11,448
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L240-L252
[ "def", "from_dict", "(", "cls", ",", "dictionary", ")", ":", "cookbooks", "=", "set", "(", ")", "sources", "=", "set", "(", ")", "other", "=", "set", "(", ")", "# put these in order", "groups", "=", "[", "sources", ",", "cookbooks", ",", "other", "]", "for", "key", ",", "val", "in", "dictionary", ".", "items", "(", ")", ":", "if", "key", "==", "'cookbook'", ":", "cookbooks", ".", "update", "(", "{", "cls", ".", "cookbook_statement", "(", "cbn", ",", "meta", ")", "for", "cbn", ",", "meta", "in", "val", ".", "items", "(", ")", "}", ")", "elif", "key", "==", "'source'", ":", "sources", ".", "update", "(", "{", "\"source '%s'\"", "%", "src", "for", "src", "in", "val", "}", ")", "elif", "key", "==", "'metadata'", ":", "other", ".", "add", "(", "'metadata'", ")", "body", "=", "''", "for", "group", "in", "groups", ":", "if", "group", ":", "body", "+=", "'\\n'", "body", "+=", "'\\n'", ".", "join", "(", "group", ")", "return", "cls", ".", "from_string", "(", "body", ")" ]
Reads from the DCB and maps to yaml config file .
def _hm_read_address ( self ) : response = self . _hm_send_address ( self . address , 0 , 0 , 0 ) lookup = self . config [ 'keys' ] offset = self . config [ 'offset' ] keydata = { } for i in lookup : try : kdata = lookup [ i ] ddata = response [ i + offset ] keydata [ i ] = { 'label' : kdata , 'value' : ddata } except IndexError : logging . info ( "Finished processing at %d" , i ) return keydata
11,449
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L284-L300
[ "def", "access_token", "(", "self", ")", ":", "access_token", "=", "self", ".", "session", ".", "get", "(", "self", ".", "access_token_key", ")", "if", "access_token", ":", "if", "not", "self", ".", "expires_at", ":", "# user provided access_token, just return it", "return", "access_token", "timestamp", "=", "time", ".", "time", "(", ")", "if", "self", ".", "expires_at", "-", "timestamp", ">", "60", ":", "return", "access_token", "self", ".", "fetch_access_token", "(", ")", "return", "self", ".", "session", ".", "get", "(", "self", ".", "access_token_key", ")" ]
Returns the full DCB only use for non read - only operations Use self . dcb for read - only operations .
def read_dcb ( self ) : logging . info ( "Getting latest data from DCB...." ) self . dcb = self . _hm_read_address ( ) return self . dcb
11,450
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L302-L309
[ "def", "remove_targets", "(", "self", ",", "type", ",", "kept", "=", "None", ")", ":", "if", "kept", "is", "None", ":", "kept", "=", "[", "i", "for", "i", ",", "x", "in", "enumerate", "(", "self", ".", "_targets", ")", "if", "not", "isinstance", "(", "x", ",", "type", ")", "]", "if", "len", "(", "kept", ")", "==", "len", "(", "self", ".", "_targets", ")", ":", "return", "self", "self", ".", "_targets", "=", "[", "self", ".", "_targets", "[", "x", "]", "for", "x", "in", "kept", "]", "self", ".", "_labels", "=", "[", "self", ".", "_labels", "[", "x", "]", "for", "x", "in", "kept", "]", "if", "not", "self", ".", "_groups", ":", "return", "self", "index_map", "=", "{", "o_idx", ":", "n_idx", "for", "n_idx", ",", "o_idx", "in", "zip", "(", "range", "(", "len", "(", "self", ".", "_targets", ")", ")", ",", "kept", ")", "}", "kept", "=", "set", "(", "kept", ")", "for", "idx", ",", "grp", "in", "enumerate", "(", "self", ".", "_groups", ")", ":", "self", ".", "_groups", "[", "idx", "]", "=", "_sos_group", "(", "[", "index_map", "[", "x", "]", "for", "x", "in", "grp", ".", "_indexes", "if", "x", "in", "kept", "]", ",", "[", "y", "for", "x", ",", "y", "in", "zip", "(", "grp", ".", "_indexes", ",", "grp", ".", "_labels", ")", "if", "x", "in", "kept", "]", ")", ".", "set", "(", "*", "*", "grp", ".", "_dict", ")", "return", "self" ]
Sets the target temperature to the requested int
def set_target_temp ( self , temperature ) : if 35 < temperature < 5 : logging . info ( "Refusing to set temp outside of allowed range" ) return False else : self . _hm_send_address ( self . address , 18 , temperature , 1 ) return True
11,451
https://github.com/andylockran/heatmiserV3/blob/bd8638f5fd1f85d16c908020252f58a0cc4f6ac0/heatmiserV3/heatmiser.py#L384-L393
[ "def", "_finalize_merge", "(", "out_file", ",", "bam_files", ",", "config", ")", ":", "# Ensure timestamps are up to date on output file and index", "# Works around issues on systems with inconsistent times", "for", "ext", "in", "[", "\"\"", ",", "\".bai\"", "]", ":", "if", "os", ".", "path", ".", "exists", "(", "out_file", "+", "ext", ")", ":", "subprocess", ".", "check_call", "(", "[", "\"touch\"", ",", "out_file", "+", "ext", "]", ")", "for", "b", "in", "bam_files", ":", "utils", ".", "save_diskspace", "(", "b", ",", "\"BAM merged to %s\"", "%", "out_file", ",", "config", ")" ]
Returns the health info of a node .
async def node ( self , node , * , dc = None , watch = None , consistency = None ) : node_id = extract_attr ( node , keys = [ "Node" , "ID" ] ) params = { "dc" : dc } response = await self . _api . get ( "/v1/health/node" , node_id , params = params , watch = watch , consistency = consistency ) return consul ( response )
11,452
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/health_endpoint.py#L16-L69
[ "def", "remove_unused_resources", "(", "issues", ",", "app_dir", ",", "ignore_layouts", ")", ":", "for", "issue", "in", "issues", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "app_dir", ",", "issue", ".", "filepath", ")", "if", "issue", ".", "remove_file", ":", "remove_resource_file", "(", "issue", ",", "filepath", ",", "ignore_layouts", ")", "else", ":", "remove_resource_value", "(", "issue", ",", "filepath", ")" ]
Returns the checks of a service
async def checks ( self , service , * , dc = None , near = None , watch = None , consistency = None ) : service_id = extract_attr ( service , keys = [ "ServiceID" , "ID" ] ) params = { "dc" : dc , "near" : near } response = await self . _api . get ( "/v1/health/checks" , service_id , params = params , watch = watch , consistency = consistency ) return consul ( response )
11,453
https://github.com/johnnoone/aioconsul/blob/02f7a529d7dc2e49bed942111067aa5faf320e90/aioconsul/client/health_endpoint.py#L71-L92
[ "def", "_openResources", "(", "self", ")", ":", "try", ":", "rate", ",", "data", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "self", ".", "_fileName", ",", "mmap", "=", "True", ")", "except", "Exception", "as", "ex", ":", "logger", ".", "warning", "(", "ex", ")", "logger", ".", "warning", "(", "\"Unable to read wav with memmory mapping. Trying without now.\"", ")", "rate", ",", "data", "=", "scipy", ".", "io", ".", "wavfile", ".", "read", "(", "self", ".", "_fileName", ",", "mmap", "=", "False", ")", "self", ".", "_array", "=", "data", "self", ".", "attributes", "[", "'rate'", "]", "=", "rate" ]
Makes a stream limited .
def make_limited_stream ( stream , limit ) : if not isinstance ( stream , LimitedStream ) : if limit is None : raise TypeError ( 'stream not limited and no limit provided.' ) stream = LimitedStream ( stream , limit ) return stream
11,454
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_wsgi.py#L172-L178
[ "def", "delete_entity", "(", "self", ",", "entity_id", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "api_path", "=", "'/v1/{mount_point}/entity/id/{id}'", ".", "format", "(", "mount_point", "=", "mount_point", ",", "id", "=", "entity_id", ",", ")", "return", "self", ".", "_adapter", ".", "delete", "(", "url", "=", "api_path", ",", ")" ]
Exhaust the stream . This consumes all the data left until the limit is reached .
def exhaust ( self , chunk_size = 1024 * 16 ) : to_read = self . limit - self . _pos chunk = chunk_size while to_read > 0 : chunk = min ( to_read , chunk ) self . read ( chunk ) to_read -= chunk
11,455
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_wsgi.py#L85-L98
[ "def", "agp", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "base", "import", "DictFile", "p", "=", "OptionParser", "(", "agp", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "3", ":", "sys", ".", "exit", "(", "not", "p", ".", "print_help", "(", ")", ")", "tpffile", ",", "certificatefile", ",", "agpfile", "=", "args", "orientationguide", "=", "DictFile", "(", "tpffile", ",", "valuepos", "=", "2", ")", "cert", "=", "Certificate", "(", "certificatefile", ")", "cert", ".", "write_AGP", "(", "agpfile", ",", "orientationguide", "=", "orientationguide", ")" ]
Read size bytes or if size is not provided everything is read .
def read ( self , size = None ) : if self . _pos >= self . limit : return self . on_exhausted ( ) if size is None or size == - 1 : # -1 is for consistence with file size = self . limit to_read = min ( self . limit - self . _pos , size ) try : read = self . _read ( to_read ) except ( IOError , ValueError ) : return self . on_disconnect ( ) if to_read and len ( read ) != to_read : return self . on_disconnect ( ) self . _pos += len ( read ) return read
11,456
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_wsgi.py#L100-L117
[ "def", "merge_entities", "(", "self", ",", "from_entity_ids", ",", "to_entity_id", ",", "force", "=", "False", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'from_entity_ids'", ":", "from_entity_ids", ",", "'to_entity_id'", ":", "to_entity_id", ",", "'force'", ":", "force", ",", "}", "api_path", "=", "'/v1/{mount_point}/entity/merge'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Reads one line from the stream .
def readline ( self , size = None ) : if self . _pos >= self . limit : return self . on_exhausted ( ) if size is None : size = self . limit - self . _pos else : size = min ( size , self . limit - self . _pos ) try : line = self . _readline ( size ) except ( ValueError , IOError ) : return self . on_disconnect ( ) if size and not line : return self . on_disconnect ( ) self . _pos += len ( line ) return line
11,457
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_wsgi.py#L119-L134
[ "def", "configure", "(", "self", ",", "organization", ",", "base_url", "=", "''", ",", "ttl", "=", "''", ",", "max_ttl", "=", "''", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'organization'", ":", "organization", ",", "'base_url'", ":", "base_url", ",", "'ttl'", ":", "ttl", ",", "'max_ttl'", ":", "max_ttl", ",", "}", "api_path", "=", "'/v1/auth/{mount_point}/config'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Rebuilds the current item in the scene .
def rebuild ( self ) : self . markForRebuild ( False ) self . _textData = [ ] if ( self . rebuildBlocked ( ) ) : return scene = self . scene ( ) if ( not scene ) : return # rebuild a month look if ( scene . currentMode ( ) == scene . Mode . Month ) : self . rebuildMonth ( ) elif ( scene . currentMode ( ) in ( scene . Mode . Day , scene . Mode . Week ) ) : self . rebuildDay ( )
11,458
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendaritem.py#L240-L259
[ "def", "_cert_array_from_pem", "(", "pem_bundle", ")", ":", "# Normalize the PEM bundle's line endings.", "pem_bundle", "=", "pem_bundle", ".", "replace", "(", "b\"\\r\\n\"", ",", "b\"\\n\"", ")", "der_certs", "=", "[", "base64", ".", "b64decode", "(", "match", ".", "group", "(", "1", ")", ")", "for", "match", "in", "_PEM_CERTS_RE", ".", "finditer", "(", "pem_bundle", ")", "]", "if", "not", "der_certs", ":", "raise", "ssl", ".", "SSLError", "(", "\"No root certificates specified\"", ")", "cert_array", "=", "CoreFoundation", ".", "CFArrayCreateMutable", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "0", ",", "ctypes", ".", "byref", "(", "CoreFoundation", ".", "kCFTypeArrayCallBacks", ")", ")", "if", "not", "cert_array", ":", "raise", "ssl", ".", "SSLError", "(", "\"Unable to allocate memory!\"", ")", "try", ":", "for", "der_bytes", "in", "der_certs", ":", "certdata", "=", "_cf_data_from_bytes", "(", "der_bytes", ")", "if", "not", "certdata", ":", "raise", "ssl", ".", "SSLError", "(", "\"Unable to allocate memory!\"", ")", "cert", "=", "Security", ".", "SecCertificateCreateWithData", "(", "CoreFoundation", ".", "kCFAllocatorDefault", ",", "certdata", ")", "CoreFoundation", ".", "CFRelease", "(", "certdata", ")", "if", "not", "cert", ":", "raise", "ssl", ".", "SSLError", "(", "\"Unable to build cert object!\"", ")", "CoreFoundation", ".", "CFArrayAppendValue", "(", "cert_array", ",", "cert", ")", "CoreFoundation", ".", "CFRelease", "(", "cert", ")", "except", "Exception", ":", "# We need to free the array before the exception bubbles further.", "# We only want to do that if an error occurs: otherwise, the caller", "# should free.", "CoreFoundation", ".", "CFRelease", "(", "cert_array", ")", "return", "cert_array" ]
Rebuilds the current item in day mode .
def rebuildDay ( self ) : scene = self . scene ( ) if ( not scene ) : return # calculate the base information start_date = self . dateStart ( ) end_date = self . dateEnd ( ) min_date = scene . minimumDate ( ) max_date = scene . maximumDate ( ) # make sure our item is visible if ( not ( min_date <= end_date and start_date <= max_date ) ) : self . hide ( ) self . setPath ( QPainterPath ( ) ) return # make sure we have valid range information if ( start_date < min_date ) : start_date = min_date start_inrange = False else : start_inrange = True if ( max_date < end_date ) : end_date = max_date end_inrange = False else : end_inrange = True # rebuild the path path = QPainterPath ( ) self . setPos ( 0 , 0 ) pad = 2 offset = 18 height = 16 # rebuild a timed item if ( not self . isAllDay ( ) ) : start_dtime = QDateTime ( self . dateStart ( ) , self . timeStart ( ) ) end_dtime = QDateTime ( self . dateStart ( ) , self . timeEnd ( ) . addSecs ( - 30 * 60 ) ) start_rect = scene . dateTimeRect ( start_dtime ) end_rect = scene . dateTimeRect ( end_dtime ) left = start_rect . left ( ) + pad top = start_rect . top ( ) + pad right = start_rect . right ( ) - pad bottom = end_rect . bottom ( ) - pad path . moveTo ( left , top ) path . lineTo ( right , top ) path . lineTo ( right , bottom ) path . lineTo ( left , bottom ) path . lineTo ( left , top ) data = ( left + 6 , top + 6 , right - left - 12 , bottom - top - 12 , Qt . AlignTop | Qt . AlignLeft , '%s - %s\n(%s)' % ( self . timeStart ( ) . toString ( 'h:mmap' ) [ : - 1 ] , self . timeEnd ( ) . toString ( 'h:mmap' ) , self . title ( ) ) ) self . _textData . append ( data ) self . setPath ( path ) self . show ( )
11,459
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xcalendarwidget/xcalendaritem.py#L261-L334
[ "def", "certify_int", "(", "value", ",", "min_value", "=", "None", ",", "max_value", "=", "None", ",", "required", "=", "True", ")", ":", "certify_params", "(", "(", "_certify_int_param", ",", "'max_length'", ",", "max_value", ",", "dict", "(", "negative", "=", "True", ",", "required", "=", "False", ")", ")", ",", "(", "_certify_int_param", ",", "'min_length'", ",", "min_value", ",", "dict", "(", "negative", "=", "True", ",", "required", "=", "False", ")", ")", ",", ")", "if", "certify_required", "(", "value", "=", "value", ",", "required", "=", "required", ",", ")", ":", "return", "if", "not", "isinstance", "(", "value", ",", "six", ".", "integer_types", ")", ":", "raise", "CertifierTypeError", "(", "message", "=", "\"expected integer, but value is of type {cls!r}\"", ".", "format", "(", "cls", "=", "value", ".", "__class__", ".", "__name__", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", "if", "min_value", "is", "not", "None", "and", "value", "<", "min_value", ":", "raise", "CertifierValueError", "(", "message", "=", "\"{value} is less than minimum acceptable {min}\"", ".", "format", "(", "value", "=", "value", ",", "min", "=", "min_value", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")", "if", "max_value", "is", "not", "None", "and", "value", ">", "max_value", ":", "raise", "CertifierValueError", "(", "message", "=", "\"{value} is more than the maximum acceptable {max}\"", ".", "format", "(", "value", "=", "value", ",", "max", "=", "max_value", ")", ",", "value", "=", "value", ",", "required", "=", "required", ",", ")" ]
Validates the page against the scaffold information setting the values along the way .
def validatePage ( self ) : widgets = self . propertyWidgetMap ( ) failed = '' for prop , widget in widgets . items ( ) : val , success = projexui . widgetValue ( widget ) if success : # ensure we have the required values if not val and not ( prop . type == 'bool' and val is False ) : if prop . default : val = prop . default elif prop . required : msg = '{0} is a required value' . format ( prop . label ) failed = msg break # ensure the values match the required expression elif prop . regex and not re . match ( prop . regex , nativestring ( val ) ) : msg = '{0} needs to be in the format {1}' . format ( prop . label , prop . regex ) failed = msg break prop . value = val else : msg = 'Failed to get a proper value for {0}' . format ( prop . label ) failed = msg break if failed : QtGui . QMessageBox . warning ( None , 'Properties Failed' , failed ) return False return True
11,460
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L166-L203
[ "def", "register_adapter", "(", "from_classes", ",", "to_classes", ",", "func", ")", ":", "assert", "from_classes", ",", "'Must supply classes to adapt from'", "assert", "to_classes", ",", "'Must supply classes to adapt to'", "assert", "func", ",", "'Must supply adapter function'", "if", "not", "isinstance", "(", "from_classes", ",", "(", "tuple", ",", "list", ")", ")", ":", "from_classes", "=", "[", "from_classes", "]", "if", "not", "isinstance", "(", "to_classes", ",", "(", "tuple", ",", "list", ")", ")", ":", "to_classes", "=", "[", "to_classes", "]", "for", "key", "in", "itertools", ".", "product", "(", "from_classes", ",", "to_classes", ")", ":", "if", "key", "in", "__adapters__", ":", "raise", "AdapterExists", "(", "'%r to %r already exists.'", "%", "key", ")", "__adapters__", "[", "key", "]", "=", "func" ]
Saves the state for this item to the scaffold .
def save ( self ) : enabled = self . checkState ( 0 ) == QtCore . Qt . Checked self . _element . set ( 'name' , nativestring ( self . text ( 0 ) ) ) self . _element . set ( 'enabled' , nativestring ( enabled ) ) for child in self . children ( ) : child . save ( )
11,461
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L241-L250
[ "def", "on_websocket_message", "(", "message", ":", "str", ")", "->", "None", ":", "msgs", "=", "json", ".", "loads", "(", "message", ")", "for", "msg", "in", "msgs", ":", "if", "not", "isinstance", "(", "msg", ",", "dict", ")", ":", "logger", ".", "error", "(", "'Invalid WS message format: {}'", ".", "format", "(", "message", ")", ")", "continue", "_type", "=", "msg", ".", "get", "(", "'type'", ")", "if", "_type", "==", "'log'", ":", "log_handler", "(", "msg", "[", "'level'", "]", ",", "msg", "[", "'message'", "]", ")", "elif", "_type", "==", "'event'", ":", "event_handler", "(", "msg", "[", "'event'", "]", ")", "elif", "_type", "==", "'response'", ":", "response_handler", "(", "msg", ")", "else", ":", "raise", "ValueError", "(", "'Unkown message type: {}'", ".", "format", "(", "message", ")", ")" ]
Updates this item based on the interface .
def update ( self , enabled = None ) : if enabled is None : enabled = self . checkState ( 0 ) == QtCore . Qt . Checked elif not enabled or self . _element . get ( 'enabled' , 'True' ) != 'True' : self . setCheckState ( 0 , QtCore . Qt . Unchecked ) else : self . setCheckState ( 0 , QtCore . Qt . Checked ) if enabled : self . setForeground ( 0 , QtGui . QBrush ( ) ) else : self . setForeground ( 0 , QtGui . QBrush ( QtGui . QColor ( 'lightGray' ) ) ) for child in self . children ( ) : child . update ( enabled )
11,462
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L252-L269
[ "def", "on_start", "(", "self", ",", "session", ",", "session_context", ")", ":", "session_id", "=", "session", ".", "session_id", "web_registry", "=", "session_context", "[", "'web_registry'", "]", "if", "self", ".", "is_session_id_cookie_enabled", ":", "web_registry", ".", "session_id", "=", "session_id", "logger", ".", "debug", "(", "\"Set SessionID cookie using id: \"", "+", "str", "(", "session_id", ")", ")", "else", ":", "msg", "=", "(", "\"Session ID cookie is disabled. No cookie has been set for \"", "\"new session with id: \"", "+", "str", "(", "session_id", ")", ")", "logger", ".", "debug", "(", "msg", ")" ]
Initializes the page based on the current structure information .
def initializePage ( self ) : tree = self . uiStructureTREE tree . blockSignals ( True ) tree . setUpdatesEnabled ( False ) self . uiStructureTREE . clear ( ) xstruct = self . scaffold ( ) . structure ( ) self . _structure = xstruct for xentry in xstruct : XScaffoldElementItem ( tree , xentry ) tree . blockSignals ( False ) tree . setUpdatesEnabled ( True )
11,463
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L290-L305
[ "def", "_login", "(", "self", ",", "username", ",", "password", ")", ":", "data", "=", "{", "'username'", ":", "username", ",", "'password'", ":", "password", ",", "'grant_type'", ":", "'password'", "}", "r", "=", "self", ".", "spark_api", ".", "oauth", ".", "token", ".", "POST", "(", "auth", "=", "(", "'spark'", ",", "'spark'", ")", ",", "data", "=", "data", ",", "timeout", "=", "self", ".", "timeout", ")", "self", ".", "_check_error", "(", "r", ")", "return", "r", ".", "json", "(", ")", "[", "'access_token'", "]" ]
Finishes up the structure information for this wizard by building the scaffold .
def validatePage ( self ) : path = self . uiOutputPATH . filepath ( ) for item in self . uiStructureTREE . topLevelItems ( ) : item . save ( ) try : self . scaffold ( ) . build ( path , self . _structure ) except Exception , err : QtGui . QMessageBox . critical ( None , 'Error Occurred' , nativestring ( err ) ) return False return True
11,464
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/wizards/xscaffoldwizard/xscaffoldwizard.py#L315-L331
[ "def", "incoming_messages", "(", "self", ")", "->", "t", ".", "List", "[", "t", ".", "Tuple", "[", "float", ",", "bytes", "]", "]", ":", "approximate_messages", "=", "self", ".", "_receive_buffer", ".", "qsize", "(", ")", "messages", "=", "[", "]", "for", "_", "in", "range", "(", "approximate_messages", ")", ":", "try", ":", "messages", ".", "append", "(", "self", ".", "_receive_buffer", ".", "get_nowait", "(", ")", ")", "except", "queue", ".", "Empty", ":", "break", "return", "messages" ]
Clears out all the child widgets from this widget and creates the widget that best matches the column properties for this edit .
def rebuild ( self ) : plugins . init ( ) self . blockSignals ( True ) self . setUpdatesEnabled ( False ) # clear the old editor if ( self . _editor ) : self . _editor . close ( ) self . _editor . setParent ( None ) self . _editor . deleteLater ( ) self . _editor = None # create a new widget plugin_class = plugins . widgets . get ( self . _columnType ) if ( plugin_class ) : self . _editor = plugin_class ( self ) self . layout ( ) . addWidget ( self . _editor ) self . blockSignals ( False ) self . setUpdatesEnabled ( True )
11,465
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xorbcolumnedit/xorbcolumnedit.py#L120-L144
[ "def", "randoffset", "(", "self", ",", "rstate", "=", "None", ")", ":", "if", "rstate", "is", "None", ":", "rstate", "=", "np", ".", "random", "return", "np", ".", "dot", "(", "self", ".", "axes", ",", "randsphere", "(", "self", ".", "n", ",", "rstate", "=", "rstate", ")", ")" ]
Closes the current contents widget .
def closeContentsWidget ( self ) : widget = self . currentContentsWidget ( ) if ( not widget ) : return widget . close ( ) widget . setParent ( None ) widget . deleteLater ( )
11,466
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L246-L256
[ "def", "process", "(", "self", ")", ":", "subscription", "=", "None", "result", "=", "None", "try", ":", "subscription", "=", "self", ".", "socket", ".", "recv", "(", ")", "except", "AuthenticateError", "as", "exception", ":", "logging", ".", "error", "(", "'Subscriber error while authenticating request: {}'", ".", "format", "(", "exception", ")", ",", "exc_info", "=", "1", ")", "except", "AuthenticatorInvalidSignature", "as", "exception", ":", "logging", ".", "error", "(", "'Subscriber error while authenticating request: {}'", ".", "format", "(", "exception", ")", ",", "exc_info", "=", "1", ")", "except", "DecodeError", "as", "exception", ":", "logging", ".", "error", "(", "'Subscriber error while decoding request: {}'", ".", "format", "(", "exception", ")", ",", "exc_info", "=", "1", ")", "except", "RequestParseError", "as", "exception", ":", "logging", ".", "error", "(", "'Subscriber error while parsing request: {}'", ".", "format", "(", "exception", ")", ",", "exc_info", "=", "1", ")", "else", ":", "logging", ".", "debug", "(", "'Subscriber received payload: {}'", ".", "format", "(", "subscription", ")", ")", "_tag", ",", "message", ",", "fun", "=", "self", ".", "parse", "(", "subscription", ")", "message", "=", "self", ".", "verify", "(", "message", ")", "message", "=", "self", ".", "decode", "(", "message", ")", "try", ":", "result", "=", "fun", "(", "message", ")", "except", "Exception", "as", "exception", ":", "logging", ".", "error", "(", "exception", ",", "exc_info", "=", "1", ")", "# Return result to check successful execution of `fun` when testing", "return", "result" ]
Copies the selected text to the clipboard .
def copyText ( self ) : view = self . currentWebView ( ) QApplication . clipboard ( ) . setText ( view . page ( ) . selectedText ( ) )
11,467
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L258-L263
[ "def", "ValidateEndConfig", "(", "self", ",", "config_obj", ",", "errors_fatal", "=", "True", ")", ":", "errors", "=", "super", "(", "WindowsClientRepacker", ",", "self", ")", ".", "ValidateEndConfig", "(", "config_obj", ",", "errors_fatal", "=", "errors_fatal", ")", "install_dir", "=", "config_obj", "[", "\"Client.install_path\"", "]", "for", "path", "in", "config_obj", "[", "\"Client.tempdir_roots\"", "]", ":", "if", "path", ".", "startswith", "(", "\"/\"", ")", ":", "errors", ".", "append", "(", "\"Client.tempdir_root %s starts with /, probably has Unix path.\"", "%", "path", ")", "if", "not", "path", ".", "startswith", "(", "install_dir", ")", ":", "errors", ".", "append", "(", "\"Client.tempdir_root %s is not inside the install_dir %s, this is \"", "\"a security risk\"", "%", "(", "(", "path", ",", "install_dir", ")", ")", ")", "if", "config_obj", ".", "Get", "(", "\"Logging.path\"", ")", ".", "startswith", "(", "\"/\"", ")", ":", "errors", ".", "append", "(", "\"Logging.path starts with /, probably has Unix path. %s\"", "%", "config_obj", "[", "\"Logging.path\"", "]", ")", "if", "\"Windows\\\\\"", "in", "config_obj", ".", "GetRaw", "(", "\"Logging.path\"", ")", ":", "errors", ".", "append", "(", "\"Windows in Logging.path, you probably want \"", "\"%(WINDIR|env) instead\"", ")", "if", "not", "config_obj", "[", "\"Client.binary_name\"", "]", ".", "endswith", "(", "\".exe\"", ")", ":", "errors", ".", "append", "(", "\"Missing .exe extension on binary_name %s\"", "%", "config_obj", "[", "\"Client.binary_name\"", "]", ")", "if", "not", "config_obj", "[", "\"Nanny.binary\"", "]", ".", "endswith", "(", "\".exe\"", ")", ":", "errors", ".", "append", "(", "\"Missing .exe extension on nanny_binary\"", ")", "if", "errors_fatal", "and", "errors", ":", "for", "error", "in", "errors", ":", "logging", ".", "error", "(", "\"Build Config Error: %s\"", ",", "error", ")", "raise", "RuntimeError", "(", "\"Bad configuration generated. Terminating.\"", ")", "else", ":", "return", "errors" ]
Looks for the previous occurance of the current search text .
def findPrev ( self ) : text = self . uiFindTXT . text ( ) view = self . currentWebView ( ) options = QWebPage . FindWrapsAroundDocument options |= QWebPage . FindBackward if ( self . uiCaseSensitiveCHK . isChecked ( ) ) : options |= QWebPage . FindCaseSensitively view . page ( ) . findText ( text , options )
11,468
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L322-L335
[ "def", "_dmi_cast", "(", "key", ",", "val", ",", "clean", "=", "True", ")", ":", "if", "clean", "and", "not", "_dmi_isclean", "(", "key", ",", "val", ")", ":", "return", "elif", "not", "re", ".", "match", "(", "r'serial|part|asset|product'", ",", "key", ",", "flags", "=", "re", ".", "IGNORECASE", ")", ":", "if", "','", "in", "val", ":", "val", "=", "[", "el", ".", "strip", "(", ")", "for", "el", "in", "val", ".", "split", "(", "','", ")", "]", "else", ":", "try", ":", "val", "=", "int", "(", "val", ")", "except", "Exception", ":", "pass", "return", "val" ]
Refreshes the documentation from the selected index item .
def refreshFromIndex ( self ) : item = self . uiIndexTREE . currentItem ( ) if ( not item ) : return self . gotoUrl ( item . toolTip ( 0 ) )
11,469
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L455-L463
[ "def", "pspawn_wrapper", "(", "self", ",", "sh", ",", "escape", ",", "cmd", ",", "args", ",", "env", ")", ":", "return", "self", ".", "pspawn", "(", "sh", ",", "escape", ",", "cmd", ",", "args", ",", "env", ",", "self", ".", "logstream", ",", "self", ".", "logstream", ")" ]
Refreshes the contents tab with the latest selection from the browser .
def refreshContents ( self ) : item = self . uiContentsTREE . currentItem ( ) if not isinstance ( item , XdkEntryItem ) : return item . load ( ) url = item . url ( ) if url : self . gotoUrl ( url )
11,470
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L465-L476
[ "def", "from_parameter", "(", "cls", ":", "Type", "[", "XHXParameterType", "]", ",", "parameter", ":", "str", ")", "->", "Optional", "[", "XHXParameterType", "]", ":", "xhx", "=", "XHXParameter", ".", "re_xhx", ".", "match", "(", "parameter", ")", "if", "xhx", ":", "return", "cls", "(", "int", "(", "xhx", ".", "group", "(", "1", ")", ")", ")", "return", "None" ]
Refreshes the interface based on the current settings .
def refreshUi ( self ) : widget = self . uiContentsTAB . currentWidget ( ) is_content = isinstance ( widget , QWebView ) if is_content : self . _currentContentsIndex = self . uiContentsTAB . currentIndex ( ) history = widget . page ( ) . history ( ) else : history = None self . uiBackACT . setEnabled ( is_content and history . canGoBack ( ) ) self . uiForwardACT . setEnabled ( is_content and history . canGoForward ( ) ) self . uiHomeACT . setEnabled ( is_content ) self . uiNewTabACT . setEnabled ( is_content ) self . uiCopyTextACT . setEnabled ( is_content ) self . uiCloseTabACT . setEnabled ( is_content and self . uiContentsTAB . count ( ) > 2 ) for i in range ( 1 , self . uiContentsTAB . count ( ) ) : widget = self . uiContentsTAB . widget ( i ) self . uiContentsTAB . setTabText ( i , widget . title ( ) )
11,471
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L478-L501
[ "def", "batchlobstr", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "batchlobstr", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--sep\"", ",", "default", "=", "\",\"", ",", "help", "=", "\"Separator for building commandline\"", ")", "p", ".", "set_home", "(", "\"lobstr\"", ",", "default", "=", "\"s3://hli-mv-data-science/htang/str-build/lobSTR/\"", ")", "p", ".", "set_aws_opts", "(", "store", "=", "\"hli-mv-data-science/htang/str-data\"", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "not", "p", ".", "print_help", "(", ")", ")", "samplesfile", ",", "=", "args", "store", "=", "opts", ".", "output_path", "computed", "=", "ls_s3", "(", "store", ")", "fp", "=", "open", "(", "samplesfile", ")", "skipped", "=", "total", "=", "0", "for", "row", "in", "fp", ":", "total", "+=", "1", "sample", ",", "s3file", "=", "row", ".", "strip", "(", ")", ".", "split", "(", "\",\"", ")", "[", ":", "2", "]", "exec_id", ",", "sample_id", "=", "sample", ".", "split", "(", "\"_\"", ")", "bamfile", "=", "s3file", ".", "replace", "(", "\".gz\"", ",", "\"\"", ")", ".", "replace", "(", "\".vcf\"", ",", "\".bam\"", ")", "gzfile", "=", "sample", "+", "\".{0}.vcf.gz\"", ".", "format", "(", "\"hg38\"", ")", "if", "gzfile", "in", "computed", ":", "skipped", "+=", "1", "continue", "print", "(", "opts", ".", "sep", ".", "join", "(", "\"python -m jcvi.variation.str lobstr\"", ".", "split", "(", ")", "+", "[", "\"hg38\"", ",", "\"--input_bam_path\"", ",", "bamfile", ",", "\"--output_path\"", ",", "store", ",", "\"--sample_id\"", ",", "sample_id", ",", "\"--workflow_execution_id\"", ",", "exec_id", ",", "\"--lobstr_home\"", ",", "opts", ".", "lobstr_home", ",", "\"--workdir\"", ",", "opts", ".", "workdir", "]", ")", ")", "fp", ".", "close", "(", ")", "logging", ".", "debug", "(", "\"Total skipped: {0}\"", ".", "format", "(", "percentage", "(", "skipped", ",", "total", ")", ")", ")" ]
Looks up the current search terms from the xdk files that are loaded .
def search ( self ) : QApplication . instance ( ) . setOverrideCursor ( Qt . WaitCursor ) terms = nativestring ( self . uiSearchTXT . text ( ) ) html = [ ] entry_html = '<a href="%(url)s">%(title)s</a><br/>' '<small>%(url)s</small>' for i in range ( self . uiContentsTREE . topLevelItemCount ( ) ) : item = self . uiContentsTREE . topLevelItem ( i ) results = item . search ( terms ) results . sort ( lambda x , y : cmp ( y [ 'strength' ] , x [ 'strength' ] ) ) for item in results : html . append ( entry_html % item ) if ( not html ) : html . append ( '<b>No results were found for %s</b>' % terms ) self . uiSearchWEB . setHtml ( SEARCH_HTML % '<br/><br/>' . join ( html ) ) QApplication . instance ( ) . restoreOverrideCursor ( )
11,472
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/windows/xdkwindow/xdkwindow.py#L503-L529
[ "def", "communityvisibilitystate", "(", "self", ")", ":", "if", "self", ".", "_communityvisibilitystate", "==", "None", ":", "return", "None", "elif", "self", ".", "_communityvisibilitystate", "in", "self", ".", "VisibilityState", ":", "return", "self", ".", "VisibilityState", "[", "self", ".", "_communityvisibilitystate", "]", "else", ":", "#Invalid State", "return", "None" ]
Removes all entries from the config map
def clear ( self ) : self . _pb . IntMap . clear ( ) self . _pb . StringMap . clear ( ) self . _pb . FloatMap . clear ( ) self . _pb . BoolMap . clear ( )
11,473
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L129-L134
[ "def", "indication", "(", "self", ",", "apdu", ")", ":", "if", "_debug", ":", "ServerSSM", ".", "_debug", "(", "\"indication %r\"", ",", "apdu", ")", "if", "self", ".", "state", "==", "IDLE", ":", "self", ".", "idle", "(", "apdu", ")", "elif", "self", ".", "state", "==", "SEGMENTED_REQUEST", ":", "self", ".", "segmented_request", "(", "apdu", ")", "elif", "self", ".", "state", "==", "AWAIT_RESPONSE", ":", "self", ".", "await_response", "(", "apdu", ")", "elif", "self", ".", "state", "==", "SEGMENTED_RESPONSE", ":", "self", ".", "segmented_response", "(", "apdu", ")", "else", ":", "if", "_debug", ":", "ServerSSM", ".", "_debug", "(", "\" - invalid state\"", ")" ]
Returns a list of ConfigMap keys .
def keys ( self ) : return ( list ( self . _pb . IntMap . keys ( ) ) + list ( self . _pb . StringMap . keys ( ) ) + list ( self . _pb . FloatMap . keys ( ) ) + list ( self . _pb . BoolMap . keys ( ) ) )
11,474
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L159-L162
[ "def", "_sumterm_prime", "(", "lexer", ")", ":", "tok", "=", "next", "(", "lexer", ")", "# '|' XORTERM SUMTERM'", "if", "isinstance", "(", "tok", ",", "OP_or", ")", ":", "xorterm", "=", "_xorterm", "(", "lexer", ")", "sumterm_prime", "=", "_sumterm_prime", "(", "lexer", ")", "if", "sumterm_prime", "is", "None", ":", "return", "xorterm", "else", ":", "return", "(", "'or'", ",", "xorterm", ",", "sumterm_prime", ")", "# null", "else", ":", "lexer", ".", "unpop_token", "(", "tok", ")", "return", "None" ]
Returns a list of ConfigMap values .
def values ( self ) : return ( list ( self . _pb . IntMap . values ( ) ) + list ( self . _pb . StringMap . values ( ) ) + list ( self . _pb . FloatMap . values ( ) ) + list ( self . _pb . BoolMap . values ( ) ) )
11,475
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L164-L167
[ "def", "indication", "(", "self", ",", "apdu", ")", ":", "if", "_debug", ":", "ServerSSM", ".", "_debug", "(", "\"indication %r\"", ",", "apdu", ")", "if", "self", ".", "state", "==", "IDLE", ":", "self", ".", "idle", "(", "apdu", ")", "elif", "self", ".", "state", "==", "SEGMENTED_REQUEST", ":", "self", ".", "segmented_request", "(", "apdu", ")", "elif", "self", ".", "state", "==", "AWAIT_RESPONSE", ":", "self", ".", "await_response", "(", "apdu", ")", "elif", "self", ".", "state", "==", "SEGMENTED_RESPONSE", ":", "self", ".", "segmented_response", "(", "apdu", ")", "else", ":", "if", "_debug", ":", "ServerSSM", ".", "_debug", "(", "\" - invalid state\"", ")" ]
Returns an iterator over the items of ConfigMap .
def iteritems ( self ) : return chain ( self . _pb . StringMap . items ( ) , self . _pb . IntMap . items ( ) , self . _pb . FloatMap . items ( ) , self . _pb . BoolMap . items ( ) )
11,476
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L169-L174
[ "def", "require_session", "(", "handler", ")", ":", "@", "functools", ".", "wraps", "(", "handler", ")", "async", "def", "decorated", "(", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "request_session_token", "=", "request", ".", "match_info", "[", "'session'", "]", "session", "=", "session_from_request", "(", "request", ")", "if", "not", "session", "or", "request_session_token", "!=", "session", ".", "token", ":", "LOG", ".", "warning", "(", "f\"request for invalid session {request_session_token}\"", ")", "return", "web", ".", "json_response", "(", "data", "=", "{", "'error'", ":", "'bad-token'", ",", "'message'", ":", "f'No such session {request_session_token}'", "}", ",", "status", "=", "404", ")", "return", "await", "handler", "(", "request", ",", "session", ")", "return", "decorated" ]
Returns an iterator over the values of ConfigMap .
def itervalues ( self ) : return chain ( self . _pb . StringMap . values ( ) , self . _pb . IntMap . values ( ) , self . _pb . FloatMap . values ( ) , self . _pb . BoolMap . values ( ) )
11,477
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L176-L181
[ "def", "search_for_port", "(", "port_glob", ",", "req", ",", "expected_res", ")", ":", "# Check that the USB port actually exists, based on the known vendor and", "# product ID.", "if", "usb", ".", "core", ".", "find", "(", "idVendor", "=", "0x0403", ",", "idProduct", "=", "0x6001", ")", "is", "None", ":", "return", "None", "# Find ports matching the supplied glob.", "ports", "=", "glob", ".", "glob", "(", "port_glob", ")", "if", "len", "(", "ports", ")", "==", "0", ":", "return", "None", "for", "port", "in", "ports", ":", "with", "r12_serial_port", "(", "port", ")", "as", "ser", ":", "if", "not", "ser", ".", "isOpen", "(", ")", ":", "ser", ".", "open", "(", ")", "# Write a request out.", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "ser", ".", "write", "(", "str", "(", "req", ")", ".", "encode", "(", "'utf-8'", ")", ")", "else", ":", "ser", ".", "write", "(", "bytes", "(", "req", ",", "'utf-8'", ")", ")", "# Wait a short period to allow the connection to generate output.", "time", ".", "sleep", "(", "0.1", ")", "# Read output from the serial connection check if it's what we want.", "res", "=", "ser", ".", "read", "(", "ser", ".", "in_waiting", ")", ".", "decode", "(", "OUTPUT_ENCODING", ")", "if", "expected_res", "in", "res", ":", "return", "port", "raise", "ArmException", "(", "'ST Robotics connection found, but is not responsive.'", "+", "' Is the arm powered on?'", ")", "return", "None" ]
Returns an iterator over the keys of ConfigMap .
def iterkeys ( self ) : return chain ( self . _pb . StringMap . keys ( ) , self . _pb . IntMap . keys ( ) , self . _pb . FloatMap . keys ( ) , self . _pb . BoolMap . keys ( ) )
11,478
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L183-L188
[ "def", "validate", "(", "request_schema", "=", "None", ",", "response_schema", "=", "None", ")", ":", "def", "wrapper", "(", "func", ")", ":", "# Validating the schemas itself.", "# Die with exception if they aren't valid", "if", "request_schema", "is", "not", "None", ":", "_request_schema_validator", "=", "validator_for", "(", "request_schema", ")", "_request_schema_validator", ".", "check_schema", "(", "request_schema", ")", "if", "response_schema", "is", "not", "None", ":", "_response_schema_validator", "=", "validator_for", "(", "response_schema", ")", "_response_schema_validator", ".", "check_schema", "(", "response_schema", ")", "@", "asyncio", ".", "coroutine", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ")", ":", "if", "asyncio", ".", "iscoroutinefunction", "(", "func", ")", ":", "coro", "=", "func", "else", ":", "coro", "=", "asyncio", ".", "coroutine", "(", "func", ")", "# Supports class based views see web.View", "if", "isinstance", "(", "args", "[", "0", "]", ",", "AbstractView", ")", ":", "class_based", "=", "True", "request", "=", "args", "[", "0", "]", ".", "request", "else", ":", "class_based", "=", "False", "request", "=", "args", "[", "-", "1", "]", "# Strictly expect json object here", "try", ":", "req_body", "=", "yield", "from", "request", ".", "json", "(", ")", "except", "(", "json", ".", "decoder", ".", "JSONDecodeError", ",", "TypeError", ")", ":", "_raise_exception", "(", "web", ".", "HTTPBadRequest", ",", "\"Request is malformed; could not decode JSON object.\"", ")", "# Validate request data against request schema (if given)", "if", "request_schema", "is", "not", "None", ":", "_validate_data", "(", "req_body", ",", "request_schema", ",", "_request_schema_validator", ")", "coro_args", "=", "req_body", ",", "request", "if", "class_based", ":", "coro_args", "=", "(", "args", "[", "0", "]", ",", ")", "+", "coro_args", "context", "=", "yield", "from", "coro", "(", "*", "coro_args", ")", "# No validation of response for websockets stream", "if", "isinstance", "(", "context", ",", "web", ".", "StreamResponse", ")", ":", "return", "context", "# Validate response data against response schema (if given)", "if", "response_schema", "is", "not", "None", ":", "_validate_data", "(", "context", ",", "response_schema", ",", "_response_schema_validator", ")", "try", ":", "return", "web", ".", "json_response", "(", "context", ")", "except", "(", "TypeError", ",", ")", ":", "_raise_exception", "(", "web", ".", "HTTPInternalServerError", ",", "\"Response is malformed; could not encode JSON object.\"", ")", "# Store schemas in wrapped handlers, so it later can be reused", "setattr", "(", "wrapped", ",", "\"_request_schema\"", ",", "request_schema", ")", "setattr", "(", "wrapped", ",", "\"_response_schema\"", ",", "response_schema", ")", "return", "wrapped", "return", "wrapper" ]
Remove specified key and return the corresponding value . If key is not found default is returned if given otherwise KeyError is raised .
def pop ( self , key , default = None ) : if key not in self : if default is not None : return default raise KeyError ( key ) for map in [ self . _pb . IntMap , self . _pb . FloatMap , self . _pb . StringMap , self . _pb . BoolMap ] : if key in map . keys ( ) : return map . pop ( key )
11,479
https://github.com/intelsdi-x/snap-plugin-lib-py/blob/8da5d00ac5f9d2b48a7239563ac7788209891ca4/snap_plugin/v1/config_map.py#L195-L207
[ "def", "_write_header", "(", "self", ")", ":", "self", ".", "_ostream", ".", "write", "(", "len", "(", "self", ".", "_header", ")", "*", "\"-\"", "+", "\"\\n\"", ")", "self", ".", "_ostream", ".", "write", "(", "self", ".", "_header", ")", "self", ".", "_ostream", ".", "write", "(", "\"\\n\"", ")", "self", ".", "_ostream", ".", "write", "(", "len", "(", "self", ".", "_header", ")", "*", "\"-\"", "+", "\"\\n\"", ")" ]
Interrupts the current database from processing .
def interrupt ( self ) : if self . _database and self . _databaseThreadId : # support Orb 2 interruption capabilities try : self . _database . interrupt ( self . _databaseThreadId ) except AttributeError : pass self . _database = None self . _databaseThreadId = 0
11,480
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xorbworker.py#L121-L133
[ "def", "configure", "(", "self", ",", "voltage_range", "=", "RANGE_32V", ",", "gain", "=", "GAIN_AUTO", ",", "bus_adc", "=", "ADC_12BIT", ",", "shunt_adc", "=", "ADC_12BIT", ")", ":", "self", ".", "__validate_voltage_range", "(", "voltage_range", ")", "self", ".", "_voltage_range", "=", "voltage_range", "if", "self", ".", "_max_expected_amps", "is", "not", "None", ":", "if", "gain", "==", "self", ".", "GAIN_AUTO", ":", "self", ".", "_auto_gain_enabled", "=", "True", "self", ".", "_gain", "=", "self", ".", "_determine_gain", "(", "self", ".", "_max_expected_amps", ")", "else", ":", "self", ".", "_gain", "=", "gain", "else", ":", "if", "gain", "!=", "self", ".", "GAIN_AUTO", ":", "self", ".", "_gain", "=", "gain", "else", ":", "self", ".", "_auto_gain_enabled", "=", "True", "self", ".", "_gain", "=", "self", ".", "GAIN_1_40MV", "logging", ".", "info", "(", "'gain set to %.2fV'", "%", "self", ".", "__GAIN_VOLTS", "[", "self", ".", "_gain", "]", ")", "logging", ".", "debug", "(", "self", ".", "__LOG_MSG_1", "%", "(", "self", ".", "_shunt_ohms", ",", "self", ".", "__BUS_RANGE", "[", "voltage_range", "]", ",", "self", ".", "__GAIN_VOLTS", "[", "self", ".", "_gain", "]", ",", "self", ".", "__max_expected_amps_to_string", "(", "self", ".", "_max_expected_amps", ")", ",", "bus_adc", ",", "shunt_adc", ")", ")", "self", ".", "_calibrate", "(", "self", ".", "__BUS_RANGE", "[", "voltage_range", "]", ",", "self", ".", "__GAIN_VOLTS", "[", "self", ".", "_gain", "]", ",", "self", ".", "_max_expected_amps", ")", "self", ".", "_configure", "(", "voltage_range", ",", "self", ".", "_gain", ",", "bus_adc", ",", "shunt_adc", ")" ]
Processes the main thread until the loading process has finished . This is a way to force the main thread to be synchronous in its execution .
def waitUntilFinished ( self ) : QtCore . QCoreApplication . processEvents ( ) while self . isLoading ( ) : QtCore . QCoreApplication . processEvents ( )
11,481
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/xorbworker.py#L153-L160
[ "def", "SUB", "(", "classical_reg", ",", "right", ")", ":", "left", ",", "right", "=", "unpack_reg_val_pair", "(", "classical_reg", ",", "right", ")", "return", "ClassicalSub", "(", "left", ",", "right", ")" ]
Sets the current alignment for the editor .
def assignAlignment ( self , action ) : if self . _actions [ 'align_left' ] == action : self . setAlignment ( Qt . AlignLeft ) elif self . _actions [ 'align_right' ] == action : self . setAlignment ( Qt . AlignRight ) elif self . _actions [ 'align_center' ] == action : self . setAlignment ( Qt . AlignHCenter ) else : self . setAlignment ( Qt . AlignJustify )
11,482
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L165-L176
[ "def", "prune_feed_map", "(", "meta_graph", ",", "feed_map", ")", ":", "node_names", "=", "[", "x", ".", "name", "+", "\":0\"", "for", "x", "in", "meta_graph", ".", "graph_def", ".", "node", "]", "keys_to_delete", "=", "[", "]", "for", "k", ",", "_", "in", "feed_map", ".", "items", "(", ")", ":", "if", "k", "not", "in", "node_names", ":", "keys_to_delete", ".", "append", "(", "k", ")", "for", "k", "in", "keys_to_delete", ":", "del", "feed_map", "[", "k", "]" ]
Assigns the font family and point size settings from the font picker widget .
def assignFont ( self ) : font = self . currentFont ( ) font . setFamily ( self . _fontPickerWidget . currentFamily ( ) ) font . setPointSize ( self . _fontPickerWidget . pointSize ( ) ) self . setCurrentFont ( font )
11,483
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L178-L186
[ "def", "compare_arrays", "(", "left", ",", "right", ")", ":", "return", "(", "left", "is", "right", "or", "(", "(", "left", ".", "shape", "==", "right", ".", "shape", ")", "and", "(", "left", "==", "right", ")", ".", "all", "(", ")", ")", ")" ]
Matches the UI state to the current cursor positioning .
def refreshUi ( self ) : font = self . currentFont ( ) for name in ( 'underline' , 'bold' , 'italic' , 'strikeOut' ) : getter = getattr ( font , name ) act = self . _actions [ name ] act . blockSignals ( True ) act . setChecked ( getter ( ) ) act . blockSignals ( False )
11,484
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L465-L476
[ "def", "delete", "(", "request", ",", "obj_id", "=", "None", ")", ":", "data", "=", "request", ".", "DELETE", "or", "json", ".", "loads", "(", "request", ".", "body", ")", "guids", "=", "data", ".", "get", "(", "'guids'", ")", ".", "split", "(", "','", ")", "objects", "=", "getObjectsFromGuids", "(", "guids", ")", "gallery", "=", "Gallery", ".", "objects", ".", "get", "(", "pk", "=", "obj_id", ")", "LOGGER", ".", "info", "(", "'{} removed {} from {}'", ".", "format", "(", "request", ".", "user", ".", "email", ",", "guids", ",", "gallery", ")", ")", "for", "o", "in", "objects", ":", "if", "isinstance", "(", "o", ",", "Image", ")", ":", "gallery", ".", "images", ".", "remove", "(", "o", ")", "elif", "isinstance", "(", "o", ",", "Video", ")", ":", "gallery", ".", "videos", ".", "remove", "(", "o", ")", "res", "=", "Result", "(", ")", "return", "JsonResponse", "(", "res", ".", "asDict", "(", ")", ")" ]
Refreshes the alignment UI information .
def refreshAlignmentUi ( self ) : align = self . alignment ( ) for name , value in ( ( 'align_left' , Qt . AlignLeft ) , ( 'align_right' , Qt . AlignRight ) , ( 'align_center' , Qt . AlignHCenter ) , ( 'align_justify' , Qt . AlignJustify ) ) : act = self . _actions [ name ] act . blockSignals ( True ) act . setChecked ( value == align ) act . blockSignals ( False )
11,485
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L478-L491
[ "def", "command_max_delay", "(", "self", ",", "event", "=", "None", ")", ":", "try", ":", "max_delay", "=", "self", ".", "max_delay_var", ".", "get", "(", ")", "except", "ValueError", ":", "max_delay", "=", "self", ".", "runtime_cfg", ".", "max_delay", "if", "max_delay", "<", "0", ":", "max_delay", "=", "self", ".", "runtime_cfg", ".", "max_delay", "if", "max_delay", ">", "0.1", ":", "max_delay", "=", "self", ".", "runtime_cfg", ".", "max_delay", "self", ".", "runtime_cfg", ".", "max_delay", "=", "max_delay", "self", ".", "max_delay_var", ".", "set", "(", "self", ".", "runtime_cfg", ".", "max_delay", ")" ]
Updates the font picker widget to the current font settings .
def updateFontPicker ( self ) : font = self . currentFont ( ) self . _fontPickerWidget . setPointSize ( font . pointSize ( ) ) self . _fontPickerWidget . setCurrentFamily ( font . family ( ) )
11,486
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xrichtextedit/xrichtextedit.py#L708-L714
[ "def", "generate_epochs_info", "(", "epoch_list", ")", ":", "time1", "=", "time", ".", "time", "(", ")", "epoch_info", "=", "[", "]", "for", "sid", ",", "epoch", "in", "enumerate", "(", "epoch_list", ")", ":", "for", "cond", "in", "range", "(", "epoch", ".", "shape", "[", "0", "]", ")", ":", "sub_epoch", "=", "epoch", "[", "cond", ",", ":", ",", ":", "]", "for", "eid", "in", "range", "(", "epoch", ".", "shape", "[", "1", "]", ")", ":", "r", "=", "np", ".", "sum", "(", "sub_epoch", "[", "eid", ",", ":", "]", ")", "if", "r", ">", "0", ":", "# there is an epoch in this condition", "start", "=", "np", ".", "nonzero", "(", "sub_epoch", "[", "eid", ",", ":", "]", ")", "[", "0", "]", "[", "0", "]", "epoch_info", ".", "append", "(", "(", "cond", ",", "sid", ",", "start", ",", "start", "+", "r", ")", ")", "time2", "=", "time", ".", "time", "(", ")", "logger", ".", "debug", "(", "'epoch separation done, takes %.2f s'", "%", "(", "time2", "-", "time1", ")", ")", "return", "epoch_info" ]
Starts dragging information from this chart widget based on the dragData associated with this item .
def startDrag ( self , data ) : if not data : return widget = self . scene ( ) . chartWidget ( ) drag = QDrag ( widget ) drag . setMimeData ( data ) drag . exec_ ( )
11,487
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xchartwidget/xchartwidgetitem.py#L740-L751
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Adjusts the margins to incorporate enough room for the widget s title and sub - title .
def adjustMargins ( self ) : y = 0 height = 0 if self . _titleLabel . text ( ) : height += self . _titleLabel . height ( ) + 3 y += height if self . _subTitleLabel . text ( ) : self . _subTitleLabel . move ( 0 , y ) height += self . _subTitleLabel . height ( ) + 3 self . setContentsMargins ( 0 , height , 0 , 0 )
11,488
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L45-L59
[ "def", "replicaStatus", "(", "self", ",", "url", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "url", "=", "url", "+", "\"/status\"", "return", "self", ".", "_get", "(", "url", "=", "url", ",", "param_dict", "=", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_port", "=", "self", ".", "_proxy_port", ",", "proxy_url", "=", "self", ".", "_proxy_url", ")" ]
Returns the next id for this page . By default it will provide the next id from the wizard but this method can be overloaded to create a custom path . If - 1 is returned then it will be considered the final page .
def nextId ( self ) : if self . _nextId is not None : return self . _nextId wizard = self . wizard ( ) curr_id = wizard . currentId ( ) all_ids = wizard . pageIds ( ) try : return all_ids [ all_ids . index ( curr_id ) + 1 ] except IndexError : return - 1
11,489
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L121-L138
[ "def", "checkIsConsistent", "(", "self", ")", ":", "if", "is_an_array", "(", "self", ".", "mask", ")", "and", "self", ".", "mask", ".", "shape", "!=", "self", ".", "data", ".", "shape", ":", "raise", "ConsistencyError", "(", "\"Shape mismatch mask={}, data={}\"", ".", "format", "(", "self", ".", "mask", ".", "shape", "!=", "self", ".", "data", ".", "shape", ")", ")" ]
Sets the sub - title for this page to the inputed title .
def setSubTitle ( self , title ) : self . _subTitleLabel . setText ( title ) self . _subTitleLabel . adjustSize ( ) self . adjustMargins ( )
11,490
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L174-L182
[ "def", "list_devices", "(", "connection", ":", "ForestConnection", "=", "None", ")", ":", "# For the record, the dictionary stored in \"devices\" that we're getting back is keyed on device", "# names and has this structure in its values:", "#", "# {", "# \"is_online\": a boolean indicating the availability of the device,", "# \"is_retuning\": a boolean indicating whether the device is busy retuning,", "# \"specs\": a Specs object describing the entire device, serialized as a dictionary,", "# \"isa\": an ISA object describing the entire device, serialized as a dictionary,", "# \"noise_model\": a NoiseModel object describing the entire device, serialized as a dictionary", "# }", "if", "connection", "is", "None", ":", "connection", "=", "ForestConnection", "(", ")", "session", "=", "connection", ".", "session", "url", "=", "connection", ".", "forest_cloud_endpoint", "+", "'/devices'", "return", "sorted", "(", "get_json", "(", "session", ",", "url", ")", "[", "\"devices\"", "]", ".", "keys", "(", ")", ")" ]
Sets the title for this page to the inputed title .
def setTitle ( self , title ) : self . _titleLabel . setText ( title ) self . _titleLabel . adjustSize ( ) self . adjustMargins ( )
11,491
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L192-L200
[ "def", "create_pgroup_snapshot", "(", "self", ",", "source", ",", "*", "*", "kwargs", ")", ":", "# In REST 1.4, support was added for snapshotting multiple pgroups. As a", "# result, the endpoint response changed from an object to an array of", "# objects. To keep the response type consistent between REST versions,", "# we unbox the response when creating a single snapshot.", "result", "=", "self", ".", "create_pgroup_snapshots", "(", "[", "source", "]", ",", "*", "*", "kwargs", ")", "if", "self", ".", "_rest_version", ">=", "LooseVersion", "(", "\"1.4\"", ")", ":", "headers", "=", "result", ".", "headers", "result", "=", "ResponseDict", "(", "result", "[", "0", "]", ")", "result", ".", "headers", "=", "headers", "return", "result" ]
Adjusts the size of this wizard and its page contents to the inputed size .
def adjustSize ( self ) : super ( XOverlayWizard , self ) . adjustSize ( ) # adjust the page size page_size = self . pageSize ( ) # resize the current page to the inputed size x = ( self . width ( ) - page_size . width ( ) ) / 2 y = ( self . height ( ) - page_size . height ( ) ) / 2 btn_height = max ( [ btn . height ( ) for btn in self . _buttons . values ( ) ] ) curr_page = self . currentPage ( ) for page in self . _pages . values ( ) : page . resize ( page_size . width ( ) , page_size . height ( ) - btn_height - 6 ) if page == curr_page : page . move ( x , y ) else : page . move ( self . width ( ) , y ) # move the left most buttons y += page_size . height ( ) - btn_height left_btns = ( self . _buttons [ self . WizardButton . HelpButton ] , self . _buttons [ self . WizardButton . BackButton ] ) for btn in left_btns : if btn . isVisible ( ) : btn . move ( x , y ) btn . raise_ ( ) x += btn . width ( ) + 6 # move the right buttons x = self . width ( ) - ( self . width ( ) - page_size . width ( ) ) / 2 for key in reversed ( sorted ( self . _buttons . keys ( ) ) ) : btn = self . _buttons [ key ] if not btn . isVisible ( ) or btn in left_btns : continue btn . move ( x - btn . width ( ) , y ) btn . raise_ ( ) x -= btn . width ( ) + 6
11,492
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L319-L361
[ "def", "updateSeriesRegistrationStatus", "(", ")", ":", "from", ".", "models", "import", "Series", "if", "not", "getConstant", "(", "'general__enableCronTasks'", ")", ":", "return", "logger", ".", "info", "(", "'Checking status of Series that are open for registration.'", ")", "open_series", "=", "Series", ".", "objects", ".", "filter", "(", ")", ".", "filter", "(", "*", "*", "{", "'registrationOpen'", ":", "True", "}", ")", "for", "series", "in", "open_series", ":", "series", ".", "updateRegistrationStatus", "(", ")" ]
Returns whether or not this wizard can move forward .
def canGoBack ( self ) : try : backId = self . _navigation . index ( self . currentId ( ) ) - 1 if backId >= 0 : self . _navigation [ backId ] else : return False except StandardError : return False else : return True
11,493
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L448-L463
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_publish", ":", "self", ".", "_events", ".", "put", "(", "(", "self", ".", "_listener", ".", "publish_server_closed", ",", "(", "self", ".", "_description", ".", "address", ",", "self", ".", "_topology_id", ")", ")", ")", "self", ".", "_monitor", ".", "close", "(", ")", "self", ".", "_pool", ".", "reset", "(", ")" ]
Returns the current page size for this wizard .
def pageSize ( self ) : # update the size based on the new size page_size = self . fixedPageSize ( ) if page_size . isEmpty ( ) : w = self . width ( ) - 80 h = self . height ( ) - 80 min_w = self . minimumPageSize ( ) . width ( ) min_h = self . minimumPageSize ( ) . height ( ) max_w = self . maximumPageSize ( ) . width ( ) max_h = self . maximumPageSize ( ) . height ( ) page_size = QtCore . QSize ( min ( max ( min_w , w ) , max_w ) , min ( max ( min_h , h ) , max_h ) ) return page_size
11,494
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L644-L663
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Restarts the whole wizard from the beginning .
def restart ( self ) : # hide all of the pages for page in self . _pages . values ( ) : page . hide ( ) pageId = self . startId ( ) try : first_page = self . _pages [ pageId ] except KeyError : return self . _currentId = pageId self . _navigation = [ pageId ] page_size = self . pageSize ( ) x = ( self . width ( ) - page_size . width ( ) ) / 2 y = ( self . height ( ) - page_size . height ( ) ) / 2 first_page . move ( self . width ( ) + first_page . width ( ) , y ) first_page . show ( ) # animate the current page out anim_out = QtCore . QPropertyAnimation ( self ) anim_out . setTargetObject ( first_page ) anim_out . setPropertyName ( 'pos' ) anim_out . setStartValue ( first_page . pos ( ) ) anim_out . setEndValue ( QtCore . QPoint ( x , y ) ) anim_out . setDuration ( self . animationSpeed ( ) ) anim_out . setEasingCurve ( QtCore . QEasingCurve . Linear ) anim_out . finished . connect ( anim_out . deleteLater ) # update the button states self . _buttons [ self . WizardButton . BackButton ] . setVisible ( False ) self . _buttons [ self . WizardButton . NextButton ] . setVisible ( self . canGoForward ( ) ) self . _buttons [ self . WizardButton . CommitButton ] . setVisible ( first_page . isCommitPage ( ) ) self . _buttons [ self . WizardButton . FinishButton ] . setVisible ( first_page . isFinalPage ( ) ) self . adjustSize ( ) first_page . initializePage ( ) self . currentIdChanged . emit ( pageId ) anim_out . start ( )
11,495
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L673-L716
[ "def", "_set_max_value", "(", "self", ",", "max_value", ")", ":", "self", ".", "_external_max_value", "=", "max_value", "# Check that the current value of the parameter is still within the boundaries. If not, issue a warning", "if", "self", ".", "_external_max_value", "is", "not", "None", "and", "self", ".", "value", ">", "self", ".", "_external_max_value", ":", "warnings", ".", "warn", "(", "\"The current value of the parameter %s (%s) \"", "\"was above the new maximum %s.\"", "%", "(", "self", ".", "name", ",", "self", ".", "value", ",", "self", ".", "_external_max_value", ")", ",", "exceptions", ".", "RuntimeWarning", ")", "self", ".", "value", "=", "self", ".", "_external_max_value" ]
Removes the inputed page from this wizard .
def removePage ( self , pageId ) : try : self . _pages [ pageId ] . deleteLater ( ) del self . _pages [ pageId ] except KeyError : pass
11,496
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L718-L728
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Sets the button for this wizard for the inputed type .
def setButton ( self , which , button ) : try : self . _buttons [ which ] . deleteLater ( ) except KeyError : pass button . setParent ( self ) self . _buttons [ which ] = button
11,497
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L747-L760
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Sets the display text for the inputed button to the given text .
def setButtonText ( self , which , text ) : try : self . _buttons [ which ] . setText ( text ) except KeyError : pass
11,498
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L762-L772
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Sets the page and id for the given page vs . auto - constructing it . This will allow the developer to create a custom order for IDs .
def setPage ( self , pageId , page ) : page . setParent ( self ) if self . property ( "useShadow" ) is not False : # create the drop shadow effect effect = QtGui . QGraphicsDropShadowEffect ( page ) effect . setColor ( QtGui . QColor ( 'black' ) ) effect . setBlurRadius ( 50 ) effect . setOffset ( 0 , 0 ) page . setGraphicsEffect ( effect ) self . _pages [ pageId ] = page if self . _startId == - 1 : self . _startId = pageId
11,499
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xoverlaywizard.py#L816-L837
[ "def", "server_close", "(", "self", ")", ":", "if", "self", ".", "remove_file", ":", "try", ":", "os", ".", "remove", "(", "self", ".", "remove_file", ")", "except", ":", "pass", "self", ".", "socket", ".", "close", "(", ")" ]