INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Convert a python dict to a dict containing valid environment variable values.
def dict_to_env(d, pathsep=os.pathsep): ''' Convert a python dict to a dict containing valid environment variable values. :param d: Dict to convert to an env dict :param pathsep: Path separator used to join lists(default os.pathsep) ''' out_env = {} for k, v in d.iteritems(): ...
Expand all environment variables in an environment dict
def expand_envvars(env): ''' Expand all environment variables in an environment dict :param env: Environment dict ''' out_env = {} for k, v in env.iteritems(): out_env[k] = Template(v).safe_substitute(env) # Expand twice to make sure we expand everything we possibly can for k...
Returns an unused random filepath.
def get_store_env_tmp(): '''Returns an unused random filepath.''' tempdir = tempfile.gettempdir() temp_name = 'envstore{0:0>3d}' temp_path = unipath(tempdir, temp_name.format(random.getrandbits(9))) if not os.path.exists(temp_path): return temp_path else: return get_store_env_tm...
Encode current environment as yaml and store in path or a temporary file. Return the path to the stored environment.
def store_env(path=None): '''Encode current environment as yaml and store in path or a temporary file. Return the path to the stored environment. ''' path = path or get_store_env_tmp() env_dict = yaml.safe_dump(os.environ.data, default_flow_style=False) with open(path, 'w') as f: f.wr...
Set environment variables in the current python process from a dict containing envvars and values.
def restore_env(env_dict): '''Set environment variables in the current python process from a dict containing envvars and values.''' if hasattr(sys, 'real_prefix'): sys.prefix = sys.real_prefix del(sys.real_prefix) replace_osenviron(expand_envvars(dict_to_env(env_dict)))
Restore the current environment from an environment stored in a yaml yaml file.
def restore_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) restore_env(env_dict)
Set environment variables in the current python process from a dict containing envvars and values.
def set_env(*env_dicts): '''Set environment variables in the current python process from a dict containing envvars and values.''' old_env_dict = env_to_dict(os.environ.data) new_env_dict = join_dicts(old_env_dict, *env_dicts) new_env = dict_to_env(new_env_dict) replace_osenviron(expand_envvars(...
Restore the current environment from an environment stored in a yaml yaml file.
def set_env_from_file(env_file): '''Restore the current environment from an environment stored in a yaml yaml file. :param env_file: Path to environment yaml file. ''' with open(env_file, 'r') as f: env_dict = yaml.load(f.read()) if 'environment' in env_dict: env_dict = env_di...
Returns the URL to the upstream data source for the given URI based on configuration
def upstream_url(self, uri): "Returns the URL to the upstream data source for the given URI based on configuration" return self.application.options.upstream + self.request.uri
Returns ( headers body ) from the cache or raise KeyError
def cache_get(self): "Returns (headers, body) from the cache or raise KeyError" key = self.cache_key() (headers, body, expires_ts) = self.application._cache[key] if expires_ts < time.now(): # asset has expired, delete it del self.application._cache[key] ...
Return request object for calling the upstream
def make_upstream_request(self): "Return request object for calling the upstream" url = self.upstream_url(self.request.uri) return tornado.httpclient.HTTPRequest(url, method=self.request.method, headers=self.request.headers, body=self.request.body if self.requ...
Returns time to live in seconds. 0 means no caching.
def ttl(self, response): """Returns time to live in seconds. 0 means no caching. Criteria: - response code 200 - read-only method (GET, HEAD, OPTIONS) Plus http headers: - cache-control: option1, option2, ... where options are: private | public ...
Creates a 2 - D histogram of data * x * * y * with * bins * * labels * =: code: [ title xlabel ylabel ] aspect ration * aspect *. Attempts to use axis * ax * first then the current axis of * fig * then the last axis to use an already - created window. Plotting ( * plot * ) is on by default setting false doesn t attempt...
def hist2d(x, y, bins=10, labels=None, aspect="auto", plot=True, fig=None, ax=None, interpolation='none', cbar=True, **kwargs): """ Creates a 2-D histogram of data *x*, *y* with *bins*, *labels* = :code:`[title, xlabel, ylabel]`, aspect ration *aspect*. Attempts to use axis *ax* first, then the current axis of ...
Plasma frequency: math: \\ omega_p for given plasma density
def w_p(self): """ Plasma frequency :math:`\\omega_p` for given plasma density """ return _np.sqrt(self.n_p * _np.power(_spc.e, 2) / (_spc.m_e * _spc.epsilon_0))
Geometric focusing force due to ion column for given plasma density as a function of * E *
def k_ion(self, E): """ Geometric focusing force due to ion column for given plasma density as a function of *E* """ return self.n_p * _np.power(_spc.e, 2) / (2*_sltr.GeV2joule(E) * _spc.epsilon_0)
Guarantee the existence of a basic MANIFEST. in.
def manifest(): """Guarantee the existence of a basic MANIFEST.in. manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive. `options.paved.dist.manifest.recursive_include`: set of fi...
This template tag is used to do complex nested attribute accessing of an object. The first parameter is the object being accessed subsequent paramters are one of:
def accessor(parser, token): """This template tag is used to do complex nested attribute accessing of an object. The first parameter is the object being accessed, subsequent paramters are one of: * a variable in the template context * a literal in the template context * either of the above su...
Helper to get field value from string path. String <context > is used to go up on context stack. It just can be used at the beginning of path: <context >. <context >. field_name_1 On the other hand <root > is used to start lookup from first item on context.
def get_field_value_from_context(field_name, context_list): """ Helper to get field value from string path. String '<context>' is used to go up on context stack. It just can be used at the beginning of path: <context>.<context>.field_name_1 On the other hand, '<root>' is used to start lookup from fi...
Returns a function wrapper that defers function calls execute inside gevent s threadpool but keeps any exception or backtrace in the caller s context.: param original_func: function to wrap: returns: wrapper function
def create_threadpool_executed_func(original_func): """ Returns a function wrapper that defers function calls execute inside gevent's threadpool but keeps any exception or backtrace in the caller's context. :param original_func: function to wrap :returns: wrapper function """ def wrapped_fun...
Format a pathname
def format_pathname( pathname, max_length): """ Format a pathname :param str pathname: Pathname to format :param int max_length: Maximum length of result pathname (> 3) :return: Formatted pathname :rtype: str :raises ValueError: If *max_length* is not larger than 3 This...
: param str time_point_string: String representation of a time point to format: return: Formatted time point: rtype: str: raises ValueError: If * time_point_string * is not formatted by dateutil. parser. parse
def format_time_point( time_point_string): """ :param str time_point_string: String representation of a time point to format :return: Formatted time point :rtype: str :raises ValueError: If *time_point_string* is not formatted by dateutil.parser.parse See :py:meth:`date...
Format a UUID string
def format_uuid( uuid, max_length=10): """ Format a UUID string :param str uuid: UUID to format :param int max_length: Maximum length of result string (> 3) :return: Formatted UUID :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function format...
Finds the reduced chi square difference of * observe * and * expect * with a given * error * and * ddof * degrees of freedom.
def chisquare(observe, expect, error, ddof, verbose=True): """ Finds the reduced chi square difference of *observe* and *expect* with a given *error* and *ddof* degrees of freedom. *verbose* flag determines if the reduced chi square is printed to the terminal. """ chisq = 0 error = error.fla...
Finds the mantissa and exponent of a number: math: x such that: math: x = m 10^e.
def frexp10(x): """ Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`. Parameters ---------- x : float Number :math:`x` such that :math:`x = m 10^e`. Returns ------- mantissa : float Number :math:`m` such that :math:`x = m 10^e`. e...
Returns count of upcoming events for a given number of days either featured or all Usage: { % get_upcoming_events_count DAYS as events_count % } with days being the number of days you want or 5 by default
def get_upcoming_events_count(days=14, featured=False): """ Returns count of upcoming events for a given number of days, either featured or all Usage: {% get_upcoming_events_count DAYS as events_count %} with days being the number of days you want, or 5 by default """ from happenings.models ...
Get upcoming events. Allows slicing to a given number picking the number of days to hold them after they ve started and whether they should be featured or not. Usage: { % get_upcoming_events 5 14 featured as events % } Would return no more than 5 Featured events holding them for 14 days past their start date.
def get_upcoming_events(num, days, featured=False): """ Get upcoming events. Allows slicing to a given number, picking the number of days to hold them after they've started and whether they should be featured or not. Usage: {% get_upcoming_events 5 14 featured as events %} Would return n...
Get upcoming events for a given number of days ( days out ) Allows specifying number of days to hold events after they ve started The max number to show ( defaults to 5 ) and whether they should be featured or not. Usage: { % get_events_by_date_range 14 3 3 featured as events % } Would return no more than 3 featured ev...
def get_events_by_date_range(days_out, days_hold, max_num=5, featured=False): """ Get upcoming events for a given number of days (days out) Allows specifying number of days to hold events after they've started The max number to show (defaults to 5) and whether they should be featured or not. Usa...
attempts to get next and previous on updates
def paginate_update(update): """ attempts to get next and previous on updates """ from happenings.models import Update time = update.pub_time event = update.event try: next = Update.objects.filter( event=event, pub_time__gt=time ).order_by('pub_time')....
Notify the client of the result of handling a request
def notify_client( notifier_uri, client_id, status_code, message=None): """ Notify the client of the result of handling a request The payload contains two elements: - client_id - result The *client_id* is the id of the client to notify. It is assumed that t...
Decorator for methods handling requests from RabbitMQ
def consume_message( method): """ Decorator for methods handling requests from RabbitMQ The goal of this decorator is to perform the tasks common to all methods handling requests: - Log the raw message to *stdout* - Decode the message into a Python dictionary - Log errors to *stder...
Decorator for methods handling requests from RabbitMQ
def consume_message_with_notify( notifier_uri_getter): """ Decorator for methods handling requests from RabbitMQ This decorator builds on the :py:func:`consume_message` decorator. It extents it by logic for notifying a client of the result of handling the request. The *notifier_uri_get...
>>> c = LRUCache () >>> c. get ( toto ) Traceback ( most recent call last ):... KeyError: toto >>> c. stats () [ misses ] 1 >>> c. put ( toto tata ) >>> c. get ( toto ) tata >>> c. stats () [ hits ] 1
def get(self, key): """ >>> c = LRUCache() >>> c.get('toto') Traceback (most recent call last): ... KeyError: 'toto' >>> c.stats()['misses'] 1 >>> c.put('toto', 'tata') >>> c.get('toto') 'tata' >>> c.stats()['hits'] ...
>>> c = LRUCache () >>> c. put ( 1 one ) >>> c. get ( 1 ) one >>> c. size () 1 >>> c. put ( 2 two ) >>> c. put ( 3 three ) >>> c. put ( 4 four ) >>> c. put ( 5 five ) >>> c. get ( 5 ) five >>> c. size () 5
def put(self, key, value): """ >>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) 'five' ...
>>> c = LRUCache () >>> c. put ( 1 one ) >>> c. get ( 1 ) one >>> c. delete ( 1 ) >>> c. get ( 1 ) Traceback ( most recent call last ):... KeyError: 1 >>> c. delete ( 1 ) Traceback ( most recent call last ):... KeyError: 1
def delete(self, key): """ >>> c = LRUCache() >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.delete(1) >>> c.get(1) Traceback (most recent call last): ... KeyError: 1 >>> c.delete(1) Traceback (most recent call last): ...
>>> c = MemSizeLRUCache ( maxmem = 24 * 4 ) >>> c. put ( 1 1 ) >>> c. mem () # 24 - bytes per integer 24 >>> c. put ( 2 2 ) >>> c. put ( 3 3 ) >>> c. put ( 4 4 ) >>> c. get ( 1 ) 1 >>> c. mem () 96 >>> c. size () 4 >>> c. put ( 5 5 ) >>> c. size () 4 >>> c. get ( 2 ) Traceback ( most recent call last ):... KeyError: 2
def put(self, key, value): """ >>> c = MemSizeLRUCache(maxmem=24*4) >>> c.put(1, 1) >>> c.mem() # 24-bytes per integer 24 >>> c.put(2, 2) >>> c.put(3, 3) >>> c.put(4, 4) >>> c.get(1) 1 >>> c.mem() 96 >>> c.size() ...
>>> c = MemSizeLRUCache () >>> c. put ( 1 1 ) >>> c. mem () 24 >>> c. delete ( 1 ) >>> c. mem () 0
def delete(self, key): """ >>> c = MemSizeLRUCache() >>> c.put(1, 1) >>> c.mem() 24 >>> c.delete(1) >>> c.mem() 0 """ (_value, mem) = LRUCache.get(self, key) self._mem -= mem LRUCache.delete(self, key)
>>> c = FixedSizeLRUCache ( maxsize = 5 ) >>> c. put ( 1 one ) >>> c. get ( 1 ) one >>> c. size () 1 >>> c. put ( 2 two ) >>> c. put ( 3 three ) >>> c. put ( 4 four ) >>> c. put ( 5 five ) >>> c. get ( 5 ) five >>> c. size () 5 >>> c. put ( 6 six ) >>> c. size () 5 >>> c. get ( 1 ) Traceback ( most recent call last ):....
def put(self, key, value): """ >>> c = FixedSizeLRUCache(maxsize=5) >>> c.put(1, 'one') >>> c.get(1) 'one' >>> c.size() 1 >>> c.put(2, 'two') >>> c.put(3, 'three') >>> c.put(4, 'four') >>> c.put(5, 'five') >>> c.get(5) ...
Retrieves the setting value whose name is indicated by name_hyphen.
def setting(self, name_hyphen): """ Retrieves the setting value whose name is indicated by name_hyphen. Values starting with $ are assumed to reference environment variables, and the value stored in environment variables is retrieved. It's an error if thes corresponding environm...
Returns dict of all setting values ( removes the helpstrings ).
def setting_values(self, skip=None): """ Returns dict of all setting values (removes the helpstrings). """ if not skip: skip = [] return dict( (k, v[1]) for k, v in six.iteritems(self._instance_settings) if not k in ski...
This method does the work of updating settings. Can be passed with enforce_helpstring = False which you may want if allowing end users to add arbitrary metadata via the settings system.
def _update_settings(self, new_settings, enforce_helpstring=True): """ This method does the work of updating settings. Can be passed with enforce_helpstring = False which you may want if allowing end users to add arbitrary metadata via the settings system. Preferable to use upda...
Return a combined dictionary of setting values and attribute values.
def settings_and_attributes(self): """Return a combined dictionary of setting values and attribute values.""" attrs = self.setting_values() attrs.update(self.__dict__) skip = ["_instance_settings", "aliases"] for a in skip: del attrs[a] return attrs
Detect if we get a class or a name convert a name to a class.
def get_reference_to_class(cls, class_or_class_name): """ Detect if we get a class or a name, convert a name to a class. """ if isinstance(class_or_class_name, type): return class_or_class_name elif isinstance(class_or_class_name, string_types): if ":" in...
Asserts that the class has a docstring returning it if successful.
def check_docstring(cls): """ Asserts that the class has a docstring, returning it if successful. """ docstring = inspect.getdoc(cls) if not docstring: breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1]) msg = "docstring required ...
Get absolute path to resource works for dev and for PyInstaller
def resourcePath(self, relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ from os import path import sys try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exc...
Add new block of logbook selection windows. Only 5 allowed.
def addLogbook(self, physDef= "LCLS", mccDef="MCC", initialInstance=False): '''Add new block of logbook selection windows. Only 5 allowed.''' if self.logMenuCount < 5: self.logMenus.append(LogSelectMenu(self.logui.multiLogLayout, initialInstance)) self.logMenus[-1].addLogbooks(se...
Remove logbook menu set.
def removeLogbook(self, menu=None): '''Remove logbook menu set.''' if self.logMenuCount > 1 and menu is not None: menu.removeMenu() self.logMenus.remove(menu) self.logMenuCount -= 1
Return selected log books by type.
def selectedLogs(self): '''Return selected log books by type.''' mcclogs = [] physlogs = [] for i in range(len(self.logMenus)): logType = self.logMenus[i].selectedType() log = self.logMenus[i].selectedProgram() if logType == "MCC": if l...
Verify enetered user name is on accepted MCC logbook list.
def acceptedUser(self, logType): '''Verify enetered user name is on accepted MCC logbook list.''' from urllib2 import urlopen, URLError, HTTPError import json isApproved = False userName = str(self.logui.userName.text()) if userName == "": re...
Create xml file with fields from logbook form.
def xmlSetup(self, logType, logList): """Create xml file with fields from logbook form.""" from xml.etree.ElementTree import Element, SubElement, ElementTree from datetime import datetime curr_time = datetime.now() if logType == "MCC": # Set up xml t...
Parse xml elements for pretty printing
def prettify(self, elem): """Parse xml elements for pretty printing""" from xml.etree import ElementTree from re import sub rawString = ElementTree.tostring(elem, 'utf-8') parsedString = sub(r'(?=<[^/].*>)', '\n', rawString) # Adds newline after each closing ta...
Convert supplied QPixmap object to image file.
def prepareImages(self, fileName, logType): """Convert supplied QPixmap object to image file.""" import subprocess if self.imageType == "png": self.imagePixmap.save(fileName + ".png", "PNG", -1) if logType == "Physics": makePostScript = "convert "...
Process user inputs and subit logbook entry when user clicks Submit button
def submitEntry(self): """Process user inputs and subit logbook entry when user clicks Submit button""" # logType = self.logui.logType.currentText() mcclogs, physlogs = self.selectedLogs() success = True if mcclogs != []: if not self.acceptedUser("MC...
Process log information and push to selected logbooks.
def sendToLogbook(self, fileName, logType, location=None): '''Process log information and push to selected logbooks.''' import subprocess success = True if logType == "MCC": fileString = "" if not self.imagePixmap.isNull(): fileString = fi...
Clear all form fields ( except author ).
def clearForm(self): """Clear all form fields (except author).""" self.logui.titleEntry.clear() self.logui.textEntry.clear() # Remove all log selection menus except the first while self.logMenuCount > 1: self.removeLogbook(self.logMenus[-1])
Create graphical objects for menus.
def setupUI(self): '''Create graphical objects for menus.''' labelSizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) labelSizePolicy.setHorizontalStretch(0) labelSizePolicy.setVerticalStretch(0) menuSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy....
Display menus and connect even signals.
def show(self): '''Display menus and connect even signals.''' self.parent.addLayout(self._logSelectLayout) self.menuCount += 1 self._connectSlots()
Add or change list of logbooks.
def addLogbooks(self, type=None, logs=[], default=""): '''Add or change list of logbooks.''' if type is not None and len(logs) != 0: if type in self.logList: for logbook in logs: if logbook not in self.logList.get(type)[0]: # print(...
Remove unwanted logbooks from list.
def removeLogbooks(self, type=None, logs=[]): '''Remove unwanted logbooks from list.''' if type is not None and type in self.logList: if len(logs) == 0 or logs == "All": del self.logList[type] else: for logbook in logs: if logbo...
Populate log program list to correspond with log type selection.
def changeLogType(self): '''Populate log program list to correspond with log type selection.''' logType = self.selectedType() programs = self.logList.get(logType)[0] default = self.logList.get(logType)[1] if logType in self.logList: self.programName.clear() ...
Add menus to parent gui.
def addMenu(self): '''Add menus to parent gui.''' self.parent.multiLogLayout.addLayout(self.logSelectLayout) self.getPrograms(logType, programName)
Iteratively remove graphical objects from layout.
def removeLayout(self, layout): '''Iteratively remove graphical objects from layout.''' for cnt in reversed(range(layout.count())): item = layout.takeAt(cnt) widget = item.widget() if widget is not None: widget.deleteLater() else: ...
Adds labels to a plot.
def addlabel(ax=None, toplabel=None, xlabel=None, ylabel=None, zlabel=None, clabel=None, cb=None, windowlabel=None, fig=None, axes=None): """Adds labels to a plot.""" if (axes is None) and (ax is not None): axes = ax if (windowlabel is not None) and (fig is not None): fig.canvas.set_window...
Determine the URL corresponding to Python object
def linkcode_resolve(domain, info): """ Determine the URL corresponding to Python object """ if domain != 'py': return None modname = info['module'] fullname = info['fullname'] submod = sys.modules.get(modname) if submod is None: return None obj = submod for pa...
Utility function to run commands against Django s django - admin. py/ manage. py.
def call_manage(cmd, capture=False, ignore_error=False): """Utility function to run commands against Django's `django-admin.py`/`manage.py`. `options.paved.django.project`: the path to the django project files (where `settings.py` typically resides). Will fall back to a DJANGO_SETTINGS_MODULE e...
Update the database with model schema. Shorthand for paver manage syncdb.
def syncdb(args): """Update the database with model schema. Shorthand for `paver manage syncdb`. """ cmd = args and 'syncdb %s' % ' '.join(options.args) or 'syncdb --noinput' call_manage(cmd) for fixture in options.paved.django.syncdb.fixtures: call_manage("loaddata %s" % fixture)
Run the dev server.
def start(info): """Run the dev server. Uses `django_extensions <http://pypi.python.org/pypi/django-extensions/0.5>`, if available, to provide `runserver_plus`. Set the command to use with `options.paved.django.runserver` Set the port to use with `options.paved.django.runserver_port` """ c...
Run South s schemamigration command.
def schema(args): """Run South's schemamigration command. """ try: import south cmd = args and 'schemamigration %s' % ' '.join(options.args) or 'schemamigration' call_manage(cmd) except ImportError: error('Could not import south.')
This static method validates a BioMapMapper definition. It returns None on success and throws an exception otherwise.
def validate(cls, definition): ''' This static method validates a BioMapMapper definition. It returns None on success and throws an exception otherwise. ''' schema_path = os.path.join(os.path.dirname(__file__), '../../schema/mapper_definition_sc...
The main method of this class and the essence of the package. It allows to map stuff.
def map(self, ID_s, FROM=None, TO=None, target_as_set=False, no_match_sub=None): ''' The main method of this class and the essence of the package. It allows to "map" stuff. Args: ID_s: Nested lists with...
Returns all data entries for a particular key. Default is the main key.
def get_all(self, key=None): ''' Returns all data entries for a particular key. Default is the main key. Args: key (str): key whose values to return (default: main key) Returns: List of all data entries for the key ''' key = self.definition.mai...
List requests
def get_requests(self, params={}): """ List requests http://dev.wheniwork.com/#listing-requests """ if "status" in params: params['status'] = ','.join(map(str, params['status'])) requests = [] users = {} messages = {} params['page'] =...
Make a guess comparing the hidden object to a set of provided digits. The digits should be passed as a set of arguments e. g:
def guess(self, *args): """ Make a guess, comparing the hidden object to a set of provided digits. The digits should be passed as a set of arguments, e.g: * for a normal game: 0, 1, 2, 3 * for a hex game: 0xA, 0xB, 5, 4 * alternate for hex game: 'A', 'b', 5, 4 :...
Load a game from a serialized JSON representation. The game expects a well defined structure as follows ( Note JSON string format ):
def load(self, game_json=None, mode=None): """ Load a game from a serialized JSON representation. The game expects a well defined structure as follows (Note JSON string format): '{ "guesses_made": int, "key": "str:a 4 word", "status": "str: one of pla...
Loads modes ( GameMode objects ) to be supported by the game object. Four default modes are provided ( normal easy hard and hex ) but others could be provided either by calling load_modes directly or passing a list of GameMode objects to the instantiation call.
def load_modes(self, input_modes=None): """ Loads modes (GameMode objects) to be supported by the game object. Four default modes are provided (normal, easy, hard, and hex) but others could be provided either by calling load_modes directly or passing a list of GameMode objects to ...
Simple method to form a start again message and give the answer in readable form.
def _start_again_message(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = ', '.join( [str(d) for d in self.game.answer][:-1] ) + ', and ...
Returns list of strings split by input delimeter
def line(self, line): """Returns list of strings split by input delimeter Argument: line - Input line to cut """ # Remove empty strings in case of multiple instances of delimiter return [x for x in re.split(self.delimiter, line.rstrip()) if x != '']
Get Existing Message
def get_message(self, message_id): """ Get Existing Message http://dev.wheniwork.com/#get-existing-message """ url = "/2/messages/%s" % message_id return self.message_from_json(self._get_resource(url)["message"])
List messages
def get_messages(self, params={}): """ List messages http://dev.wheniwork.com/#listing-messages """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/messages/?%s" % urlencode(param_list) data = self._get_resource(url) messages = [] ...
Creates a message
def create_message(self, params={}): """ Creates a message http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/" body = params data = self._post_resource(url, body) return self.message_from_json(data["message"])
Modify an existing message.
def update_message(self, message): """ Modify an existing message. http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/%s" % message.message_id data = self._put_resource(url, message.json_data()) return self.message_from_json(data)
Delete existing messages.
def delete_messages(self, messages): """ Delete existing messages. http://dev.wheniwork.com/#delete-existing-message """ url = "/2/messages/?%s" % urlencode([('ids', ",".join(messages))]) data = self._delete_resource(url) return data
Returns site data.
def get_site(self, site_id): """ Returns site data. http://dev.wheniwork.com/#get-existing-site """ url = "/2/sites/%s" % site_id return self.site_from_json(self._get_resource(url)["site"])
Returns a list of sites.
def get_sites(self): """ Returns a list of sites. http://dev.wheniwork.com/#listing-sites """ url = "/2/sites" data = self._get_resource(url) sites = [] for entry in data['sites']: sites.append(self.site_from_json(entry)) return site...
Creates a site
def create_site(self, params={}): """ Creates a site http://dev.wheniwork.com/#create-update-site """ url = "/2/sites/" body = params data = self._post_resource(url, body) return self.site_from_json(data["site"])
Returns a link to a view that moves the passed in object up in rank.
def admin_link_move_up(obj, link_text='up'): """Returns a link to a view that moves the passed in object up in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "up" :returns: HTML link code to view for moving the object """ if ...
Returns a link to a view that moves the passed in object down in rank.
def admin_link_move_down(obj, link_text='down'): """Returns a link to a view that moves the passed in object down in rank. :param obj: Object to move :param link_text: Text to display in the link. Defaults to "down" :returns: HTML link code to view for moving the object """...
Shows a figure with a typical orientation so that x and y axes are set up as expected.
def showfig(fig, aspect="auto"): """ Shows a figure with a typical orientation so that x and y axes are set up as expected. """ ax = fig.gca() # Swap y axis if needed alim = list(ax.axis()) if alim[3] < alim[2]: temp = alim[2] alim[2] = alim[3] alim[3] = temp ...
Shifts indicies as needed to account for one based indexing
def _setup_index(index): """Shifts indicies as needed to account for one based indexing Positive indicies need to be reduced by one to match with zero based indexing. Zero is not a valid input, and as such will throw a value error. Arguments: index - index to shift """ index =...
Returns selected positions from cut input source in desired arrangement.
def cut(self, line): """Returns selected positions from cut input source in desired arrangement. Argument: line - input to cut """ result = [] line = self.line(line) for i, field in enumerate(self.positions): try: ind...
Processes positions to account for ranges
def _setup_positions(self, positions): """Processes positions to account for ranges Arguments: positions - list of positions and/or ranges to process """ updated_positions = [] for i, position in enumerate(positions): ranger = re.search(r'(?P<start>-...
Performs cut for range from start position to end
def _cut_range(self, line, start, current_position): """Performs cut for range from start position to end Arguments: line - input to cut start - start of range current_position - current position in main cut function """ resu...
Creates list of values in a range with output delimiters.
def _extendrange(self, start, end): """Creates list of values in a range with output delimiters. Arguments: start - range start end - range end """ range_positions = [] for i in range(start, end): if i != 0: range_pos...
Locks the file by writing a. lock file. Returns True when the file is locked and False when the file was locked already
def lock_file(filename): """Locks the file by writing a '.lock' file. Returns True when the file is locked and False when the file was locked already""" lockfile = "%s.lock"%filename if isfile(lockfile): return False else: with open(lockfile, "w"): pass ret...
Unlocks the file by remove a. lock file. Returns True when the file is unlocked and False when the file was unlocked already
def unlock_file(filename): """Unlocks the file by remove a '.lock' file. Returns True when the file is unlocked and False when the file was unlocked already""" lockfile = "%s.lock"%filename if isfile(lockfile): os.remove(lockfile) return True else: return False
Copy Smart Previews from local to cloud or vica versa when local2cloud == False NB: nothing happens if source dir doesn t exist
def copy_smart_previews(local_catalog, cloud_catalog, local2cloud=True): """Copy Smart Previews from local to cloud or vica versa when 'local2cloud==False' NB: nothing happens if source dir doesn't exist""" lcat_noext = local_catalog[0:local_catalog.rfind(".lrcat")] ccat_noext = cloud_catalog...
Return a hash of the file From <http:// stackoverflow. com/ a/ 7829658 >
def hashsum(filename): """Return a hash of the file From <http://stackoverflow.com/a/7829658>""" with open(filename, mode='rb') as f: d = hashlib.sha1() for buf in iter(partial(f.read, 2**20), b''): d.update(buf) return d.hexdigest()
Initiate the local catalog and push it the cloud
def cmd_init_push_to_cloud(args): """Initiate the local catalog and push it the cloud""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-push-to-cloud]: %s => %s"%(lcat, ccat)) if not isfile(lcat): args.error("[init-push-to-cloud] The local catalog does not exist: %...
Initiate the local catalog by downloading the cloud catalog
def cmd_init_pull_from_cloud(args): """Initiate the local catalog by downloading the cloud catalog""" (lcat, ccat) = (args.local_catalog, args.cloud_catalog) logging.info("[init-pull-from-cloud]: %s => %s"%(ccat, lcat)) if isfile(lcat): args.error("[init-pull-from-cloud] The local catalog alre...
Normal procedure: * Pull from cloud ( if necessary ) * Run Lightroom * Push to cloud
def cmd_normal(args): """Normal procedure: * Pull from cloud (if necessary) * Run Lightroom * Push to cloud """ logging.info("cmd_normal") (lcat, ccat) = (args.local_catalog, args.cloud_catalog) (lmeta, cmeta) = ("%s.lrcloud"%lcat, "%s.lrcloud"%ccat) if not isfile(lcat)...
Return arguments
def parse_arguments(argv=None): """Return arguments""" def default_config_path(): """Returns the platform specific default location of the configure file""" if os.name == "nt": return join(os.getenv('APPDATA'), "lrcloud.ini") else: return join(os.path.expanduser...