input
stringlengths
11
5.29k
target
stringlengths
20
8.26k
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def argument_processing(args, total_number_of_pdb_files): #print(args) print('Parametrs ') print('Total number of pdb files', total_number_of_pdb_files) if total_number_of_pdb_files < args.number_of_selected_files: print("Number od pdb files is ", total_number_of_pdb_files) sys.exit(0) if args.k_number_of_options > args.number_of_selected_files: print("Number of selected structure is only", args.number_of_selected_files) sys.exit(0) if args.mixing_koeficient != 1: print ("For q>1 is not implemented now \n") sys.exit(0) print('Files from directory', args.myDirVariable) print('The number of the selected files', args.number_of_selected_files) print('The number of selected options', args.k_number_of_options) print('All pdb.dat files \n', pdb_files) global selected_files_for_ensamble selected_files_for_ensamble = random.sample(pdb_files, args.number_of_selected_files) print('Randomly selected files: \n', selected_files_for_ensamble) global list_of_random_items list_of_random_items = random.sample(selected_files_for_ensamble, args.k_number_of_options) print('Randomly selected files: \n', list_of_random_items)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def save_pattern(self, filename=None, subtract_background=False): """ Saves the current integrated pattern. The format depends on the file ending. Possible file formats: [*.xy, *.chi, *.dat, *.fxye] :param filename: where to save the file :param subtract_background: flat whether the pattern should be saved with or without subtracted background """ if filename is None: filename = self.img_model.filename if filename.endswith('.xy'): self.pattern_model.save_pattern(filename, header=self._create_xy_header(), subtract_background=subtract_background) elif filename.endswith('.fxye'): self.pattern_model.save_pattern(filename, header=self._create_fxye_header(filename), subtract_background=subtract_background) else: self.pattern_model.save_pattern(filename, subtract_background=subtract_background)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def init(src, minimal=False): """Copies template files to a given directory. :param str src: The path to output the template lambda project files. :param bool minimal: Minimal possible template files (excludes event.json). """ templates_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "project_templates", ) for filename in os.listdir(templates_path): if (minimal and filename == "event.json") or filename.endswith(".pyc"): continue dest_path = os.path.join(templates_path, filename) if not os.path.isdir(dest_path): copy(dest_path, src)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def upload_s3(cfg, path_to_zip_file, *use_s3): """Upload a function to AWS S3.""" print("Uploading your new Lambda function") profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "s3", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) byte_stream = b"" with open(path_to_zip_file, mode="rb") as fh: byte_stream = fh.read() s3_key_prefix = cfg.get("s3_key_prefix", "/dist") checksum = hashlib.new("md5", byte_stream).hexdigest() timestamp = str(time.time()) filename = "{prefix}{checksum}-{ts}.zip".format( prefix=s3_key_prefix, checksum=checksum, ts=timestamp, ) # Do we prefer development variable over config? buck_name = os.environ.get("S3_BUCKET_NAME") or cfg.get("bucket_name") func_name = os.environ.get("LAMBDA_FUNCTION_NAME") or cfg.get( "function_name" ) kwargs = { "Bucket": "{}".format(buck_name), "Key": "{}".format(filename), "Body": byte_stream, } client.put_object(**kwargs) print("Finished uploading {} to S3 bucket {}".format(func_name, buck_name)) if use_s3: return filename
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _addTrailingNewline(self, filename, fullpath): # FIXME: This exists only for stability; there is no longer # any need to add trailing newlines to config files. This # also violates the rule that no files are modified after # destdir modification has been completed. self.warn("adding trailing newline to config file '%s'" % \ filename) mode = os.lstat(fullpath)[stat.ST_MODE] oldmode = None if mode & 0600 != 0600: # need to be able to read and write the file to fix it oldmode = mode os.chmod(fullpath, mode|0600) f = open(fullpath, 'a') f.seek(0, 2) f.write('\n') f.close() if oldmode is not None: os.chmod(fullpath, oldmode)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def updateArgs(self, *args, **keywords): """ call as:: UtilizeFoo(item, filespec(s)...) List them in order, most specific first, ending with most general; the filespecs will be matched in the order that you provide them. """ item = args[0] % self.recipe.macros if args: for filespec in args[1:]: self.filespecs.append((filespec, item)) policy.Policy.updateArgs(self, **keywords)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def doProcess(self, recipe): self.rootdir = self.rootdir % recipe.macros self.fileFilters = [] for (filespec, item) in self.filespecs: self.fileFilters.append( (filter.Filter(filespec, recipe.macros), item)) del self.filespecs policy.Policy.doProcess(self, recipe)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _create_attachments(self): # type: () -> None sample_size = 10 dummy_files = [ ('zulip.txt', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/zulip.txt', sample_size), ('temp_file.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/temp_file.py', sample_size), ('abc.py', '1/31/4CBjtTLYZhk66pZrF8hnYGwc/abc.py', sample_size) ] user_profile = self.example_user('hamlet') for file_name, path_id, size in dummy_files: create_attachment(file_name, path_id, user_profile, size)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def put(self, content, filename=None, content_type=None): """ Saves a new file using the storage system, preferably with the name specified. If there already exists a file with this name name, the storage system may modify the filename as necessary to get a unique name. Depending on the storage system, a unique id or the actual name of the stored file will be returned. The content type argument is used to appropriately identify the file when it is retrieved. .. versionchanged:: 0.5 Allow filename to be optional (#414). """ raise NotImplementedError
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def on_click_save_tads(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: with open(save_path, 'w') as o: for region in self.tad_regions: o.write("%s\t%d\t%d\n" % (region.chromosome, region.start-1, region.end))
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def on_click_save_vector(self, event): tk.Tk().withdraw() # Close the root window save_path = filedialog.asksaveasfilename() if save_path is not None: da_sub = self.da[self.current_da_ix] with open(save_path, 'w') as o: for i, region in enumerate(self.regions): o.write("%s\t%d\t%d\t.\t%e\n" % (region.chromosome, region.start-1, region.end, da_sub[i]))
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _read_flow(self, file_name): # Return the flow or a tuple with the flow and the valid_flow_mask if _has_builtin_flow_mask is True pass
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def setUp(self): self.oFile = vhdlFile.vhdlFile(lFile) self.assertIsNone(eError) self.oFile.set_indent_map(dIndentMap)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def poll(cls, context): userpref = context.user_preferences return (userpref.active_section == 'FILES')
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_parse_include(): filepaths, current_line = mariofile.parse_include(INCLUDE_FILE.splitlines(True)) assert filepaths == ['prova.ini', 'altrofile.ini'] assert current_line == 4 filepaths, current_line = mariofile.parse_include(INCLUDE_UNIQUE_FILE.splitlines(True)) assert filepaths == ['prova.ini'] assert current_line == 1
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config.get('ALLOWED_EXTENSIONS')
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def __iter__(self): for f in self._files: yield f
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def files(self): """Explicitly listed files or patterns or roots: if no patterns or .always(): empty list, if exact: list exact files, if not .anypats(): list all files and dirs, else: optimal roots""" return self._files
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def exact(self, f): """Returns True if f is in .files().""" return f in self._fileset
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def always(self): """Matcher will match everything and .files() will be empty -- optimization might be possible.""" return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def isexact(self): """Matcher will match exactly the list of files in .files() -- optimization might be possible.""" return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def prefix(self): """Matcher will match the paths in .files() recursively -- optimization might be possible.""" return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchfn(self, f): return True
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchfn(self, f): # XXX: is_dir is set to True here for performance. # It should be set to whether "f" is actually a directory or not. return self._matcher.match_relative(f, True)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchfn(self, f): return self._matcher.matches(f)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def __repr__(self): return "<exactmatcher files=%r>" % self._files
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchfn(self, f): return self._m1(f) and (not self._m2(f) or self._m1.exact(f))
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _files(self): if self.isexact(): return [f for f in self._m1.files() if self(f)] # If m1 is not an exact matcher, we can't easily figure out the set of # files, because its files() are not always files. For example, if # m1 is "path:dir" and m2 is "rootfileins:.", we don't # want to remove "dir" from the set even though it would match m2, # because the "dir" in m1 may not be a file. return self._m1.files()
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _files(self): if self.isexact(): m1, m2 = self._m1, self._m2 if not m1.isexact(): m1, m2 = m2, m1 return [f for f in m1.files() if m2(f)] # It neither m1 nor m2 is an exact matcher, we can't easily intersect # the set of files, because their files() are not always files. For # example, if intersecting a matcher "-I glob:foo.txt" with matcher of # "path:dir2", we don't want to remove "dir2" from the set. return self._m1.files() + self._m2.files()
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchfn(self, f): return bool(self.m1(f)) ^ bool(self.m2(f))
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchsubinclude(f): for prefix, matcherargs in subincludes: if f.startswith(prefix): mf = submatchers.get(prefix) if mf is None: mf = match(*matcherargs) submatchers[prefix] = mf if mf(f[len(prefix) :]): return True return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _explicitfiles(kindpats): """Returns the potential explicit filenames from the patterns. >>> _explicitfiles([(b'path', b'foo/bar', b'')]) ['foo/bar'] >>> _explicitfiles([(b'rootfilesin', b'foo/bar', b'')]) [] """ # Keep only the pattern kinds where one can specify filenames (vs only # directory names). filable = [kp for kp in kindpats if kp[0] not in ("rootfilesin",)] return _roots(filable)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def read(self, path): return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def read(self, path): return True
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def GetCompletions_Basic_test( app ): filepath = PathToTestFile( 'basic.py' ) completion_data = BuildRequest( filepath = filepath, filetype = 'python', contents = ReadFile( filepath ), line_num = 7, column_num = 3) results = app.post_json( '/completions', completion_data ).json[ 'completions' ] assert_that( results, has_items( CompletionEntryMatcher( 'a' ), CompletionEntryMatcher( 'b' ), CompletionLocationMatcher( 'line_num', 3 ), CompletionLocationMatcher( 'line_num', 4 ), CompletionLocationMatcher( 'column_num', 10 ), CompletionLocationMatcher( 'filepath', filepath ) ) )
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def testProvenanceItemFiles(self): """ Test item provenance when adding, modifying, and deleting files. """ item = self.item1 admin = self.admin # Test adding a new file to an existing item fileData1 = 'Hello world' fileData2 = 'Hello world, again' fileName1 = 'helloWorld.txt' fileName2 = 'helloWorldEdit.txt' resp = self.request( path='/file', method='POST', user=admin, params={ 'parentType': 'item', 'parentId': item['_id'], 'name': fileName1, 'size': len(fileData1), 'mimeType': 'text/plain' }) self.assertStatusOk(resp) uploadId = resp.json['_id'] fields = [('offset', 0), ('uploadId', uploadId)] files = [('chunk', fileName1, fileData1)] resp = self.multipartRequest( path='/file/chunk', user=admin, fields=fields, files=files) self.assertStatusOk(resp) file1 = resp.json self._checkProvenance(None, item, 2, admin, 'fileAdded', fileInfo={'fileId': str(file1['_id']), 'new': {'mimeType': 'text/plain', 'size': len(fileData1), 'name': fileName1}}) # Edit the file name resp = self.request(path='/file/%s' % file1['_id'], method='PUT', user=admin, params={'name': fileName2}) self.assertStatusOk(resp) self._checkProvenance(None, item, 3, admin, 'fileUpdate', fileInfo={'fileId': str(file1['_id']), 'old': {'name': fileName1}, 'new': {'name': fileName2}}) # Reupload the file resp = self.request(path='/file/%s/contents' % file1['_id'], method='PUT', user=admin, params={'size': len(fileData2)}) self.assertStatusOk(resp) uploadId = resp.json['_id'] fields = [('offset', 0), ('uploadId', uploadId)] files = [('chunk', fileName1, fileData2)] resp = self.multipartRequest( path='/file/chunk', user=admin, fields=fields, files=files) self.assertStatusOk(resp) self.assertEqual(file1['_id'], resp.json['_id']) self._checkProvenance(None, item, 4, admin, 'fileUpdate', fileInfo={'fileId': str(file1['_id']), 'old': {'size': len(fileData1)}, 'new': {'size': len(fileData2)}}) # Delete the file resp = self.request(path='/file/%s' % file1['_id'], method='DELETE', user=admin) self.assertStatusOk(resp) self._checkProvenance(None, item, 5, admin, 'fileRemoved', fileInfo={'fileId': str(file1['_id']), 'old': {'size': len(fileData2), 'name': fileName2}})
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _load_data(self, directory): try: with open(directory, 'r') as f: data = f.read() return literal_eval(data) except OSError as e: raise
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def get_outputs(self): return self.outfiles
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def md5(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest()
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _file_name_to_batch_number(example_file_name): """Parses batch number from file. :param example_file_name: See doc for `find_example_file`. :return: batch_number: Integer. :raises: ValueError: if batch number cannot be parsed from file name. """ pathless_file_name = os.path.split(example_file_name)[-1] extensionless_file_name = os.path.splitext(pathless_file_name)[0] return int(extensionless_file_name.split('input_examples_batch')[-1])
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _getFileContent(self, file_path): try: f = open(file_path, 'rb') data = f.read() f.close() sys.stdout.write("[+]\tFile '%s' was loaded for exfiltration.\n" % file_path) return data except IOError, e: sys.stderr.write("[-]\tUnable to read file '%s'.\n%s.\n" % (file_path, e)) return 1
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def find_sounding_files( top_sounding_dir_name, radar_file_name_matrix, target_names, lag_time_for_convective_contamination_sec): """Locates files with storm-centered soundings. D = number of SPC dates in time period :param top_sounding_dir_name: Name of top-level directory. Files therein will be found by `soundings.find_sounding_file`. :param radar_file_name_matrix: numpy array created by either `find_storm_images_2d` or `find_storm_images_3d`. Length of the first axis is D. :param target_names: See doc for `_check_target_vars`. :param lag_time_for_convective_contamination_sec: See doc for `soundings.read_soundings`. :return: sounding_file_names: length-D list of file paths. """ error_checking.assert_is_numpy_array(radar_file_name_matrix) num_file_dimensions = len(radar_file_name_matrix.shape) error_checking.assert_is_geq(num_file_dimensions, 2) error_checking.assert_is_leq(num_file_dimensions, 3) mean_lead_time_seconds = _check_target_vars(target_names)[0] num_file_times = radar_file_name_matrix.shape[0] sounding_file_names = [''] * num_file_times for i in range(num_file_times): if num_file_dimensions == 2: this_file_name = radar_file_name_matrix[i, 0] else: this_file_name = radar_file_name_matrix[i, 0, 0] this_time_unix_sec, this_spc_date_string = ( storm_images.image_file_name_to_time(this_file_name) ) sounding_file_names[i] = soundings.find_sounding_file( top_directory_name=top_sounding_dir_name, spc_date_string=this_spc_date_string, lead_time_seconds=mean_lead_time_seconds, lag_time_for_convective_contamination_sec= lag_time_for_convective_contamination_sec, init_time_unix_sec=this_time_unix_sec, raise_error_if_missing=True) return sounding_file_names
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def find_target_files(top_target_dir_name, radar_file_name_matrix, target_names): """Locates files with target values (storm-hazard indicators). D = number of SPC dates in time period :param top_target_dir_name: Name of top-level directory. Files therein will be found by `target_val_utils.find_target_file`. :param radar_file_name_matrix: numpy array created by either `find_storm_images_2d` or `find_storm_images_3d`. Length of the first axis is D. :param target_names: See doc for `_check_target_vars`. :return: target_file_names: length-D list of file paths. """ error_checking.assert_is_numpy_array(radar_file_name_matrix) num_file_dimensions = len(radar_file_name_matrix.shape) error_checking.assert_is_geq(num_file_dimensions, 2) error_checking.assert_is_leq(num_file_dimensions, 3) event_type_string = _check_target_vars(target_names)[-1] num_file_times = radar_file_name_matrix.shape[0] target_file_names = [''] * num_file_times for i in range(num_file_times): if num_file_dimensions == 2: this_file_name = radar_file_name_matrix[i, 0] else: this_file_name = radar_file_name_matrix[i, 0, 0] _, this_spc_date_string = storm_images.image_file_name_to_time( this_file_name) target_file_names[i] = target_val_utils.find_target_file( top_directory_name=top_target_dir_name, event_type_string=event_type_string, spc_date_string=this_spc_date_string, raise_error_if_missing=False) if os.path.isfile(target_file_names[i]): continue target_file_names[i] = None return target_file_names
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def find_example_file( top_directory_name, shuffled=True, spc_date_string=None, batch_number=None, raise_error_if_missing=True): """Looks for file with input examples. If `shuffled = True`, this method looks for a file with shuffled examples (from many different times). If `shuffled = False`, this method looks for a file with examples from one SPC date. :param top_directory_name: Name of top-level directory with input examples. :param shuffled: Boolean flag. The role of this flag is explained in the general discussion above. :param spc_date_string: [used only if `shuffled = False`] SPC date (format "yyyymmdd"). :param batch_number: [used only if `shuffled = True`] Batch number (integer). :param raise_error_if_missing: Boolean flag. If file is missing and `raise_error_if_missing = True`, this method will error out. :return: example_file_name: Path to file with input examples. If file is missing and `raise_error_if_missing = False`, this is the *expected* path. :raises: ValueError: if file is missing and `raise_error_if_missing = True`. """ error_checking.assert_is_string(top_directory_name) error_checking.assert_is_boolean(shuffled) error_checking.assert_is_boolean(raise_error_if_missing) if shuffled: error_checking.assert_is_integer(batch_number) error_checking.assert_is_geq(batch_number, 0) first_batch_number = int(number_rounding.floor_to_nearest( batch_number, NUM_BATCHES_PER_DIRECTORY)) last_batch_number = first_batch_number + NUM_BATCHES_PER_DIRECTORY - 1 example_file_name = ( '{0:s}/batches{1:07d}-{2:07d}/input_examples_batch{3:07d}.nc' ).format(top_directory_name, first_batch_number, last_batch_number, batch_number) else: time_conversion.spc_date_string_to_unix_sec(spc_date_string) example_file_name = ( '{0:s}/{1:s}/input_examples_{2:s}.nc' ).format(top_directory_name, spc_date_string[:4], spc_date_string) if raise_error_if_missing and not os.path.isfile(example_file_name): error_string = 'Cannot find file. Expected at: "{0:s}"'.format( example_file_name) raise ValueError(error_string) return example_file_name
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def find_many_example_files( top_directory_name, shuffled=True, first_spc_date_string=None, last_spc_date_string=None, first_batch_number=None, last_batch_number=None, raise_error_if_any_missing=True): """Looks for many files with input examples. :param top_directory_name: See doc for `find_example_file`. :param shuffled: Same. :param first_spc_date_string: [used only if `shuffled = False`] First SPC date (format "yyyymmdd"). This method will look for all SPC dates from `first_spc_date_string`...`last_spc_date_string`. :param last_spc_date_string: See above. :param first_batch_number: [used only if `shuffled = True`] First batch number (integer). This method will look for all batches from `first_batch_number`...`last_batch_number`. :param last_batch_number: See above. :param raise_error_if_any_missing: Boolean flag. If *any* desired file is not found and `raise_error_if_any_missing = True`, this method will error out. :return: example_file_names: 1-D list of paths to example files. :raises: ValueError: if no files are found. """ error_checking.assert_is_boolean(shuffled) if shuffled: error_checking.assert_is_integer(first_batch_number) error_checking.assert_is_integer(last_batch_number) error_checking.assert_is_geq(first_batch_number, 0) error_checking.assert_is_geq(last_batch_number, first_batch_number) example_file_pattern = ( '{0:s}/batches{1:s}-{1:s}/input_examples_batch{1:s}.nc' ).format(top_directory_name, BATCH_NUMBER_REGEX) example_file_names = glob.glob(example_file_pattern) if len(example_file_names) > 0: batch_numbers = numpy.array( [_file_name_to_batch_number(f) for f in example_file_names], dtype=int) good_indices = numpy.where(numpy.logical_and( batch_numbers >= first_batch_number, batch_numbers <= last_batch_number ))[0] example_file_names = [example_file_names[k] for k in good_indices] if len(example_file_names) == 0: error_string = ( 'Cannot find any files with batch number from {0:d}...{1:d}.' ).format(first_batch_number, last_batch_number) raise ValueError(error_string) return example_file_names spc_date_strings = time_conversion.get_spc_dates_in_range( first_spc_date_string=first_spc_date_string, last_spc_date_string=last_spc_date_string) example_file_names = [] for this_spc_date_string in spc_date_strings: this_file_name = find_example_file( top_directory_name=top_directory_name, shuffled=False, spc_date_string=this_spc_date_string, raise_error_if_missing=raise_error_if_any_missing) if not os.path.isfile(this_file_name): continue example_file_names.append(this_file_name) if len(example_file_names) == 0: error_string = ( 'Cannot find any file with SPC date from {0:s} to {1:s}.' ).format(first_spc_date_string, last_spc_date_string) raise ValueError(error_string) return example_file_names
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def getter(): with open(filepath, "r") as f: return f.read()
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def md5(file_path): """Get md5 hash of a file. Parameters ---------- file_path: str File path. Returns ------- md5_hash: str md5 hash of data in file_path """ hash_md5 = hashlib.md5() with open(file_path, 'rb') as fhandle: for chunk in iter(lambda: fhandle.read(4096), b''): hash_md5.update(chunk) return hash_md5.hexdigest()
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_validate(self, open_mock, is_file_mock): is_file_mock.return_value = True file_obj = open_mock.return_value.__enter__.return_value file_obj.read.return_value = 'connector.noname=example' self.assertRaisesRegexp(ConfigurationError, 'Catalog configuration example.properties ' 'does not contain connector.name', catalog.add, 'example')
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def read(self, filenames_to_try=[]): if isinstance(filenames_to_try, str): filenames_to_try = [filenames_to_try] self._filenames_to_try.extend(filenames_to_try) return self._cp.read(self._filenames_to_try)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def read(self): ''' read from file ''' # check if it exists if self.filename is None or not self.file_exists(): return None contents = None with open(self.filename) as yfd: contents = yfd.read() return contents
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def file_exists(self): ''' return whether file exists ''' if os.path.exists(self.filename): return True return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def get_resource_file(sfile, sfile_type='yaml'): ''' return the service file ''' contents = None with open(sfile) as sfd: contents = sfd.read() if sfile_type == 'yaml': # AUDIT:no-member makes sense here due to ruamel.YAML/PyYAML usage # pylint: disable=no-member if hasattr(yaml, 'RoundTripLoader'): contents = yaml.load(contents, yaml.RoundTripLoader) else: contents = yaml.safe_load(contents) elif sfile_type == 'json': contents = json.loads(contents) return contents
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def md5_for_file(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return str(hash_md5.hexdigest())
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def parseFileObject(fileobject, index=True): """ Function to read a FLAT file (by the file object descriptor) into python structures """ # Read entire file and use parseBuffer return parseFLATBuffer(fileobject.read(), index)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def parse(filename, index=True): """ Function to read a FLAT file into python structures """ # Open file with open(filename, 'r') as f: # Use FileObject parser to read the file return parseFLATBuffer(f.read(), index)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def analemma_file(self): """Analemma file name. Use this file to create the octree. """ return 'analemma.rad'
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def sunlist_file(self): """Sun list file name. Use this file as the list of modifiers in rcontrib. """ return 'analemma.mod'
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def analemma_file(self): """Analemma file name. Use this file to create the octree. """ return 'analemma_reversed.rad'
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def check_module_event(self, event): filename = self.getfilename() if not filename: return 'break' if not self.checksyntax(filename): return 'break' if not self.tabnanny(filename): return 'break'
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def main(): if len(sys.argv) < 2: print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr) return 1 list_scopes = set() with list_scope_path.open('r') as f: for line in f: line = line.strip() if line.startswith('#') or len(line) == 0: continue list_scopes.add(line) max_kw_len = max( len(kw) for kw in list_scopes ) if sys.argv[1] == 'tokens': t_id = (1 << (keyword_bit - 1)) | (1 << (list_scope_bit-1)) for t in sorted(list_scopes): print(' {:<{width}} = 0x{:4X};'.format(t.upper(), t_id, width=max_kw_len)) t_id += 1 elif sys.argv[1] == 'emitters': for t in sorted(list_scopes): print(' {:<{width}} => T_{}(Lexeme);'.format('"' + t + '"', t.upper(), width = max_kw_len + 2)) else: print("Error: Must specify an argument of either 'tokens' or 'emitters'!", file=sys.stderr) return 1 return 0
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def find_version(filename): _version_re = re.compile(r"__version__ = '(.*)'") for line in open(filename): version_match = _version_re.match(line) if version_match: return version_match.group(1)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def searching_pdb(): for line in files: line = line.rstrip() if re.search('.pdb$', line): #if re.search('.pdb.dat', line): pdb_files.append(line) #if re.search('exp.dat', line): #print('experimental file', line) # exp_file.append(line) total_number_of_pdb_files = len(pdb_files) return(total_number_of_pdb_files)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def find_index(strings): for e in list_of_random_items: value_of_index[e] = selected_files_for_ensamble.index(e) print(selected_files_for_ensamble.index(e)) with open("input_for_ensamble_fit", "w") as f: f.write(strings[0])
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def dropout_state_filter_visitor(unused_state): return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_should_encode_none(self): encoded = cypher_repr(None) assert encoded == u"null"
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_should_encode_true(self): encoded = cypher_repr(True) assert encoded == u"true"
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_should_encode_false(self): encoded = cypher_repr(False) assert encoded == u"false"
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def step_impl(context, count): cnt = len(context.response.json()) cnt.should.equal(int(count))
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_volume_bootable(self): """Test setting and retrieving bootable flag of a volume""" for bool_bootable in [True, False]: self.volumes_client.set_bootable_volume(self.volume['id'], bootable=bool_bootable) fetched_volume = self.volumes_client.show_volume( self.volume['id'])['volume'] # Get Volume information # NOTE(masayukig): 'bootable' is "true" or "false" in the current # cinder implementation. So we need to cast boolean values to str # and make it lower to compare here. self.assertEqual(str(bool_bootable).lower(), fetched_volume['bootable'])
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_disk_usage_sensor_is_stateless(): sensor = disk_usage.DiskUsage() ok_([] != sensor.measure())
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _update_changed_options(self): changed = {} for key in Parameters.updatables: if getattr(self.want, key) is not None: attr1 = getattr(self.want, key) attr2 = getattr(self.have, key) if attr1 != attr2: changed[key] = attr1 if changed: self.changes = Parameters(changed) return True return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _pool_is_licensed(self): if self.have.state == 'LICENSED': return True return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def _pool_is_unlicensed_eula_unaccepted(self, current): if current.state != 'LICENSED' and not self.want.accept_eula: return True return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def should_update(self): if self._pool_is_licensed(): return False if self._pool_is_unlicensed_eula_unaccepted(): return False return True
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def remove_duplicates(self): if self.ui.chkBRemoveDuplicates.isChecked(): for lbl in self.message.message_type: seq = lbl.fuzz_values[:] seen = set() add_seen = seen.add lbl.fuzz_values = [l for l in seq if not (l in seen or add_seen(l))]
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_regex_flags_good_input(): cases = ( 'abcd', 'ABCabc', 'ABC', ) case_insensitive = inputs.regex(r'^[A-Z]+$', re.IGNORECASE) for value in cases: yield assert_equal, case_insensitive(value), value
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_boolean_false(self): assert_equal(inputs.boolean("False"), False)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_boolean_is_false_for_0(self): assert_equal(inputs.boolean("0"), False)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_boolean_true(self): assert_equal(inputs.boolean("true"), True)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_boolean_is_true_for_1(self): assert_equal(inputs.boolean("1"), True)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_boolean_upper_case(self): assert_equal(inputs.boolean("FaLSE"), False)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_boolean(self): assert_equal(inputs.boolean("FaLSE"), False)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_boolean_with_python_bool(self): """Input that is already a native python `bool` should be passed through without extra processing.""" assert_equal(inputs.boolean(True), True) assert_equal(inputs.boolean(False), False)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_bad_boolean(self): assert_raises(ValueError, lambda: inputs.boolean("blah"))
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_date_input_error(self): assert_raises(ValueError, lambda: inputs.date("2008-13-13"))
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def union(matches, root, cwd): """Union a list of matchers. If the list is empty, return nevermatcher. If the list only contains one non-None value, return that matcher. Otherwise return a union matcher. """ matches = list(filter(None, matches)) if len(matches) == 0: return nevermatcher(root, cwd) elif len(matches) == 1: return matches[0] else: return unionmatcher(matches)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchfn(self, f): return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def anypats(self): """None of .always(), .isexact(), and .prefix() is true -- optimizations will be difficult.""" return not self.always() and not self.isexact() and not self.prefix()
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def always(self): return True
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def isexact(self): return True
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def prefix(self): return True
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchfn(self, f): return self._m1(f) and self._m2(f)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def matchfn(self, f): for match in self._matchers: if match(f): return True return False
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def patkind(pattern, default=None): """If pattern is 'kind:pat' with a known kind, return kind.""" return _patsplit(pattern, default)[0]
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_supertype(self): self.assert_(isinstance(None, NullType)) self.assert_(isinstance(Optional('a'), NullType)) self.assert_(isinstance(NotPassed, NotPassedType)) self.assert_(isinstance(NotPassed, NullType))
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_optional(self): self._option_suite('a') self._option_suite(5)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def test_edges(self): self.assertEqual(self.myfunc('a', third=None), self.expected)
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def ask_YesOrNo(self, info): yui.YUI.widgetFactory mgafactory = yui.YMGAWidgetFactory.getYMGAWidgetFactory(yui.YExternalWidgets.externalWidgetFactory("mga")) dlg = mgafactory.createDialogBox(yui.YMGAMessageBox.B_TWO) dlg.setTitle(info.title) dlg.setText(info.text, info.richtext) dlg.setButtonLabel("Yes", yui.YMGAMessageBox.B_ONE) dlg.setButtonLabel("No", yui.YMGAMessageBox.B_TWO) dlg.setMinSize(50, 5); return dlg.show() == yui.YMGAMessageBox.B_ONE
def __init__(self): self.filediff = None meldsettings.connect('changed', self.on_setting_changed)
def is_dirty(self): return any(context['dirty'] for context in self)