code
stringlengths
1
18.2k
def send_start(remote, code, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess...
def send_stop(remote, code, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- remote: str code: str device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documentation for subprocess....
def set_transmitters(transmitters, device=None, address=None): """ All parameters are passed to irsend. See the man page for irsend for details about their usage. Parameters ---------- transmitters: iterable yielding ints device: str address: str Notes ----- No attempt is made to catch or handle errors. See the documen...
def check_updates(): """Check and display upgraded packages """ count, packages = fetch() message = "No news is good news !" if count > 0: message = ("{0} software updates are available\n".format(count)) return [message, count, packages]
def _init_check_upodates(): """Sub function for init """ message, count, packages = check_updates() if count > 0: print(message) for pkg in packages: print("{0}".format(pkg)) else: print(message)
def init(): """Initialization , all begin from here """ su() args = sys.argv args.pop(0) cmd = "{0}sun_daemon".format(bin_path) if len(args) == 1: if args[0] == "start": print("Starting SUN daemon: {0} &".format(cmd)) subprocess.call("{0} &".format(cmd), shell=True) elif args[0] == "stop": print("Stopping SUN daemon: {...
def cli(parser): ''' Uninstall inactive Python packages from all accessible site-packages directories. Inactive Python packages when multiple packages with the same name are installed ''' parser.add_argument('-n', '--dry-run', action='store_true', help='Print cleanup actions without running') opts = parser.parse_args()...
def daemon_start(self): """Start daemon when gtk loaded """ if daemon_status() == "SUN not running": subprocess.call("{0} &".format(self.cmd), shell=True)
def sub_menu(self): """Create daemon submenu """ submenu = gtk.Menu() self.start = gtk.ImageMenuItem("Start") self.stop = gtk.ImageMenuItem("Stop") self.restart = gtk.ImageMenuItem("Restart") self.status = gtk.ImageMenuItem("Status") self.start.show() self.stop.show() self.restart.show() self.status.show() img_Start = ...
def menu(self, event_button, event_time, data=None): """Create popup menu """ self.sub_menu() menu = gtk.Menu() menu.append(self.daemon) separator = gtk.SeparatorMenuItem() menu_Check = gtk.ImageMenuItem("Check updates") img_Check = gtk.image_new_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_MENU) img_Check.show() menu_Info =...
def message(self, data): """Function to display messages to the user """ msg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_CLOSE, data) msg.set_resizable(1) msg.set_title(self.dialog_title) self.img.set_from_file(self.sun_icon) msg.set_image(self.img) msg.show_all() msg.run() msg.destroy()
def right_click(self, data, event_button, event_time): """Right click handler """ self.menu(event_button, event_time, data)
def parse(payload, candidate_classes): """ Parse a json response into an intent. :param payload: a JSON object representing an intent. :param candidate_classes: a list of classes representing various intents, each having their own `parse` method to attempt parsing the JSON object into the given intent class. :return: A...
def get_slot_value(payload, slot_name): """ Return the parsed value of a slot. An intent has the form: { "text": "brew me a cappuccino with 3 sugars tomorrow", "slots": [ {"value": {"slotName": "coffee_type", "value": "cappuccino"}}, ... ] } This function extracts a slot value given its slot name, and parses it into a ...
{ "slotName": "weatherForecastStartDatetime", "value": { "kind": "TimeInterval", "value": { "from": "2017-07-14 12:00:00 +00:00", "to": "2017-07-14 19:00:00 +00:00" } }, } which will be extracted as a TimeInterval object. :param payload: the intent, in JSON format. :return: the parsed value, as described above. """ if ...
def parse_instant_time(slot): """ Parse a slot into an InstantTime object. Sample response: { "entity": "snips/datetime", "range": { "end": 36, "start": 28 }, "rawValue": "tomorrow", "slotName": "weatherForecastStartDatetime", "value": { "grain": "Day", "kind": "InstantTime", "precision": "Exact", "value": "2017-09-15 ...
def parse_time_interval(slot): """ Parse a slot into a TimeInterval object. Sample response: { "entity": "snips/datetime", "range": { "end": 42, "start": 13 }, "rawValue": "between tomorrow and saturday", "slotName": "weatherForecastStartDatetime", "value": { "from": "2017-09-15 00:00:00 +00:00", "kind": "TimeInterval"...
def get_dict_value(dictionary, path): """ Safely get the value of a dictionary given a key path. For instance, for the dictionary `{ 'a': { 'b': 1 } }`, the value at key path ['a'] is { 'b': 1 }, at key path ['a', 'b'] is 1, at key path ['a', 'b', 'c'] is None. :param dictionary: a dictionary. :param path: the key path...
def csview(self, view=False): """View chemical shift values organized by amino acid residue. :param view: Open in default image viewer or save file in current working directory quietly. :type view: :py:obj:`True` or :py:obj:`False` :return: None :rtype: :py:obj:`None` """ for starfile in fileio.read_files(self.from_pat...
label, color) nextnodename = atname nodes.append(atnode_entry) edges.append("{} -> {}".format(currnodename, nextnodename)) currnodename = nextnodename if self.filename is None: filename = "{}_{}".format(starfile.id, idx) else: filename = "{}_{}".format(self.filename, idx) src = Source(self.dot_template.format("\n".join...
def getStringPartition(self): """ Get the string representation of the current partition @return string like ":-1,0:2" """ res = '' for s in self.partitions[self.index].getSlice(): start = '' stop = '' if s.start is not None: start = int(s.start) if s.stop is not None: stop = int(s.stop) res += '{0}:{1},'.format(start,...
def runit(): """run things""" parser = OptionParser() parser.add_option('-s', '--server', help='The spamassassin spamd server to connect to', dest='server', type='str', default='standalone.home.topdog-software.com') parser.add_option('-p', '--port', help='The spamassassin spamd server port to connect to', dest='port', ...
filename = os.path.join(path, test['name']) print "File => %s" % filename fileobj = open(filename) print "=" * 10, "client.check()" pprint.pprint(client.check(fileobj)) print "=" * 10, "client.symbols()" pprint.pprint(client.symbols(fileobj)) print "=" * 10, "client.report()" pprint.pprint(client.report(fileobj)) print...
def urlopen(link): """Return urllib2 urlopen """ try: return urllib2.urlopen(link) except urllib2.URLError: pass except ValueError: return "" except KeyboardInterrupt: print("") raise SystemExit()
def slack_ver(): """Open file and read Slackware version """ dist = read_file("/etc/slackware-version") sv = re.findall(r"\d+", dist) if len(sv) > 2: version = (".".join(sv[:2])) else: version = (".".join(sv)) return dist.split()[0], version
def ins_packages(): """Count installed Slackware packages """ count = 0 for pkg in os.listdir(pkg_path): if not pkg.startswith("."): count += 1 return count
def read_config(config): """Read config file and return uncomment line """ for line in config.splitlines(): line = line.lstrip() if line and not line.startswith("#"): return line return ""
def mirror(): """Get mirror from slackpkg mirrors file """ slack_mirror = read_config( read_file("{0}{1}".format(etc_slackpkg, "mirrors"))) if slack_mirror: return slack_mirror + changelog_txt else: print("\nYou do not have any mirror selected in /etc/slackpkg/mirrors" "\nPlease edit that file and uncomment ONE mirror....
def fetch(): """Get ChangeLog.txt file size and counts upgraded packages """ mir, r, slackpkg_last_date = mirror(), "", "" count, upgraded = 0, [] if mir: tar = urlopen(mir) try: r = tar.read() except AttributeError: print("sun: error: can't read mirror") if os.path.isfile(var_lib_slackpkg + changelog_txt): slackpkg_la...
def config(): """Return sun configuration values """ conf_args = { "INTERVAL": 60, "STANDBY": 3 } config_file = read_file("{0}{1}".format(conf_path, "sun.conf")) for line in config_file.splitlines(): line = line.lstrip() if line and not line.startswith("#"): conf_args[line.split("=")[0]] = line.split("=")[1] return con...
def os_info(): """Get OS info """ stype = "" slack, ver = slack_ver() mir = mirror() if mir: if "current" in mir: stype = "Current" else: stype = "Stable" info = ( "User: {0}\n" "OS: {1}\n" "Version: {2}\n" "Type: {3}\n" "Arch: {4}\n" "Kernel: {5}\n" "Packages: {6}".format(getpass.getuser(), slack, ver, stype, os.uname...
def getPrimeFactors(n): """ Get all the prime factor of given integer @param n integer @return list [1, ..., n] """ lo = [1] n2 = n // 2 k = 2 for k in range(2, n2 + 1): if (n // k)*k == n: lo.append(k) return lo + [n, ]
def getNeighborProc(self, proc, offset, periodic=None): """ Get the neighbor to a processor @param proc the reference processor rank @param offset displacement, e.g. (1, 0) for north, (0, -1) for west,... @param periodic boolean list of True/False values, True if axis is periodic, False otherwise @note will return None...
def __computeDecomp(self): """ Compute optimal dedomposition, each sub-domain has the same volume in index space. @return list if successful, empty list if not successful """ primeNumbers = [getPrimeFactors(d) for d in self.globalDims] ns = [len(pns) for pns in primeNumbers] validDecomps = [] self.validProcs = [] for i...
for d in range(self.ndims)] volume = reduce(operator.mul, sizes, 1) surface = 0 for d in range(self.ndims): surface += 2*reduce(operator.mul, sizes[:d], 1) * \ reduce(operator.mul, sizes[d+1:], 1) cost = surface / float(volume) if cost < minCost: bestDecomp = decomp minCost = cost self.decomp = bestDecomp # ok, we have...
def _generate_manager(manager_config): ''' Generate a manager from a manager_config dictionary Parameters ---------- manager_config : dict Configuration with keys class, args, and kwargs used to generate a new datafs.manager object Returns ------- manager : object datafs.managers.MongoDBManager or datafs.managers.Dynam...
manager_config['class'] if mgr_class_name.lower()[:5] == 'mongo': from datafs.managers.manager_mongo import ( MongoDBManager as mgr_class) elif mgr_class_name.lower()[:6] == 'dynamo': from datafs.managers.manager_dynamo import ( DynamoDBManager as mgr_class) else: raise KeyError( 'Manager class "{}" not recognized. Cho...
def _generate_service(service_config): ''' Generate a service from a service_config dictionary Parameters ---------- service_config : dict Configuration with keys service, args, and kwargs used to generate a new fs service object Returns ------- service : object fs service object initialized with *args, **kwargs Exampl...
local.close() >>> import shutil >>> shutil.rmtree(tempdir) Mock an S3 filesystem with moto: .. code-block:: python >>> import moto >>> m = moto.mock_s3() >>> m.start() >>> s3 = APIConstructor._generate_service( ... { ... 'service': 'S3FS', ... 'args': ['bucket-name'], ... 'kwargs': { ... 'aws_access_key':'MY_KEY', ... ...
def addStencilBranch(self, disp, weight): """ Set or overwrite the stencil weight for the given direction @param disp displacement vector @param weight stencil weight """ self.stencil[tuple(disp)] = weight self.__setPartionLogic(disp)
def apply(self, localArray): """ Apply stencil to data @param localArray local array @return new array on local proc """ # input dist array inp = daZeros(localArray.shape, localArray.dtype) inp[...] = localArray inp.setComm(self.comm) # output array out = numpy.zeros(localArray.shape, localArray.dtype) # expose the dis...
fetch out[dstSlce] += weight*inp.getData(remoteRank, remoteWinId) # some implementations require this inp.free() return out
def getIndicesFromBigIndex(self, bigIndex): """ Get index set from given big index @param bigIndex @return index set @note no checks are performed to ensure that the returned big index is valid """ indices = numpy.array([0 for i in range(self.ndims)]) for i in range(self.ndims): indices[i] = bigIndex // self.dimProd[i]...
def getBigIndexFromIndices(self, indices): """ Get the big index from a given set of indices @param indices @return big index @note no checks are performed to ensure that the returned indices are valid """ return reduce(operator.add, [self.dimProd[i]*indices[i] for i in range(self.ndims)], 0)
def areIndicesValid(self, inds): """ Test if indices are valid @param inds index set @return True if valid, False otherwise """ return reduce(operator.and_, [0 <= inds[d] < self.dims[d] for d in range(self.ndims)], True)
def get_setting(setting): """ Get the specified django setting, or it's default value """ defaults = { # The context to use for rendering fields 'TEMPLATE_FIELD_CONTEXT': {}, # When this is False, don't do any TemplateField rendering 'TEMPLATE_FIELD_RENDER': True } try: return getattr(settings, setting, defaults[settin...
def csv_line_items(self): ''' Invoices from lists omit csv-line-items ''' if not hasattr(self, '_csv_line_items'): url = '{}/{}'.format(self.base_url, self.id) self._csv_line_items = self.harvest._get_element_values(url, self.element_name).next().get('csv-line-items', '') return self._csv_line_items
def _create_getters(self, klass): ''' This method creates both the singular and plural getters for various Harvest object classes. ''' flag_name = '_got_' + klass.element_name cache_name = '_' + klass.element_name setattr(self, cache_name, {}) setattr(self, flag_name, False) cache = getattr(self, cache_name) def _get_i...
def api_call(self, call, method, params=None, headers=None, data=None, json=None): """ This is our generic api call function. We will route all calls except requests that do not return JSON ('Export' and 'Experiment Metrics' are examples where this is the case). This is beneficial because: 1. Allows for easier debuggin...
if data is None: data = {} # json- data to be sent in body of Request if json is None: json ={} # make the request following the 'requests.request' method r = requests.request(method=method, url=self.base_uri+call, params=params, headers=self.headers, data=data, json=json) response = { "body": r.json(), "code": r.statu...
def track_purchase(self, user, items, total, purchase_id= None, campaign_id=None, template_id=None, created_at=None, data_fields=None): """ The 'purchase_id' argument maps to 'id' for this API endpoint. This name is used to distinguish it from other instances where 'id' is a part of the API request with other Iterable ...
def get_experiment_metrics(self, path, return_response_object= None, experiment_id=None, campaign_id=None, start_date_time=None, end_date_time=None ): """ This endpoint doesn't return a JSON object, instead it returns a series of rows, each its own object. Given this setup, it makes sense to treat it how we handle our ...
def export_data_json(self, return_response_object, chunk_size=1024, path=None, data_type_name=None, date_range=None, delimiter=None, start_date_time=None, end_date_time=None, omit_fields=None, only_fields=None, campaign_id=None): """ Custom Keyword arguments: 1. return_response_object: if set to 'True', the 'r' respons...
Example: "/Users/username/Desktop/" If not set the file will download into the current directory. """ call="/api/export/data.json" # make sure correct ranges are being used date_ranges = ["Today", "Yesterday", "BeforeToday", "All"] if isinstance(return_response_object, bool) is False: raise ValueError("'return_iterator...
def delete_user_by_email(self, email): """ This call will delete a user from the Iterable database. This call requires a path parameter to be passed in, 'email' in this case, which is why we're just adding this to the 'call' argument that goes into the 'api_call' request. """ call = "/api/users/"+ str(email) return sel...
def get_user_by_email(self, email): """This function gets a user's data field and info""" call = "/api/users/"+ str(email) return self.api_call(call=call, method="GET")
def bulk_update_user(self, users): """ The Iterable 'Bulk User Update' api Bulk update user data or adds it if does not exist. Data is merged - missing fields are not deleted The body of the request takes 1 keys: 1. users -- in the form of an array -- which is the list of users that we're updating in sets of 50 users a...
def disable_device(self, token, email=None, user_id=None): """ This request manually disable pushes to a device until it comes online again. """ call = "/api/users/disableDevice" payload ={} payload["token"] = str(token) if email is not None: payload["email"] = str(email) if user_id is not None: payload["userId"] = str...
def update_user(self, email=None, data_fields=None, user_id=None, prefer_userId= None, merge_nested_objects=None): """ The Iterable 'User Update' api updates a user profile with new data fields. Missing fields are not deleted and new data is merged. The body of the request takes 4 keys: 1. email-- in the form of a stri...
not None: payload["email"] = str(email) if data_fields is not None: payload["dataFields"] = data_fields if user_id is not None: payload["userId"] = str(user_id) if prefer_userId is not None: payload["preferUserId"]= prefer_userId if merge_nested_objects is not None: payload["mergeNestedObjects"] = merge_nested_objects ...
def cli( ctx, config_file=None, requirements=None, profile=None): ''' An abstraction layer for data storage systems DataFS is a package manager for data. It manages file versions, dependencies, and metadata for individual use or large organizations. For more information, see the docs at https://datafs.readthedocs.io ''...
def configure(ctx, helper, edit): ''' Update configuration ''' ctx.obj.config = ConfigFile(ctx.obj.config_file) if edit: ctx.obj.config.edit_config_file() return if os.path.isfile(ctx.obj.config.config_file): ctx.obj.config.read_config() if ctx.obj.profile is None: ctx.obj.profile = ctx.obj.config.default_profile args,...
def create( ctx, archive_name, authority_name, versioned=True, tag=None, helper=False): ''' Create an archive ''' tags = list(tag) _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) var = ctx.obj.api.create( archive_name, authority_name=...
def update( ctx, archive_name, bumpversion='patch', prerelease=None, dependency=None, message=None, string=False, file=None): ''' Update an archive with new contents ''' _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) dependencies_dic...
bumpmsg))
def update_metadata(ctx, archive_name): ''' Update an archive's metadata ''' _generate_api(ctx) args, kwargs = _parse_args_and_kwargs(ctx.args) assert len(args) == 0, 'Unrecognized arguments: "{}"'.format(args) var = ctx.obj.api.get_archive(archive_name) var.update_metadata(metadata=kwargs)
def set_dependencies(ctx, archive_name, dependency=None): ''' Set the dependencies of an archive ''' _generate_api(ctx) kwargs = _parse_dependencies(dependency) var = ctx.obj.api.get_archive(archive_name) var.set_dependencies(dependencies=kwargs)
def get_dependencies(ctx, archive_name, version): ''' List the dependencies of an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) deps = [] dependencies = var.get_dependencies(version=version) for arch, dep in dependencies.items(): if dep is None: deps.append(arch) else: deps.append('{}=={}'....
def add_tags(ctx, archive_name, tags): ''' Add tags to an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) var.add_tags(*tags)
def get_tags(ctx, archive_name): ''' Print tags assigned to an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(' '.join(var.get_tags()), nl=False) print('')
def download(ctx, archive_name, filepath, version): ''' Download an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) if version is None: version = var.get_default_version() var.download(filepath, version=version) archstr = var.archive_name +\ '' if (not var.versioned) else ' v{}'.format(versio...
def cat(ctx, archive_name, version): ''' Echo the contents of an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) with var.open('r', version=version) as f: for chunk in iter(lambda: f.read(1024 * 1024), ''): click.echo(chunk)
def log(ctx, archive_name): ''' Get the version log for an archive ''' _generate_api(ctx) ctx.obj.api.get_archive(archive_name).log()
def metadata(ctx, archive_name): ''' Get an archive's metadata ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(var.get_metadata()))
def history(ctx, archive_name): ''' Get archive history ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(var.get_history()))
def versions(ctx, archive_name): ''' Get an archive's versions ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(map(str, var.get_versions())))
def filter_archives(ctx, prefix, pattern, engine): ''' List all archives matching filter criteria ''' _generate_api(ctx) # want to achieve behavior like click.echo(' '.join(matches)) for i, match in enumerate(ctx.obj.api.filter( pattern, engine, prefix=prefix)): click.echo(match, nl=False) print('')
def search(ctx, tags, prefix=None): ''' List all archives matching tag search criteria ''' _generate_api(ctx) for i, match in enumerate(ctx.obj.api.search(*tags, prefix=prefix)): click.echo(match, nl=False) print('')
def listdir(ctx, location, authority_name=None): ''' List archive path components at a given location Note: When using listdir on versioned archives, listdir will provide the version numbers when a full archive path is supplied as the location argument. This is because DataFS stores the archive path as a directory and ...
is attached or if :py:attr:`DefaultAuthorityName` is assigned). Returns ------- list Archive path components that exist at the given "directory" location on the specified authority Raises ------ ValueError A ValueError is raised if the authority is ambiguous or invalid ''' _generate_api(ctx) for path_component in ctx.o...
def delete(ctx, archive_name): ''' Delete an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) var.delete() click.echo('deleted archive {}'.format(var))
def getDirectoryDictionary(self,args): """ This is an internal method to compute a dictionary containing all the directories that potentially contain (more) input. The dictionary 'table' indicates which of its contents are part of the input: table[directory] == 'ALL' means that its entire content must be mapped table[d...
file, its extension is added to the dictionary entry: else: path = os.path.dirname(element) extension = os.path.splitext(element)[1] # If there is no extension, a '.' was missing. This happens when calling: # map -r [command] path/to/folder/*ext # and the folder 'folder' DOES NOT contain files with the extension 'ext'....
def createListRecursively(self,args): """ This is an internal method to create the list of input files (or directories) recursively, starting at the provided directory or directories. """ resultList = [] dirDict = self.getDirectoryDictionary(args) for key in dirDict: for path,dirs,files in os.walk(key): # Walk through ...
def createList(self,args): """ This is an internal method to create the list of input files (or directories) contained in the provided directory or directories. """ resultList = [] if len(args.path) == 1 and os.path.isdir(args.path[0]): resultList = [os.path.join(args.path[0], f) for f in os.listdir(args.path[0])] else...
def getExtensionList(self,extensions): """ This is an internal method that transforms the comma-separated extensions string into a list of extensions, e.g., "ext1,ext2,ext3" gets turned into ['.ext1','.ext2','.ext3']. If MapConstants.placeholderNoExtensionFilter is part of the string, the resulting list will also conta...
def getFiles(self,args): """ This is the main method of the class. Given the arguments, the corresponding list of all files (or directories if the -d option is used) are returned. """ fileList = [] if args.recursive: # The list is created by going through the folder(s) recursively: fileList = self.createListRecursively...
else: # Filter out all directories: fileList = [element for element in fileList if os.path.isfile(element)] if args.extensions != None: # Files are filtered based on their extensions: extensionList = self.getExtensionList(args.extensions) fileList = [element for element in fileList if os.path.splitext(element)[1] in ex...
def replaceInCommand(self,command, pattern, replacement, replacementAtBeginning): """ This is in internal method that replaces a certain 'pattern' in the provided command with a 'replacement'. A different replacement can be specified when the pattern occurs right at the beginning of the command. """ # Turn the command ...
def escapePlaceholders(self,inputString): """ This is an internal method that escapes all the placeholders defined in MapConstants.py. """ escaped = inputString.replace(MapConstants.placeholder,'\\'+MapConstants.placeholder) escaped = escaped.replace(MapConstants.placeholderFileName,'\\'+MapConstants.placeholderFileNam...
def buildPart(self,commandPart,fileNameWithPath,count,args): """ This is in internal method that builds a part of the command, see buildCommand(). """ # Get the path to the file: filePath = os.path.split(fileNameWithPath)[0] # Append '/' if there is a path, i.e., the file is not in the local directory: if filePath != '...
file: commandPart = self.replaceInCommand(commandPart,MapConstants.placeholderFileName,plainFileName,plainFileName) # Replace the extension placeholder with the extension: commandPart = self.replaceInCommand(commandPart,MapConstants.placeholderExtension,fileExtension,fileExtension) # Replace the placeholder for the cou...
def buildCommand(self,fileName,count,args): """ This is an internal method, building the command for a particular file. """ # Escape all placeholders in the file path: fileNameWithPath = self.escapePlaceholders(fileName) # The command is split into 'parts', which are separated by blank spaces: commandParts = args.comma...
def buildCommands(self,files,args): """ Given a list of (input) files, buildCommands builds all the commands. This is one of the two key methods of MapExecutor. """ commands = [] count = args.count_from # For each file, a command is created: for fileName in files: commands.append(self.buildCommand(fileName,count,args))...
def runCommands(self,commands,args): """ Given a list of commands, runCommands executes them. This is one of the two key methods of MapExecutor. """ errorCounter = 0 if args.list: print '\n'.join(commands) else: # Each command is executed sequentially: for command in commands: process = subprocess.Popen(command, stdout...
during the process.'
def _generate_filenames(sources): """Generate filenames. :param tuple sources: Sequence of strings representing path to file(s). :return: Path to file(s). :rtype: :py:class:`str` """ for source in sources: if os.path.isdir(source): for path, dirlist, filelist in os.walk(source): for fname in filelist: if nmrstarlib.VER...
def _generate_handles(filenames): """Open a sequence of filenames one at time producing file objects. The file is closed immediately when proceeding to the next iteration. :param generator filenames: Generator object that yields the path to each file, one at a time. :return: Filehandle to be processed into a :class:`~n...
def read_files(*sources): """Construct a generator that yields :class:`~nmrstarlib.nmrstarlib.StarFile` instances. :param sources: One or more strings representing path to file(s). :return: :class:`~nmrstarlib.nmrstarlib.StarFile` instance(s). :rtype: :class:`~nmrstarlib.nmrstarlib.StarFile` """ filenames = _generate_f...
def validate(self, csdl, service='facebook'): """ Validate the given CSDL :param csdl: The CSDL to be validated for analysis :type csdl: str :param service: The service for this API call (facebook, etc) :type service: str :return: dict of REST API output with headers attached :rtype: :class:`~datasift.request.DictRespo...