code stringlengths 1 18.2k |
|---|
def add_argparser(self, root, parents): """ Add arguments for this command. """ parser = root.add_parser('report', parents=parents) parser.set_defaults(func=self) parser.add_argument( '--auth', dest='auth', action='store', help='Path to the authorized credentials file (analytics.dat).' ) parser.add_argument( '--title',... |
help='Path to either a YAML configuration file or pre-reported JSON data.' ) parser.add_argument( 'output_path', action='store', help='Path to output either an HTML report or a JSON data file.' ) return parser |
def _ndays(self, start_date, ndays): """ Compute an end date given a start date and a number of days. """ if not getattr(self.args, 'start-date') and not self.config.get('start-date', None): raise Exception('start-date must be provided when ndays is used.') d = date(*map(int, start_date.split('-'))) d += timedelta(days... |
def query(self, start_date=None, end_date=None, ndays=None, metrics=[], dimensions=[], filters=None, segment=None, sort=[], start_index=1, max_results=10): """ Execute a query. """ if start_date: start_date = start_date elif getattr(self.args, 'start-date'): start_date = getattr(self.args, 'start-date') elif self.confi... |
None if prefix: prefix_filter = 'ga:pagePath=~^%s' % prefix if filters: filters = '%s;%s' % (prefix_filter, filters) else: filters = prefix_filter return self.service.data().ga().get( ids='ga:' + self.config['property-id'], start_date=start_date, end_date=end_date, metrics=','.join(metrics) or None, dimensions=','.join... |
def report(self): """ Query analytics and stash data in a format suitable for serializing. """ output = OrderedDict() for arg in GLOBAL_ARGUMENTS: output[arg] = getattr(self.args, arg) or self.config.get(arg, None) output['title'] = getattr(self.args, 'title') or self.config.get('title', 'Untitled Report') output['run_... |
i, metric in enumerate(analytic['metrics']): data['data'][metric] = OrderedDict() data_type = data['data_types'][metric] if dimensions_len: for row in results.get('rows', []): column = i + dimensions_len label = ','.join(row[:dimensions_len]) value = cast_data_type(row[column], data_type) data['data'][metric][label] = ... |
def html(self, report, f): """ Write report data to an HTML file. """ env = Environment(loader=PackageLoader('clan', 'templates')) template = env.get_template('report.html') context = { 'report': report, 'GLOBAL_ARGUMENTS': GLOBAL_ARGUMENTS, 'field_definitions': self.field_definitions, 'format_comma': format_comma, 'fo... |
def ensure_exe(exe_name: str, *paths: str): # pragma: no cover """ Makes sure that an executable can be found on the system path. Will exit the program if the executable cannot be found Args: exe_name: name of the executable paths: optional path(s) to be searched; if not specified, search the whole system """ if not el... |
def handle_captcha(self, query_params: dict, html: str, login_data: dict) -> requests.Response: """ Handling CAPTCHA request """ check_url = get_base_url(html) captcha_url = '{}?s={}&sid={}'.format(self.CAPTCHA_URI, query_params['s'], query_params['sid']) login_data['captcha_sid'] = query_params['sid'] login_data['capt... |
def handle_two_factor_check(self, html: str) -> requests.Response: """ Handling two factor authorization request """ action_url = get_base_url(html) code = input(self.TWO_FACTOR_PROMPT).strip() data = {'code': code, '_ajax': '1', 'remember': '1'} post_url = '/'.join((self.LOGIN_URL, action_url)) return self.post(post_u... |
def handle_phone_number_check(self, html: str) -> requests.Response: """ Handling phone number request """ action_url = get_base_url(html) phone_number = input(self.PHONE_PROMPT) url_params = get_url_params(action_url) data = {'code': phone_number, 'act': 'security_check', 'hash': url_params['hash']} post_url = '/'.joi... |
def check_for_additional_actions(self, url_params: dict, html: str, login_data: dict) -> None: """ Checks the url for a request for additional actions, if so, calls the event handler """ action_response = '' if 'sid' in url_params: action_response = self.handle_captcha(url_params, html, login_data) elif 'authcheck' in ... |
def login(self) -> bool: """ Authorizes a user and returns a bool value of the result """ response = self.get(self.LOGIN_URL) login_url = get_base_url(response.text) login_data = {'email': self._login, 'pass': self._password} login_response = self.post(login_url, login_data) url_params = get_url_params(login_response.u... |
def auth_oauth2(self) -> dict: """ Authorizes a user by OAuth2 to get access token """ oauth_data = { 'client_id': self._app_id, 'display': 'mobile', 'response_type': 'token', 'scope': '+66560', 'v': self.API_VERSION } response = self.post(self.OAUTH_URL, oauth_data) url_params = get_url_params(response.url, fragment=T... |
def get_access_token(self) -> str: """ Returns the access token in case of successful authorization """ if self._service_token: return self._service_token if self._app_id and self._login and self._password: try: if self.login(): url_params = self.auth_oauth2() if 'access_token' in url_params: return url_params['access_... |
def send_method_request(self, method: str, method_params: dict) -> dict: """ Sends user-defined method and method params """ url = '/'.join((self.METHOD_URL, method)) method_params['v'] = self.API_VERSION if self._access_token: method_params['access_token'] = self._access_token response = self.post(url, method_params, ... |
def train(self, net_sizes, epochs, batchsize): """ Initialize the base trainer """ self.trainer = ClassificationTrainer(self.data, self.targets, net_sizes) self.trainer.learn(epochs, batchsize) return self.trainer.evaluate(batchsize) |
def classify(self, phrase, cut_to_len=True): """ Classify a phrase based on the model. (See corresponding function in PhraseClassifier). Provided here mostly to help verify that a created model is worth saving. Technically, the results of the training should be enough for that, but it is good to be able to run it on co... |
def classify(self, phrase, cut_to_len=True): """ Classify a phrase based on the loaded model. If cut_to_len is True, cut to desired length.""" if (len(phrase) > self.max_phrase_len): if not cut_to_len: raise Exception("Phrase too long.") phrase = phrase[0:self.max_phrase_len] numbers = self.classifier.classify(stringTo... |
def find_command(cmd, path=None, pathext=None): """ Taken `from Django http://bit.ly/1njB3Y9>`_. """ if path is None: path = os.environ.get('PATH', '').split(os.pathsep) if isinstance(path, string_types): path = [path] # check if there are path extensions for Windows executables if pathext is None: pathext = os.environ... |
def handle_extensions(extensions=None, ignored=None): """ Organizes multiple extensions that are separated with commas or passed by using --extension/-e multiple times. Note that the .py extension is ignored here because of the way non-*.py files are handled in ``extract`` messages (they are copied to file.ext.py files... |
'.%s' % ext_list[i] return set([x for x in ext_list if x.strip('.') not in ignored]) |
def popen_wrapper(args): """ Friendly wrapper around Popen. Returns stdout output, stderr output and OS status code. """ try: p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt', universal_newlines=True) except OSError as e: raise OSError( "Error executing '{:}': '{:}'".format(args[0], e.st... |
def cmd(str, print_ret=False, usr_pwd=None, run=True): """ Executes a command and throws an exception on error. in: str - command print_ret - print command return usr_pwd - execute command as another user (user_name, password) run - really execute command? out: returns the command output """ if usr_pwd: str = 'echo {} ... |
def getPackages(plist): """ Cleans up input from the command line tool and returns a list of package names """ nlist = plist.split('\n') pkgs = [] for i in nlist: if i.find('===') > 0: continue pkg = i.split()[0] if pkg == 'Warning:': continue elif pkg == 'Could': continue elif pkg == 'Some': continue elif pkg == 'You'... |
def pip(usr_pswd=None): """ This updates one package at a time. Could do all at once: pip list --outdated | cut -d' ' -f1 | xargs pip install --upgrade """ # see if pip is installed try: cmd('which pip') except: return print('-[pip]----------') p = cmd('pip list --outdated') if not p: return pkgs = getPackages(p) # upd... |
def brew(clean=False): """ Handle homebrew on macOS """ # see if homebrew is installed try: cmd('which brew') except: return print('-[brew]----------') cmd('brew update') p = cmd('brew outdated') if not p: return pkgs = getPackages(p) for p in pkgs: cmd('brew upgrade {}'.format(p), run=global_run) if clean: print(' > b... |
def kernel(): """ Handle linux kernel update """ print('================================') print(' WARNING: upgrading the kernel') print('================================') time.sleep(5) print('-[kernel]----------') cmd('rpi-update', True) print(' >> You MUST reboot to load the new kernel <<') |
def npm(usr_pwd=None, clean=False): """ Handle npm for Node.js """ # see if node is installed try: cmd('which npm') except: return print('-[npm]----------') # awk, ignore 1st line and grab 1st word p = cmd("npm outdated -g | awk 'NR>1 {print $1}'") if not p: return pkgs = getPackages(p) for p in pkgs: cmd('{} {}'.forma... |
def split(self): """Immediately stop the current interval and start a new interval that has a start_instant equivalent to the stop_interval of self""" self.stop() interval = Interval() interval._start_instant = self.stop_instant return interval |
def stop(self): """Mark the stop of the interval. Calling stop on an already stopped interval has no effect. An interval can only be stopped once. :returns: the duration if the interval is truely stopped otherwise ``False``. """ if self._start_instant is None: raise IntervalException("Attempt to stop an interval that h... |
def duration_so_far(self): """Return how the duration so far. :returns: the duration from the time the Interval was started if the interval is running, otherwise ``False``. """ if self._start_instant is None: return False if self._stop_instant is None: return int((instant() - self._start_instant) * 1000) return False |
def duration(self): """Returns the integer value of the interval, the value is in milliseconds. If the interval has not had stop called yet, it will report the number of milliseconds in the interval up to the current point in time. """ if self._stop_instant is None: return int((instant() - self._start_instant) * 1000) ... |
def __get_preferential_value(self, paths, index=0): """ Returns the preferential path's value. Preferential path being the first keyword (a.k.a. path) found in the path order list created on instantiation. """ try: value = paths[self.path_preference_order[index]] except KeyError: value = self.__get_preferential_value(p... |
def import_module(self, name): """Import a module into the bridge.""" if name not in self._objects: module = _import_module(name) self._objects[name] = module self._object_references[id(module)] = name return self._objects[name] |
def _component_of(name): """Get the root package or module of the passed module. """ # Get the registered package this model belongs to. segments = name.split('.') while segments: # Is this name a registered package? test = '.'.join(segments) if test in settings.get('COMPONENTS', []): # This is the component we are in.... |
def save(self, commit=False): """Save the changes to the model. If the model has not been persisted then it adds the model to the declared session. Then it flushes the object session and optionally commits it. """ if not has_identity(self): # Object has not been persisted to the database. session.add(self) if commit: #... |
def url(sport, league_id, team_id, start_date=None): """ Given sport name, league_id, team_id, and optional start date (YYYY-MM-DD), return the url for the fantasy team page for that date (default: today) """ url = '%s/%s/%s/' % (SPORT_URLS[sport], league_id, team_id) if start_date is not None: url += 'team?&date=%s' %... |
def team(page): """ Return the team name """ soup = BeautifulSoup(page) try: return soup.find('title').text.split(' | ')[0].split(' - ')[1] except: return None |
def league(page): """ Return the league name """ soup = BeautifulSoup(page) try: return soup.find('title').text.split(' | ')[0].split(' - ')[0] except: return None |
def date(page): """ Return the date, nicely-formatted """ soup = BeautifulSoup(page) try: page_date = soup.find('input', attrs={'name': 'date'})['value'] parsed_date = datetime.strptime(page_date, '%Y-%m-%d') return parsed_date.strftime('%a, %b %d, %Y') except: return None |
def alternates(page): """ Return iterable containing players on bench who are available to play, where each player is a dict containing: - name - details - opponent """ soup = BeautifulSoup(page) try: bench = soup.find_all('tr', class_='bench') bench_bios = [p.find('div', class_='ysf-player-name') for p in bench] names... |
def start_active_players_path(page): """ Return the path in the "Start Active Players" button """ soup = BeautifulSoup(page) try: return soup.find('a', href=True, text='Start Active Players')['href'] except: return None |
def _migrateStorageSchema(self, metadata: MetaData) -> None: """ Initialise the DB This method is called by the platform between the load() and start() calls. There should be no need for a plugin to call this method it's self. :param metadata: the SQLAlchemy metadata for this plugins schema """ relDir = self._packageCf... |
def prefetchDeclarativeIds(self, Declarative, count) -> Deferred: """ Get PG Sequence Generator A PostGreSQL sequence generator returns a chunk of IDs for the given declarative. :return: A generator that will provide the IDs :rtype: an iterator, yielding the numbers to assign """ return self._dbConn.prefetchDeclarative... |
def run_once(func): """ Simple decorator to ensure a function is ran only once """ def _inner(*args, **kwargs): if func.__name__ in CTX.run_once: LOGGER.info('skipping %s', func.__name__) return CTX.run_once[func.__name__] LOGGER.info('running: %s', func.__name__) result = func(*args, **kwargs) CTX.run_once[func.__name... |
def run(self, commands=None, default_command=None, context=None): """ Context: A dict of namespaces as the key, and their objects as the value. Used to easily inject code into the shell's runtime env. """ if commands: self._commands.update(commands) # HACK: Overriding the old shell isn't cool. # Should do it by default... |
def score_x_of_a_kind_yahtzee(dice: List[int], min_same_faces: int) -> int: """Return sum of dice if there are a minimum of equal min_same_faces dice, otherwise return zero. Only works for 3 or more min_same_faces. """ for die, count in Counter(dice).most_common(1): if count >= min_same_faces: return sum(dice) return 0 |
def score_x_of_a_kind_yatzy(dice: List[int], min_same_faces: int) -> int: """Similar to yahtzee, but only return the sum of the dice that satisfy min_same_faces """ for die, count in Counter(dice).most_common(1): if count >= min_same_faces: return die * min_same_faces return 0 |
def score_small_straight_yahztee(dice: List[int]) -> int: """ Small straight scoring according to regular yahtzee rules """ global CONSTANT_SCORES_YAHTZEE dice_set = set(dice) if _are_two_sets_equal({1, 2, 3, 4}, dice_set) or \ _are_two_sets_equal({2, 3, 4, 5}, dice_set) or \ _are_two_sets_equal({3, 4, 5, 6}, dice_set)... |
def score_small_straight_yatzy(dice: List[int]) -> int: """ Small straight scoring according to yatzy rules """ dice_set = set(dice) if _are_two_sets_equal({1, 2, 3, 4, 5}, dice_set): return sum(dice) return 0 |
def score_large_straight_yahtzee(dice: List[int]) -> int: """ Large straight scoring according to regular yahtzee rules """ global CONSTANT_SCORES_YAHTZEE dice_set = set(dice) if _are_two_sets_equal({1, 2, 3, 4, 5}, dice_set) or \ _are_two_sets_equal({2, 3, 4, 5, 6}, dice_set): return CONSTANT_SCORES_YAHTZEE[Category.L... |
def score_large_straight_yatzy(dice: List[int]) -> int: """ Large straight scoring according to yatzy rules """ dice_set = set(dice) if _are_two_sets_equal({2, 3, 4, 5, 6}, dice_set): return sum(dice) return 0 |
def select_dict(coll, key, value): """ Given an iterable of dictionaries, return the dictionaries where the values at a given key match the given value. If the value is an iterable of objects, the function will consider any to be a match. This is especially useful when calling REST APIs which return arrays of JSON obje... |
2, 30: 4}, ... {'hi': 'hello', 'bye': 'goodbye'}, ... ] >>> select_dict(dicts, 'hi', 'bye') [{'hi': 'bye'}] >>> select_dict(dicts, 'hi', ('bye', 'hello')) [{'hi': 'bye'}, {'hi': 'hello', 'bye': 'goodbye'}] """ if getattr(value, '__iter__', None): iterable = value else: iterable = [value] return [v for v in coll if key ... |
def inside_brain(stat_dset,atlas=None,p=0.001): '''calculates the percentage of voxels above a statistical threshold inside a brain mask vs. outside it if ``atlas`` is ``None``, it will try to find ``TT_N27``''' atlas = find_atlas(atlas) if atlas==None: return None mask_dset = nl.suffix(stat_dset,'_atlasfrac') nl.run([... |
def atlas_overlap(dset,atlas=None): '''aligns ``dset`` to the TT_N27 atlas and returns ``(cost,overlap)``''' atlas = find_atlas(atlas) if atlas==None: return None cost_func = 'crM' infile = os.path.abspath(dset) tmpdir = tempfile.mkdtemp() with nl.run_in(tmpdir): o = nl.run(['3dAllineate','-verb','-base',atlas,'-source... |
def outcount(dset,fraction=0.1): '''gets outlier count and returns ``(list of proportion of outliers by timepoint,total percentage of outlier time points)''' polort = nl.auto_polort(dset) info = nl.dset_info(dset) o = nl.run(['3dToutcount','-fraction','-automask','-polort',polort,dset],stderr=None,quiet=None) if o.retu... |
def temporal_snr(signal_dset,noise_dset,mask=None,prefix='temporal_snr.nii.gz'): '''Calculates temporal SNR by dividing average signal of ``signal_dset`` by SD of ``noise_dset``. ``signal_dset`` should be a dataset that contains the average signal value (i.e., nothing that has been detrended by removing the mean), and ... |
def auto_qc(dset,inside_perc=60,atlas=None,p=0.001): '''returns ``False`` if ``dset`` fails minimum checks, or returns a float from ``0.0`` to ``100.0`` describing data quality''' with nl.notify('Running quality check on %s:' % dset): if not os.path.exists(dset): nl.notify('Error: cannot find the file!',level=nl.level.... |
return_val: nl.notify('Looks ok') return min(100*(1-cost),overlap,100*perc_outliers) return False with nl.notify('Single brain image detected...'): (cost,overlap) = atlas_overlap(dset) # Be more lenient if it's not an EPI, cuz who knows what else is in this image if cost>0.45 or overlap<70: nl.notify('Warning: does not... |
def lazy(func, *resultclasses): """ Turn any callable into a lazy evaluated callable. result classes or types is required -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access. """ @total_ordering class __pro... |
in resultclasses: for type_ in resultclass.mro(): for method_name in type_.__dict__.keys(): # All __promise__ return the same wrapper method, they # look up the correct implementation when called. if hasattr(cls, method_name): continue meth = cls.__promise__(method_name) setattr(cls, method_name, meth) cls._delegate_by... |
**self.__kw)) def __bytes_cast_encoded(self): return func(*self.__args, **self.__kw).encode() def __cast(self): if self._delegate_bytes: return self.__bytes_cast() elif self._delegate_text: return self.__text_cast() else: return func(*self.__args, **self.__kw) def __str__(self): # object defines __str__(), so __prepare... |
the actual value. return __proxy__(args, kw) return __wrapper__ |
def reconnect(self, conn_retries=None): ''' Connects to Redis with a exponential waiting (3**n) ''' if conn_retries is None: conn_retries = self.conn_retries count = 0 if self.logger: self.logger.info('Connecting to Redis..') while count < conn_retries: super(redis.client.Redis, self).__init__(*self.args, **self.kwargs... |
def _multi_lpop_pipeline(self, pipe, queue, number): ''' Pops multiple elements from a list in a given pipeline''' pipe.lrange(queue, 0, number - 1) pipe.ltrim(queue, number, -1) |
def multi_lpop(self, queue, number, transaction=False): ''' Pops multiple elements from a list This operation will be atomic if transaction=True is passed ''' try: pipe = self.pipeline(transaction=transaction) pipe.multi() self._multi_lpop_pipeline(pipe, queue, number) return pipe.execute()[0] except IndexError: return... |
def _multi_rpush_pipeline(self, pipe, queue, values, bulk_size=0): ''' Pushes multiple elements to a list in a given pipeline If bulk_size is set it will execute the pipeline every bulk_size elements ''' cont = 0 for value in values: pipe.rpush(queue, value) if bulk_size != 0 and cont % bulk_size == 0: pipe.execute() |
def multi_rpush(self, queue, values, bulk_size=0, transaction=False): ''' Pushes multiple elements to a list If bulk_size is set it will execute the pipeline every bulk_size elements This operation will be atomic if transaction=True is passed ''' # Check that what we receive is iterable if hasattr(values, '__iter__'): ... |
def multi_rpush_limit(self, queue, values, limit=100000): ''' Pushes multiple elements to a list in an atomic way until it reaches certain size Once limit is reached, the function will lpop the oldest elements This operation runs in LUA, so is always atomic ''' lua = ''' local queue = KEYS[1] local max_size = tonumber(... |
ipairs(ARGV) do redis.call('RPUSH', queue, key) end return 1 ''' # Check that what we receive is iterable if hasattr(values, '__iter__'): if len(values) > limit: raise ValueError('The iterable size is bigger than the allowed limit ({1}): {0}'.format(len(values), limit)) try: self.multi_rpush_limit_script([queue, limit]... |
def rpush_limit(self, queue, value, limit=100000): ''' Pushes an element to a list in an atomic way until it reaches certain size Once limit is reached, the function will lpop the oldest elements This operation runs in LUA, so is always atomic ''' lua = ''' local queue = KEYS[1] local max_size = tonumber(KEYS[2]) local... |
return 1 ''' try: self.rpush_limit_script([queue, limit], [value]) except AttributeError: if self.logger: self.logger.info('Script not registered... registering') # If the script is not registered, register it self.rpush_limit_script = self.register_script(lua) self.rpush_limit_script([queue, limit], [value]) |
def get_lock(self, lockname, locktime=60, auto_renewal=False): ''' Gets a lock and returns if it can be stablished. Returns false otherwise ''' pid = os.getpid() caller = inspect.stack()[0][3] try: # rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['host'], "port": settings.REDIS_SERVERS['std_redis'][... |
def wait_for_lock(self, lockname, locktime=60, auto_renewal=False): ''' Gets a lock or waits until it is able to get it ''' pid = os.getpid() caller = inspect.stack()[0][3] try: # rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['host'], "port": settings.REDIS_SERVERS['std_redis']['port'], "db": setti... |
locktime)) return rl |
def release_lock(self, lock, force=False): ''' Frees a lock ''' pid = os.getpid() caller = inspect.stack()[0][3] # try: # rl = redlock.Redlock([{"host": settings.REDIS_SERVERS['std_redis']['host'], "port": settings.REDIS_SERVERS['std_redis']['port'], "db": settings.REDIS_SERVERS['std_redis']['db']}, ]) # except: # logg... |
def pipeline(self, transaction=True, shard_hint=None): ''' Return a pipeline that support StoneRedis custom methods ''' args_dict = { 'connection_pool': self.connection_pool, 'response_callbacks': self.response_callbacks, 'transaction': transaction, 'shard_hint': shard_hint, 'logger': self.logger, } return StonePipelin... |
def multi_lpop(self, queue, number, transaction=False): ''' Pops multiple elements from a list ''' try: self._multi_lpop_pipeline(self, queue, number) except: raise |
def multi_rpush(self, queue, values, bulk_size=0, transaction=False): ''' Pushes multiple elements to a list ''' # Check that what we receive is iterable if hasattr(values, '__iter__'): self._multi_rpush_pipeline(self, queue, values, 0) else: raise ValueError('Expected an iterable') |
def _deserialize(data, klass): """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object. """ if data is None: return None if klass in six.integer_types or klass in (float, str, bool): return _deserialize_primitive(data, klass) ... |
def _deserialize_primitive(data, klass): """Deserializes to primitive type. :param data: data to deserialize. :param klass: class literal. :return: int, long, float, str, bool. :rtype: int | long | float | str | bool """ try: value = klass(data) except UnicodeEncodeError: value = six.u(data) except TypeError: value = d... |
def _deserialize_dict(data, boxed_type): """Deserializes a dict and its elements. :param data: dict to deserialize. :type data: dict :param boxed_type: class literal. :return: deserialized dict. :rtype: dict """ return {k: _deserialize(v, boxed_type) for k, v in six.iteritems(data)} |
def remove(self, what, call): """ remove an observer what: (string | array) state fields to observe call: (function) when not given, decorator usage is assumed. The call function should have 2 parameters: - previousValue, - actualValue """ type = observerTypeEnum.typeOf(what) self._observers.remove({ "observing": what,... |
def getObservers(self): """ Get the list of observer to the instance of the class. :return: Subscribed Obversers. :rtype: Array """ result = [] for observer in self._observers: result.append( { "observing": observer["observing"], "call": observer["call"] }) return result |
def add_job(session, command_line, name = 'job', dependencies = [], array = None, exec_dir=None, log_dir = None, stop_on_failure = False, **kwargs): """Helper function to create a job, add the dependencies and the array jobs.""" job = Job(command_line=command_line, name=name, exec_dir=exec_dir, log_dir=log_dir, array_s... |
def times(job): """Returns a string containing timing information for teh given job, which might be a :py:class:`Job` or an :py:class:`ArrayJob`.""" timing = "Submitted: %s" % job.submit_time.ctime() if job.start_time is not None: timing += "\nStarted : %s \t Job waited : %s" % (job.start_time.ctime(), job.start_time -... |
def format(self, format): """Formats the current job into a nicer string to fit into a table.""" job_id = "%d - %d" % (self.job.id, self.id) queue = self.job.queue_name if self.machine_name is None else self.machine_name status = "%s" % self.status + (" (%d)" % self.result if self.result is not None else "" ) return fo... |
def submit(self, new_queue = None): """Sets the status of this job to 'submitted'.""" self.status = 'submitted' self.result = None self.machine_name = None if new_queue is not None: self.queue_name = new_queue for array_job in self.array: array_job.status = 'submitted' array_job.result = None array_job.machine_name = N... |
def queue(self, new_job_id = None, new_job_name = None, queue_name = None): """Sets the status of this job to 'queued' or 'waiting'.""" # update the job id (i.e., when the job is executed in the grid) if new_job_id is not None: self.id = new_job_id if new_job_name is not None: self.name = new_job_name if queue_name is ... |
self.status = new_status for array_job in self.array: if array_job.status not in ('success', 'failure'): array_job.status = new_status |
def execute(self, array_id = None, machine_name = None): """Sets the status of this job to 'executing'.""" self.status = 'executing' if array_id is not None: for array_job in self.array: if array_job.id == array_id: array_job.status = 'executing' if machine_name is not None: array_job.machine_name = machine_name array_... |
def finish(self, result, array_id = None): """Sets the status of this job to 'success' or 'failure'.""" # check if there is any array job still running new_status = 'success' if result == 0 else 'failure' new_result = result finished = True if array_id is not None: for array_job in self.array: if array_job.id == array_... |
def refresh(self): """Refreshes the status information.""" if self.status == 'executing' and self.array: new_result = 0 for array_job in self.array: if array_job.status == 'failure' and new_result is not None: new_result = array_job.result elif array_job.status not in ('success', 'failure'): new_result = None if new_re... |
def get_command_line(self): """Returns the command line for the job.""" # In python 2, the command line is unicode, which needs to be converted to string before pickling; # In python 3, the command line is bytes, which can be pickled directly return loads(self.command_line) if isinstance(self.command_line, bytes) else ... |
def get_exec_dir(self): """Returns the command line for the job.""" # In python 2, the command line is unicode, which needs to be converted to string before pickling; # In python 3, the command line is bytes, which can be pickled directly return str(os.path.realpath(self.exec_dir)) if self.exec_dir is not None else Non... |
def get_array(self): """Returns the array arguments for the job; usually a string.""" # In python 2, the command line is unicode, which needs to be converted to string before pickling; # In python 3, the command line is bytes, which can be pickled directly return loads(self.array_string) if isinstance(self.array_string... |
def get_arguments(self): """Returns the additional options for the grid (such as the queue, memory requirements, ...).""" # In python 2, the command line is unicode, which needs to be converted to string before pickling; # In python 3, the command line is bytes, which can be pickled directly args = loads(self.grid_argu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.