code stringlengths 1 18.2k |
|---|
def getbit(self, key, offset): """Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is always out of range and the value is also as... |
def getrange(self, key, start, end): """Returns the bit value at offset in the string value stored at key. When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. When key does not exist it is assumed to be an empty string, so offset is always out of range and the value is a... |
:class:`str`, :class:`bytes` :param int start: The start position to evaluate in the string :param int end: The end position to evaluate in the string :rtype: bytes|None :raises: :exc:`~tredis.exceptions.RedisError` """ return self._execute([b'GETRANGE', key, ascii(start), ascii(end)]) |
def incrby(self, key, increment): """Increments the number stored at key by increment. If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 6... |
def incrbyfloat(self, key, increment): """Increment the string representing a floating point number stored at key by the specified increment. If the key does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur: - The key contains a value of the wrong ... |
the value computed after the increment is stored consistently in the same format, that is, an integer number followed (if needed) by a dot, and a variable number of digits representing the decimal part of the number. Trailing zeroes are always removed. The precision of the output is fixed at 17 digits after the decimal... |
def mset(self, mapping): """Sets the given keys to their respective values. :meth:`~tredis.RedisClient.mset` replaces existing values with new values, just as regular :meth:`~tredis.RedisClient.set`. See :meth:`~tredis.RedisClient.msetnx` if you don't want to overwrite existing values. :meth:`~tredis.RedisClient.mset` ... |
def msetnx(self, mapping): """Sets the given keys to their respective values. :meth:`~tredis.RedisClient.msetnx` will not perform any operation at all even if just a single key already exists. Because of this semantic :meth:`~tredis.RedisClient.msetnx` can be used in order to set different keys representing different f... |
= [b'MSETNX'] for key, value in mapping.items(): command += [key, value] return self._execute(command, 1) |
def psetex(self, key, milliseconds, value): """:meth:`~tredis.RedisClient.psetex` works exactly like :meth:`~tredis.RedisClient.psetex` with the sole difference that the expire time is specified in milliseconds instead of seconds. .. versionadded:: 0.2.0 .. note:: **Time complexity**: ``O(1)`` :param key: The key to se... |
def set(self, key, value, ex=None, px=None, nx=False, xx=False): """Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful :meth:`~tredis.RedisClient.set` operation. If the value is not one o... |
exist :rtype: bool :raises: :exc:`~tredis.exceptions.RedisError` :raises: :exc:`ValueError` """ command = [b'SET', key, value] if ex: command += [b'EX', ascii(ex).encode('ascii')] if px: command += [b'PX', ascii(px).encode('ascii')] if nx: command.append(b'NX') if xx: command.append(b'XX') return self._execute(command,... |
def setbit(self, key, offset, bit): """Sets or clears the bit at offset in the string value stored at key. The bit is either set or cleared depending on value, which can be either 0 or 1. When key does not exist, a new string value is created. The string is grown to make sure it can hold a bit at offset. The offset arg... |
small string value, Redis needs to allocate all intermediate memory which can block the server for some time. On a 2010 MacBook Pro, setting bit number 2 :sup:`32` -1 (512MB allocation) takes ~300ms, setting bit number 2 :sup:`30` -1 (128MB allocation) takes ~80ms, setting bit number 2 :sup:`28` -1 (32MB allocation) ta... |
for the bit :rtype: int :raises: :exc:`~tredis.exceptions.RedisError` """ if 0 < bit > 1: raise ValueError('bit must be 1 or 0, not {}'.format(bit)) return self._execute([b'SETBIT', key, ascii(offset), ascii(bit)]) |
def setex(self, key, seconds, value): """Set key to hold the string value and set key to timeout after a given number of seconds. :meth:`~tredis.RedisClient.setex` is atomic, and can be reproduced by using :meth:`~tredis.RedisClient.set` and :meth:`~tredis.RedisClient.expire` inside an :meth:`~tredis.RedisClient.multi`... |
def setrange(self, key, offset, value): """Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as emp... |
hold a string value, or holds a small string value, Redis needs to allocate all intermediate memory which can block the server for some time. On a 2010 MacBook Pro, setting byte number 536870911 (512MB allocation) takes ~300ms, setting byte number 134217728 (128MB allocation) takes ~80ms, setting bit number 33554432 (3... |
value argument. :param key: The key to get the bit from :type key: :class:`str`, :class:`bytes` :param value: The value to set :type value: :class:`str`, :class:`bytes`, :class:`int` :returns: The length of the string after it was modified by the command :rtype: int :raises: :exc:`~tredis.exceptions.RedisError` """ ret... |
def conflicts(self, ext): """ Check if the extension conflicts with an already accepted extension. This may be the case when the two extensions use the same reserved bits, or have the same name (when the same extension is negotiated multiple times with different parameters). """ return ext.rsv1 and self.rsv1 \ or ext.r... |
def negotiate_safe(self, name, params): """ `name` and `params` are sent in the HTTP request by the client. Check if the extension name is supported by this extension, and validate the parameters. Returns a dict with accepted parameters, or None if not accepted. """ for param in params.iterkeys(): if param not in self.... |
def index(request): """Handles a request based on method and calls the appropriate function""" if request.method == 'GET': return get(request) elif request.method == 'POST': return post(request) return HttpResponse('') |
def get(request): """Gets the currently logged in users preferences :returns: json """ res = Result() obj, created = UserPref.objects.get_or_create(user=request.user, defaults={'data': json.dumps(DefaultPrefs.copy())}) data = obj.json() data['subscriptions'] = [_.json() for _ in GallerySubscription.objects.filter(user=... |
def post(request): """Sets a key to a value on the currently logged in users preferences :param key: Key to set :type key: str :param val: Value to set :type val: primitive :returns: json """ data = request.POST or json.loads(request.body)['body'] key = data.get('key', None) val = data.get('val', None) res = Result() i... |
def get_modified_date(parsed, raw): 'Return best possible guess to post modification timestamp.' if parsed: return feedparser_ts(parsed) if not raw: return None # Parse weird timestamps that feedparser can't handle, e.g.: July 30, 2013 ts, val = None, raw.replace('_', ' ') if not ts: # coreutils' "date" parses virtuall... |
def process_entry(self, entry): 'Construct a Post from a feedparser entry and save/update it in db' from feedjack.models import Post, Tag ## Construct a Post object from feedparser entry (FeedParserDict) post = Post(feed=self.feed) post.link = entry.get('link', self.feed.link) post.title = entry.get('title', post.link)... |
post.date_modified: break post.comments = entry.get('comments', '') enclosures = entry.get('enclosures', list()) if 'media_content' in entry: for mc in entry.media_content: if 'url' in mc: e = dict(href=mc['url'], medium=mc.get('medium', 'image')) else: e = entry.media_content e['type'] = 'application/x-media-content' ... |
= Tag(name=tagname) cobj.save() fcat.append(Tag.objects.get(name=tagname)) ## Some feedback post_base_fields = 'title link guid author author_email'.split() log.debug('[{0}] Entry\n{1}'.format(self.feed.id, '\n'.join( [' {0}: {1}'.format(key, getattr(post, key)) for key in post_base_fields] + ['tags: {0}'.format(' '.jo... |
else '[{0}] Post changed, but feed is marked as immutable: {1}' )\ .format(self.feed.id, post.link) ) else: # new post, store it into database retval = ENTRY_NEW log.extra( '[{0}] Saving new post: {1} (timestamp: {2})'\ .format(self.feed.id, post.guid, post.date_modified) ) # Try hard to set date_modified: feed.modifie... |
True try: post.save() except IntegrityError: log.error( 'IntegrityError while saving (supposedly) new'\ ' post with guid: {0.guid}, link: {0.link}, title: {0.title}'.format(post) ) raise for tcat in fcat: post.tags.add(tcat) self.postdict[post.guid] = post return retval |
def _process(self): 'Downloads and parses a feed.' ret_values = { ENTRY_NEW: 0, ENTRY_UPDATED: 0, ENTRY_SAME: 0, ENTRY_ERR: 0 } report_errors = not self.options.report_after\ or not self.feed.last_checked\ or (self.feed.last_checked + self.options.report_after < timezone.now()) feedparser_kws = dict() if sys.hexversion... |
return FEED_SAME, ret_values if self.fpf.status >= 400: if report_errors: log.warn('[{0}] HTTP error {1}: {2}'.format( self.feed.id, self.fpf.status, self.feed.feed_url )) return FEED_ERRFETCH, ret_values if self.fpf.bozo: bozo = getattr(self.fpf, 'bozo_exception', 'unknown error') if not self.feed.skip_errors: if repo... |
diff for empty (probably just-added) feeds if not self.postdict and Post.objects.filter(feed=self.feed.id).count() == 0: diff = 0 else: diff = op.truediv(len(guids) - len(self.postdict), len(guids)) * 100 if diff > self.options.max_diff: log.warn( '[{0}] Feed validation failed: {1} (diff: {2}% > {3}%)'\ .format(self.fe... |
def query_realtime_routine(bus_name, cur_station=None): '''Get real time routine. TODO support fuzzy matching. :param bus_name: the routine name of the bus. :param cur_station: current station, deaults to starting station of the routine. ''' routines = query_routines(bus_name) if not routines: return rv = [] for routin... |
def getRoot(): """Convenience to return the media root with forward slashes""" root = settings.MEDIA_ROOT.replace('\\', '/') if not root.endswith('/'): root += '/' return path.Path(root) |
def emailUser(video, error=None): """Emails the author of the video that it has finished processing""" html = render_to_string('frog/video_email.html', { 'user': video.author, 'error': error, 'video': video, 'SITE_URL': FROG_SITE_URL, }) subject, from_email, to = 'Video Processing Finished{}'.format(error or ''), 'nore... |
def zadd(self, key, *members, **kwargs): """Adds all the specified members with the specified scores to the sorted set stored at key. It is possible to specify multiple score / member pairs. If a specified member is already a member of the sorted set, the score is updated and the element reinserted at the right positio... |
be either: - a single dict where keys correspond to scores and values to elements - multiple strings paired as score then element .. code:: python yield client.zadd('myzset', {'1': 'one', '2': 'two'}) yield client.zadd('myzset', '1', 'one', '2', 'two') **ZADD options (Redis 3.0.2 or greater)** ZADD supports a list of o... |
had in the past are not counted. Note: normally the return value of ``ZADD`` only counts the number of new elements added. - ``incr``: When this option is specified ``ZADD`` acts like :meth:`~tredis.RedisClient.zincrby`. Only one score-element pair can be specified in this mode. .. note:: **Time complexity**: ``O(log(N... |
changed, or the new score if incr is set :raises: :exc:`~tredis.exceptions.RedisError` """ xx = kwargs.pop('xx', False) nx = kwargs.pop('nx', False) ch = kwargs.pop('ch', False) incr = kwargs.pop('incr', False) command = [b'ZADD', key] if xx: command += ['XX'] if nx: command += ['NX'] if ch: command += ['CH'] if incr: ... |
def zrange(self, key, start=0, stop=-1, with_scores=False): """Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. See :meth:`tredis.Client.zrevrange` when yo... |
0 1`` will return both the first and the second element of the sorted set. Out of range indexes will not produce an error. If start is larger than the largest index in the sorted set, or ``start > stop``, an empty list is returned. If stop is larger than the end of the sorted set Redis will treat it like it is the last... |
of elements in the sorted set and ``M`` the number of elements returned. :param key: The key of the sorted set :type key: :class:`str`, :class:`bytes` :param int start: The starting index of the sorted set :param int stop: The ending index of the sorted set :param bool with_scores: Return the scores with the elements :... |
def zrangebyscore(self, key, min_score, max_score, with_scores=False, offset=0, count=0): """Returns all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max). The elements are considered to be ordered from low to high scores. The elements having the ... |
add up to ``O(N)`` time complexity. The optional ``with_scores`` argument makes the command return both the element and its score, instead of the element alone. This option is available since Redis 2.0. **Exclusive intervals and infinity** ``min_score`` and ``max_score`` can be ``-inf`` and ``+inf``, so that you are no... |
all the elements with ``5 < score < 10`` (5 and 10 excluded). .. note:: **Time complexity**: ``O(log(N)+M)`` with ``N`` being the number of elements in the sorted set and ``M`` the number of elements being returned. If ``M`` is constant (e.g. always asking for the first 10 elements with ``count``), you can consider it ... |
if with_scores: command += ['WITHSCORES'] if offset or count: command += ['LIMIT', offset, count] return self._execute(command) |
def zrem(self, key, *members): """Removes the specified members from the sorted set stored at key. Non existing members are ignored. An error is returned when key exists and does not hold a sorted set. .. note:: **Time complexity**: ``O(M*log(N))`` with ``N`` being the number of elements in the sorted set and ``M`` the... |
def zremrangebyscore(self, key, min_score, max_score): """Removes all elements in the sorted set stored at key with a score between min and max. Intervals are described in :meth:`~tredis.RedisClient.zrangebyscore`. Returns the number of elements removed. .. note:: **Time complexity**: ``O(log(N)+M)`` with ``N`` being t... |
def zrevrange(self, key, start=0, stop=-1, with_scores=False): """Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the highest to the lowest score. Descending lexicographical order is used for elements with equal score. Apart from the reversed order... |
stop] if with_scores: command += ['WITHSCORES'] return self._execute(command) |
def getkey(stype, site_id=None, key=None): 'Returns the cache key depending on its type.' base = '{0}.feedjack'.format(settings.CACHE_MIDDLEWARE_KEY_PREFIX) if stype == T_HOST: return '{0}.hostcache'.format(base) elif stype == T_ITEM: return '{0}.{1}.item.{2}'.format(base, site_id, str2md5(key)) elif stype == T_META: r... |
def feed_interval_get(feed_id, parameters): 'Get adaptive interval between checks for a feed.' val = cache.get(getkey( T_INTERVAL, key=feed_interval_key(feed_id, parameters) )) return val if isinstance(val, tuple) else (val, None) |
def feed_interval_set(feed_id, parameters, interval, interval_ts): 'Set adaptive interval between checks for a feed.' cache.set(getkey( T_INTERVAL, key=feed_interval_key(feed_id, parameters) ), (interval, interval_ts)) |
def feed_interval_delete(feed_id, parameters): 'Invalidate cached adaptive interval value.' cache.delete(getkey( T_INTERVAL, key=feed_interval_key(feed_id, parameters) )) |
def cache_set(site, key, data): '''Sets cache data for a site. All keys related to a site are stored in a meta key. This key is per-site.''' tkey = getkey(T_ITEM, site.id, key) mkey = getkey(T_META, site.id) tmp = cache.get(mkey) longdur = 365*24*60*60 if not tmp: tmp = [tkey] cache.set(mkey, [tkey], longdur) elif tkey... |
def cache_delsite(site_id): 'Removes all cache data from a site.' mkey = getkey(T_META, site_id) tmp = cache.get(mkey) if not tmp: return for tkey in tmp: cache.delete(tkey) cache.delete(mkey) |
def wrap(self, message): """ NTM GSSwrap() :param message: The message to be encrypted :return: The signed and encrypted message """ cipher_text = _Ntlm1Session.encrypt(self, message) signature = _Ntlm1Session.sign(self, message) return cipher_text, signature |
def unwrap(self, message, signature): """ NTLM GSSUnwrap() :param message: The message to be encrypted :return: The signed and encrypted message """ plain_text = _Ntlm1Session.decrypt(self, message) _Ntlm1Session.verify(self, plain_text, signature) return plain_text |
def _weaken_key(flags, key): """ NOTE: Key weakening in NTLM2 (Extended Session Security) is performed simply by truncating the master key (or secondary master key, if key exchange is performed) to the appropriate length. 128-bit keys are supported under NTLM2. In this case, the master key is used directly in the gener... |
def sign(self, message): """ Generates a signature for the supplied message using NTLM2 Session Security Note: [MS-NLMP] Section 3.4.4 The message signature for NTLM with extended session security is a 16-byte value that contains the following components, as described by the NTLMSSP_MESSAGE_SIGNATURE structure: - A 4-b... |
#logger.debug("Signing Sequence Number: %s", str(self.outgoing_sequence)) # Increment the sequence number after signing each message self.outgoing_sequence += 1 return str(mac) |
def verify(self, message, signature): """ Verified the signature attached to the supplied message using NTLM2 Session Security :param message: The message whose signature will verified :return: True if the signature is valid, otherwise False """ # Parse the signature header mac = _Ntlm2MessageSignature() mac.from_strin... |
def wrap(self, message): """ NTM GSSwrap() :param message: The message to be encrypted :return: A Tuple containing the signature and the encrypted messaging """ cipher_text = _Ntlm2Session.encrypt(self, message) signature = _Ntlm2Session.sign(self, message) return cipher_text, signature |
def unwrap(self, message, signature): """ NTLM GSSUnwrap() :param message: The message to be decrypted :return: The decrypted message """ plain_text = _Ntlm2Session.decrypt(self, message) _Ntlm2Session.verify(self, plain_text, signature) return plain_text |
def mark_dead(self, connection, now=None): """ Mark the connection as dead (failed). Remove it from the live pool and put it on a timeout. :arg connection: the failed instance """ # allow inject for testing purposes now = now if now else time.time() try: self.connections.remove(connection) except ValueError: # connecti... |
def resurrect(self, force=False): """ Attempt to resurrect a connection from the dead pool. It will try to locate one (not all) eligible (it's timeout is over) connection to return to th live pool. :arg force: resurrect a connection even if there is none eligible (used when we have no live connections) """ # no dead co... |
def get_connection(self): """ Return a connection from the pool using the `ConnectionSelector` instance. It tries to resurrect eligible connections, forces a resurrection when no connections are availible and passes the list of live connections to the selector instance to choose from. Returns a connection instance and ... |
def _canvas_route(self, *args, **kwargs): """ Decorator for canvas route """ def outer(view_fn): @self.route(*args, **kwargs) def inner(*args, **kwargs): fn_args = getargspec(view_fn) try: idx = fn_args.args.index(_ARG_KEY) except ValueError: idx = -1 if idx > -1: if 'error' in flask_request.args: return redirect('%s?e... |
def _decode_signed_user(encoded_sig, encoded_data): """ Decodes the ``POST``ed signed data """ decoded_sig = _decode(encoded_sig) decoded_data = loads(_decode(encoded_data)) if decoded_sig != hmac.new(app.config['CANVAS_CLIENT_SECRET'], encoded_data, sha256).digest(): raise ValueError("sig doesn't match hash") return d... |
def request(self, path, data=None, method='GET'): """ Convenience Facebook request function. Utility function to request resources via the graph API, with the format expected by Facebook. """ url = '%s%s?access_token=%s' % ( 'https://graph.facebook.com', path, self['oauth_token']) req = Request(url, data=data) req.get_... |
def has_permissions(self): """ Check current user permission set Checks the current user permission set against the one being requested by the application. """ perms = self.request('/me/permissions')['data'][0].keys() return all(k in perms for k in app.config[ 'CANVAS_SCOPE'].split(',')) |
def same_guid(post, parameter=DEFAULT_SIMILARITY_TIMESPAN): '''Skip posts with exactly same GUID. Parameter: comparison timespan, seconds (int, 0 = inf, default: {0}).''' from feedjack.models import Post if isinstance(parameter, types.StringTypes): parameter = int(parameter.strip()) similar = Post.objects.filtered(for_... |
def similar_title(post, parameter=None): '''Skip posts with fuzzy-matched (threshold = levenshtein distance / length) title. Parameters (comma-delimited): minimal threshold, at which values are considired similar (float, 0 < x < 1, default: {0}); comparison timespan, seconds (int, 0 = inf, default: {1}).''' from feedja... |
def pick_enclosure_link(post, parameter=''): '''Override URL of the Post to point to url of the first enclosure with href attribute non-empty and type matching specified regexp parameter (empty=any). Missing "type" attribute for enclosure will be matched as an empty string. If none of the enclosures match, link won't b... |
def add_log_level(value, name): """ Add a new log level to the :mod:`logging` module. :param value: The log level's number (an integer). :param name: The name for the log level (a string). """ logging.addLevelName(value, name) setattr(logging, name, value) |
def notice(self, msg, *args, **kw): """Log a message with level :data:`NOTICE`. The arguments are interpreted as for :func:`logging.debug()`.""" if self.isEnabledFor(NOTICE): self._log(NOTICE, msg, args, **kw) |
def spam(self, msg, *args, **kw): """Log a message with level :data:`SPAM`. The arguments are interpreted as for :func:`logging.debug()`.""" if self.isEnabledFor(SPAM): self._log(SPAM, msg, args, **kw) |
def success(self, msg, *args, **kw): """Log a message with level :data:`SUCCESS`. The arguments are interpreted as for :func:`logging.debug()`.""" if self.isEnabledFor(SUCCESS): self._log(SUCCESS, msg, args, **kw) |
def verbose(self, msg, *args, **kw): """Log a message with level :data:`VERBOSE`. The arguments are interpreted as for :func:`logging.debug()`.""" if self.isEnabledFor(VERBOSE): self._log(VERBOSE, msg, args, **kw) |
def get_calculator_impstr(calculator_name): """ Returns the import string for the calculator """ if calculator_name.lower() == "gpaw" or calculator_name is None: return "from gpaw import GPAW as custom_calculator" elif calculator_name.lower() == "espresso": return "from espresso import espresso as custom_calculator" el... |
def get_optimizer_impstr(optimizer_name): """ Returns the import string for the optimizer """ possibilities = {"bfgs":"BFGS", "bfgslinesearch":"BFGSLineSearch", "fire":"FIRE", "goodoldquasinewton":"GoodOldQuasiNewton", "hesslbfgs":"HessLBFGS", "lbfgs":"LBFGS", "lbfgslinesearch":"LBFGSLineSearch", "linelbfgs":"LineLBFGS... |
def convert_the_getters(getters): """ A function used to prepare the arguments of calculator and atoms getter methods """ return_list = [] for getter in getters: if isinstance(getter,basestring): out_args = "" method_name = getter else: method_name, a = getter out_args = convert_the_args(a) return_list.append( (method_... |
def convert_the_args(raw_args): """ Function used to convert the arguments of methods """ if not raw_args: return "" if isinstance(raw_args,dict): out_args = ", ".join([ "{}={}".format(k,v) for k,v in raw_args.iteritems() ]) elif isinstance(raw_args,(list,tuple)): new_list = [] for x in raw_args: if isinstance(x,basest... |
def _prepare_for_submission(self,tempfolder, inputdict): """ This is the routine to be called when you want to create the input files and related stuff with a plugin. :param tempfolder: a aiida.common.folders.Folder subclass where the plugin should put all its files. :param inputdict: a dictionary with the input nodes,... |
pass if settings is not None: if not isinstance(parameters, ParameterData): raise InputValidationError("parameters is not of type " "ParameterData") try: kpoints = inputdict.pop(self.get_linkname('kpoints'),None) except KeyError: pass if kpoints is not None: if not isinstance(kpoints, KpointsData): raise InputValidatio... |
a dictionary") # get the name of the optimizer optimizer_name = optimizer.pop("name",None) if optimizer_name is None: raise InputValidationError("Don't have access to the optimizer name") # prepare the arguments to be passed to the optimizer class optimizer_argsstr = "atoms, " + convert_the_args(optimizer.pop("args",[]... |
= v calc_args[k] = the_v def return_a_function(v): try: has_magic = "@function" in v.keys() except AttributeError: has_magic = False if has_magic: args_dict = {} for k2,v2 in v['args'].iteritems(): if isinstance(v2,basestring): the_v = '"{}"'.format(v2) else: the_v = v2 args_dict[k2] = the_v v2 = "{}({})".format(v['@fu... |
save results atoms_getters = default_atoms_getters + convert_the_getters( parameters_dict.pop("atoms_getters",[]) ) # =============== prepare the methods of calculator.get(), to save results calculator_getters = convert_the_getters( parameters_dict.pop("calculator_getters",[]) ) # ===================== build the string... |
all_imports_string = "\n".join(all_imports) + "\n" # =================== prepare the python script ======================== input_txt = "" input_txt += get_file_header() input_txt += "# calculation pk: {}\n".format(self.pk) input_txt += "\n" input_txt += all_imports_string input_txt += "\n" pre_lines = parameters_dict.... |
"results = {}\n" for getter,getter_args in atoms_getters: input_txt += "results['{}'] = atoms.get_{}({})\n".format(getter, getter, getter_args) input_txt += "\n" for getter,getter_args in calculator_getters: input_txt += "results['{}'] = calculator.get_{}({})\n".format(getter, getter, getter_args) input_txt += "\n" # C... |
if optimizer is not None: input_txt += "atoms.write('{}')\n".format(self._output_aseatoms) input_txt += "\n" # write all the input script to a file input_filename = tempfolder.get_abs_path(self._INPUT_FILE_NAME) with open(input_filename,'w') as infile: infile.write(input_txt) # ============================ calcinfo ===... |
have two ways of running it: with gpaw-python in parallel # and executing python if in serial return calcinfo |
def runcmd(command, command_input=None, cwd=None): """Run a command, potentially sending stdin, and capturing stdout/err.""" proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) (stdout, stderr) = proc.communicate(command_input) if proc.returncode != 0: sys.st... |
def dd_docs(self): """Copy and convert various documentation files.""" top = os.path.join(os.path.dirname(__file__)) doc = os.path.join(top, 'doc') # Markdown to ronn to man page man_md = os.path.join(doc, 'authprogs.md') man_ronn = os.path.join(doc, 'authprogs.1.ronn') man_1 = os.path.join(doc, 'authprogs.1') # Create... |
Markdown files in top level just get renamed sans .md for name in MARKDOWN2TEXT: target = os.path.join(top, name) if os.path.exists(target): continue source = os.path.join(top, '%s.md' % target) shutil.copy(source, target) self.created.append(target) |
def rm_docs(self): """Remove converted docs.""" for filename in self.created: if os.path.exists(filename): os.unlink(filename) |
def extract_entry(scraped_info): """ Transform scraped_info dictionary into an entry, under the assumption that there is only one track in 'track' list, since each video/audio is instantiated individually on the RMF website and each of them is scraped independently, so there shouldn't be cases when there are 2 unrelate... |
date from title of audio files e.g. '10.06 Gość: Jarosław Gowin' formats = [] for src_name, src in sources.items(): url = src[0]['src'] formats.append({ 'url': url, 'quality': quality_mapping[src_name], 'ext': get_ext(url), 'width': int(scraped_info.get('width', 0)), 'height': int(scraped_info.get('height', 0)), }) # o... |
def index(request, obj_id): """Handles a request based on method and calls the appropriate function""" if request.method == 'GET': return get(request, obj_id) elif request.method == 'PUT': getPutData(request) return put(request, obj_id) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.