code
stringlengths
1
18.2k
& bitfield``). If the resultant bitfield element is non-zero, that element will be interpreted as a "bad" in the output boolean mask and it will be interpreted as "good" otherwise. ``flip_bits`` parameter may be used to flip the bits (``bitwise-NOT``) of the bitmask thus effectively changing the meaning of the ``ignore...
0 effectively will assume that all non-zero elements in the input ``bitfield`` array are to be interpreted as "bad". | When ``ignore_flags`` argument is an Python list of integer bit flags, these flags are added together to create an integer bitmask. Each item in the list must be a flag, i.e., an integer that is an int...
the bits of the resultant bitmask, use ``flip_bits`` parameter. | Alternatively, ``ignore_flags`` may be a string of comma- or '+'-separated list of integer bit flags that should be added together to create an integer bitmask. For example, both ``'4,8'`` and ``'4+8'`` are equivalent and indicate that bit flags 4 and 8 ...
note:: ``'None'``, ``'INDEF'``, and empty (or all white space) strings are special values of string ``ignore_flags`` that are interpreted as `None`. .. note:: Each item in the list must be a flag, i.e., an integer that is an integer power of 2. In addition, for convenience, an arbitrary **single** integer is allowed an...
of ``'4,8'`` one could simply provide string ``'12'``. .. note:: When ``ignore_flags`` is a `str` and when it is prepended with '~', then the meaning of ``ignore_flags`` parameters will be reversed: now it will be interpreted as a list of bit flags to be *used* (or *not ignored*) when deciding which elements of the inp...
string value of ``'~0'`` would be equivalent to setting ``ignore_flags=None``. .. warning:: Because prepending '~' to a string ``ignore_flags`` is equivalent to setting ``flip_bits`` to `True`, ``flip_bits`` cannot be used with string ``ignore_flags`` and it must be set to `None`. flip_bits : bool, None (Default = None...
or built from the bit flags passed through ``ignore_flags`` (only when bit flags are passed as Python lists of integer bit flags). Occasionally, it may be useful to *consider only specific bit flags* in the ``bitfield`` array when creating a boolean mask as opposite to *ignoring* specific bit flags as ``ignore_flags`` ...
bitmask created from ``ignore_flags`` flags which effectively changes the meaning of the ``ignore_flags`` parameter from "ignore" to "use only" these flags. Setting ``flip_bits`` to `None` means that no bit flipping will be performed. Bit flipping for string lists of bit flags must be specified by prepending '~' to str...
be set to either `True` or `False` **ONLY** when ``ignore_flags`` is either an integer bitmask or a Python list of integer bit flags. When ``ignore_flags`` is either `None` or a string list of flags, ``flip_bits`` **MUST** be set to `None`. good_mask_value : int, bool (Default = True) This parameter is used to derive t...
output boolean mask array that correspond to the "good" bit fields (that are 0 after zeroing bits specified by ``ignore_flags``) in the input ``bitfield`` array. When ``good_mask_value`` is non-zero or `True` then values in the output boolean mask array corresponding to "good" bit fields in ``bitfield`` will be `True` ...
corresponding to "bad" flags will be `False` (or 0). When ``good_mask_value`` is zero or `False` then the values in the output boolean mask array corresponding to "good" bit fields in ``bitfield`` will be `False` (if ``dtype`` is `numpy.bool_`) or 0 (if ``dtype`` is of numerical type) and values of corresponding to "ba...
The desired data-type for the output binary mask array. Returns ------- mask : numpy.ndarray Returns an array of the same dimensionality as the input ``bitfield`` array whose elements can have two possible values, e.g., `True` or `False` (or 1 or 0 for integer ``dtype``) according to values of to the input ``bitfield``...
import bitmask >>> import numpy as np >>> dqbits = np.asarray([[0,0,1,2,0,8,12,0],[10,4,0,0,0,16,6,0]]) >>> bitmask.bitfield_to_boolean_mask(dqbits, ignore_flags=0, dtype=int) array([[1, 1, 0, 0, 1, 0, 0, 1], [0, 0, 1, 1, 1, 0, 0, 1]]) >>> bitmask.bitfield_to_boolean_mask(dqbits, ignore_flags=0, dtype=bool) array([[ Tr...
0], [1, 0, 0, 0, 0, 1, 0, 0]]) >>> bitmask.bitfield_to_boolean_mask(dqbits, ignore_flags=~6, good_mask_value=0, dtype=int) array([[0, 0, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0]]) >>> bitmask.bitfield_to_boolean_mask(dqbits, ignore_flags=6, flip_bits=True, good_mask_value=0, dtype=int) array([[0, 0, 0, 1, 0, 0, 1, 0...
0], [1, 1, 0, 0, 0, 0, 1, 0]]) >>> bitmask.bitfield_to_boolean_mask(dqbits, ignore_flags=[2, 4], flip_bits=True, good_mask_value=0, dtype=int) array([[0, 0, 0, 1, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 1, 0]]) """ bitfield = np.asarray(bitfield) if not np.issubdtype(bitfield.dtype, np.integer): raise TypeError("Input bitfield...
mask = np.zeros_like(bitfield, dtype=dtype) return mask # filter out bits beyond the maximum supported by the data type: ignore_mask = ignore_mask & SUPPORTED_FLAGS # invert the "ignore" mask: ignore_mask = np.bitwise_not(ignore_mask, dtype=bitfield.dtype, casting='unsafe') mask = np.empty_like(bitfield, dtype=np.bool_...
def interpret_bits_value(val): """ Converts input bits value from string to a single integer value or None. If a comma- or '+'-separated set of values are provided, they are summed. .. note:: In order to flip the bits of the final result (after summation), for input of `str` type, prepend '~' to the input string. '~' m...
to each bit flag! Parameters ---------- val : int, str, None An integer bit mask or flag, `None`, or a comma- or '+'-separated string list of integer bit values. If `val` is a `str` and if it is prepended with '~', then the output bit mask will have its bits flipped (compared to simple sum of input val). Returns ------...
None Returns and integer bit mask formed from the input bit value or `None` if input `val` parameter is `None` or an empty string. If input string value was prepended with '~', then returned value will have its bits flipped (inverse mask). """ if isinstance(val, int) or val is None: return val else: val = str(val).stri...
else: flip_bits = False if val.startswith('('): if val.endswith(')'): val = val[1:-1].strip() else: raise ValueError('Unbalanced parantheses or incorrect syntax.') if ',' in val: valspl = val.split(',') bitmask = 0 for v in valspl: bitmask += int(v) elif '+' in val: valspl = val.split('+') bitmask = 0 for v in valspl: ...
if flip_bits: bitmask = ~bitmask return bitmask
def bitmask2mask(bitmask, ignore_bits, good_mask_value=1, dtype=np.bool_): """ bitmask2mask(bitmask, ignore_bits, good_mask_value=1, dtype=numpy.bool\_) Interprets an array of bit flags and converts it to a "binary" mask array. This function is particularly useful to convert data quality arrays to binary masks. Paramet...
"good" values. However, see `ignore_bits` parameter on how to ignore some bits in the `bitmask` array. ignore_bits : int, str, None An integer bit mask, `None`, or a comma- or '+'-separated string list of integer bit values that indicate what bits in the input `bitmask` should be *ignored* (i.e., zeroed). If `ignore_bi...
meaning of `ignore_bits` parameters will be reversed: now it will be interpreted as a list of bits to be *used* (or *not ignored*) when deciding what elements of the input `bitmask` array are "bad". The `ignore_bits` parameter is the integer sum of all of the bit values from the input `bitmask` array that should be con...
example, if values in the `bitmask` array can be combinations of 1, 2, 4, and 8 flags and one wants to consider that values having *only* bit flags 2 and/or 4 as being "good", then `ignore_bits` should be set to 2+4=6. Then a `bitmask` element having values 2,4, or 6 will be considered "good", while an element with a v...
will be interpreted as "bad". Alternatively, one can enter a comma- or '+'-separated list of integer bit flags that should be added to obtain the final "good" bits. For example, both ``4,8`` and ``4+8`` are equivalent to setting `ignore_bits` to 12. See :py:func:`interpret_bits_value` for examples. | Setting `ignore_bi...
`ignore_bits` to 0 effectively will assume that all non-zero elements in the input `bitmask` array are to be interpreted as "bad". | In order to reverse the meaning of the `ignore_bits` parameter from indicating bits in the values of `bitmask` elements that should be ignored when deciding which elements are "good" (the...
bits should be used exclusively in deciding whether a `bitmask` element is "good", prepend '~' to the string value. For example, in order to use **only** (or **exclusively**) flags 4 and 8 (2nd and 3rd bits) in the values of the input `bitmask` array when deciding whether or not that element is "good", set `ignore_bits...
with an `int` input value (except for 0), enter -(4+8+1)=-9. Following this convention, a `ignore_bits` string value of ``'~0'`` would be equivalent to setting ``ignore_bits=None``. good_mask_value : int, bool (Default = 1) This parameter is used to derive the values that will be assigned to the elements in the output ...
specified by `ignore_bits`) in the input `bitmask` array. When `good_mask_value` is non-zero or `True` then values in the output mask array corresponding to "good" bit flags in `bitmask` will be 1 (or `True` if `dtype` is `bool`) and values of corresponding to "bad" flags will be 0. When `good_mask_value` is zero or `F...
flags in `bitmask` will be 0 (or `False` if `dtype` is `bool`) and values of corresponding to "bad" flags will be 1. dtype : data-type (Default = numpy.uint8) The desired data-type for the output binary mask array. Returns ------- mask : numpy.ndarray Returns an array whose elements can have two possible values, e.g., ...
according to values of to the input `bitmask` elements, `ignore_bits` parameter, and the `good_mask_value` parameter. """ if not np.issubdtype(bitmask.dtype, np.integer): raise TypeError("Input 'bitmask' array must be of integer type.") ignore_bits = interpret_bits_value(ignore_bits) if ignore_bits is None: if good_mas...
return mask.astype(dtype=dtype, subok=False, copy=False)
def output_text(account, all_data, show_hourly=False): """Format data to get a readable output.""" print(""" ################################# # Hydro Quebec data for account # # {} #################################""".format(account)) for contract, data in all_data.items(): data['contract'] = contract if data['period_...
=========== Period day number: {d[period_length]:d} Period total days: {d[period_total_days]:d} days Period current bill =================== Total Bill: {d[period_total_bill]:.2f} $ Projection bill: {d[period_projection]:.2f} $ Mean Daily Bill: {d[period_mean_daily_bill]:.2f} $ Total period consumption ================...
= (""" Yesterday consumption ===================== Temperature: {d[yesterday_average_temperature]:d} °C Lower price: {d[yesterday_lower_price_consumption]:.2f} kWh Higher price: {d[yesterday_higher_price_consumption]:.2f} kWh Total: {d[yesterday_total_consumption]:.2f} kWh""") print(output3.format(d=data)) if show_hour...
print(msg) if data['annual_total_bill']: output3 = (""" Annual Total ============ Start date: {d[annual_date_start]} End date: {d[annual_date_end]} Total bill: {d[annual_total_bill]} $ Mean daily bill: {d[annual_mean_daily_bill]} $ Total consumption: {d[annual_total_consumption]} kWh Mean dailyconsumption: {d[annual_me...
def output_influx(data): """Print data using influxDB format.""" for contract in data: # Pop yesterdays data yesterday_data = data[contract]['yesterday_hourly_consumption'] del data[contract]['yesterday_hourly_consumption'] # Print general data out = "pyhydroquebec,contract=" + contract + " " for index, key in enumerat...
+ "=" + str(data[contract][key]) out += " " + str(int(datetime.datetime.now(HQ_TIMEZONE).timestamp() * 1000000000)) print(out) # Print yesterday values yesterday = datetime.datetime.now(HQ_TIMEZONE) - datetime.timedelta(days=1) yesterday = yesterday.replace(minute=0, hour=0, second=0, microsecond=0) for hour in yesterd...
yesterday_str))
def which_darwin_linkage(force_otool_check=False): """ Convenience function. Returns one of ('x11', 'aqua') in answer to the question of whether this is an X11-linked Python/tkinter, or a natively built (framework, Aqua) one. This is only for OSX. This relies on the assumption that on OSX, PyObjC is installed in the Fr...
otool. One driving requirement here is to try to make the determination quickly and quietly without actually importing/loading any GUI libraries. We even want to avoid importing tkinter if we can. """ # sanity check assert sys.platform=='darwin', 'Incorrect usage, not on OSX' # If not forced to run otool, then make som...
time and do not # attempt to initialize any graphics. if not force_otool_check: # There will (for now) only ever be an aqua-linked Python/tkinter # when using Ureka on darwin, so this is an easy short-circuit check. if 'UR_DIR' in os.environ: return "aqua" # There will *usually* be PyObjC modules on sys.path on the nat...
correct on Python 2.x, as # of 2012. This is kludgy but quick and effective. sp = ",".join(sys.path) sp = sp.lower().strip(',') if '/pyobjc' in sp or 'pyobjc,' in sp or 'pyobjc/' in sp or sp.endswith('pyobjc'): return "aqua" # Try one more thing - look for the physical PyObjC install dir under site-packages # The assum...
as of the # combination of Python2.7.9/PyObjC3.0.4/2015. sitepacksloc = os.path.split(os.__file__)[0]+'/site-packages/objc' if os.path.exists(sitepacksloc): return "aqua" # OK, no trace of PyObjC found - need to fall through to the forced otool check. # Use otool shell command if PY3K: import tkinter as TKNTR else: imp...
'aqua' else: return 'unknown' libs = subprocess.check_output(('/usr/bin/otool', '-L', tk_dyn_lib)).decode('ascii') if libs.find('/libX11.') >= 0: return "x11" else: return "aqua"
def get_dc_owner(raises, mask_if_self): """ Convenience function to return owner of /dev/console. If raises is True, this raises an exception on any error. If not, it returns any error string as the owner name. If owner is self, and if mask_if_self, returns "<self>".""" try: from pwd import getpwuid owner_uid = os.stat...
return owner_name except Exception as e: if raises: raise e else: return str(e)
def to_jd(year, month, day): '''Determine Julian day from Bahai date''' gy = year - 1 + EPOCH_GREGORIAN_YEAR if month != 20: m = 0 else: if isleap(gy + 1): m = -14 else: m = -15 return gregorian.to_jd(gy, 3, 20) + (19 * (month - 1)) + m + day
def from_jd(jd): '''Calculate Bahai date from Julian day''' jd = trunc(jd) + 0.5 g = gregorian.from_jd(jd) gy = g[0] bstarty = EPOCH_GREGORIAN_YEAR if jd <= gregorian.to_jd(gy, 3, 20): x = 1 else: x = 0 # verify this next line... bys = gy - (bstarty + (((gregorian.to_jd(gy, 1, 1) <= jd) and x))) year = bys + 1 days = j...
1) bld = to_jd(year, 20, 1) if jd >= bld: month = 20 else: month = trunc(days / 19) + 1 day = int((jd + 1) - to_jd(year, month, 1)) return year, month, day
def to_jd(baktun, katun, tun, uinal, kin): '''Determine Julian day from Mayan long count''' return EPOCH + (baktun * 144000) + (katun * 7200) + (tun * 360) + (uinal * 20) + kin
def from_jd(jd): '''Calculate Mayan long count from Julian day''' d = jd - EPOCH baktun = trunc(d / 144000) d = (d % 144000) katun = trunc(d / 7200) d = (d % 7200) tun = trunc(d / 360) d = (d % 360) uinal = trunc(d / 20) kin = int((d % 20)) return (baktun, katun, tun, uinal, kin)
def to_haab(jd): '''Determine Mayan Haab "month" and day from Julian day''' # Number of days since the start of the long count lcount = trunc(jd) + 0.5 - EPOCH # Long Count begins 348 days after the start of the cycle day = (lcount + 348) % 365 count = day % 20 month = trunc(day / 20) return int(count), HAAB_MONTHS[mon...
def to_tzolkin(jd): '''Determine Mayan Tzolkin "month" and day from Julian day''' lcount = trunc(jd) + 0.5 - EPOCH day = amod(lcount + 4, 13) name = amod(lcount + 20, 20) return int(day), TZOLKIN_NAMES[int(name) - 1]
def _haab_count(day, month): '''Return the count of the given haab in the cycle. e.g. 0 Pop == 1, 5 Wayeb' == 365''' if day < 0 or day > 19: raise IndexError("Invalid day number") try: i = HAAB_MONTHS.index(month) except ValueError: raise ValueError("'{0}' is not a valid Haab' month".format(month)) return min(i * 20, 3...
def tzolkin_generator(number=None, name=None): '''For a given tzolkin name/number combination, return a generator that gives cycle, starting with the input''' # By default, it will start at the beginning number = number or 13 name = name or "Ajaw" if number > 13: raise ValueError("Invalid day number") if name not in TZ...
count))) for i in ranged: yield _tzolkin_from_count(i)
def longcount_generator(baktun, katun, tun, uinal, kin): '''Generate long counts, starting with input''' j = to_jd(baktun, katun, tun, uinal, kin) while True: yield from_jd(j) j = j + 1
def next_haab(month, jd): '''For a given haab month and a julian day count, find the next start of that month on or after the JDC''' if jd < EPOCH: raise IndexError("Input day is before Mayan epoch.") hday, hmonth = to_haab(jd) if hmonth == month: days = 1 - hday else: count1 = _haab_count(hday, hmonth) count2 = _haab_...
haab of given jd and desired haab days = (count2 - count1) % 365 # add in the number of days and return new jd return jd + days
def next_tzolkin(tzolkin, jd): '''For a given tzolk'in day, and a julian day count, find the next occurrance of that tzolk'in after the date''' if jd < EPOCH: raise IndexError("Input day is before Mayan epoch.") count1 = _tzolkin_count(*to_tzolkin(jd)) count2 = _tzolkin_count(*tzolkin) add_days = (count2 - count1) % 26...
def next_tzolkin_haab(tzolkin, haab, jd): '''For a given haab-tzolk'in combination, and a Julian day count, find the next occurrance of the combination after the date''' # get H & T of input jd, and their place in the 18,980 day cycle haabcount = _haab_count(*to_haab(jd)) haab_desired_count = _haab_count(*haab) # How m...
365 possible_haab = set(h + haab_days for h in range(0, 18980, 365)) tzcount = _tzolkin_count(*to_tzolkin(jd)) tz_desired_count = _tzolkin_count(*tzolkin) # How many days between the input day and the desired day? tzolkin_days = (tz_desired_count - tzcount) % 260 possible_tz = set(t + tzolkin_days for t in range(0, 189...
def haab_monthcalendar(baktun=None, katun=None, tun=None, uinal=None, kin=None, jdc=None): '''For a given long count, return a calender of the current haab month, divided into tzolkin "weeks"''' if not jdc: jdc = to_jd(baktun, katun, tun, uinal, kin) haab_number, haab_month = to_haab(jdc) first_j = jdc - haab_number + ...
tzolkin_start_number - 1 rpad = 13 - (tzolkin_start_number + 19 % 13) monlen = month_length(haab_month) days = [None] * lpad + list(range(1, monlen + 1)) + rpad * [None] def g(x, generate): if x is None: return None return next(generate) return [[(k, g(k, gen_tzolkin), g(k, gen_longcount)) for k in days[i:i + 13]] for ...
def _update_data(self, data={}): '''Update the data in this object.''' # Store the changes to prevent this update from affecting it pending_changes = self._changes or {} try: del self._changes except: pass # Map custom fields into our custom fields object try: custom_field_data = data.pop('custom_fields') except KeyErr...
lookup_key = self._field_type.get(key, key) # if it's a datetime object, turn into proper DT object if lookup_key == 'datetime' or lookup_key == 'date': self.__dict__[key] = datetime_parse(value) else: # Check to see if there's cache data for this item. # Will return an object if it's recognized as one. self.__dict__[k...
out self._changes = pending_changes
def _remap_tag_to_tag_id(cls, tag, new_data): '''Remaps a given changed field from tag to tag_id.''' try: value = new_data[tag] except: # If tag wasn't changed, just return return tag_id = tag + '_id' try: # Remap the ID change to the required field new_data[tag_id] = value['id'] except: try: # Try and grab the id of t...
field is not a dict or object, just use whatever value was given new_data[tag_id] = value # Remove the tag from the changed data del new_data[tag]
def _add_item_manager(self, key, item_class, **paths): ''' Add an item manager to this object. ''' updated_paths = {} for path_type, path_value in paths.iteritems(): updated_paths[path_type] = path_value.format(**self.__dict__) manager = Redmine_Items_Manager(self._redmine, item_class, **updated_paths) self.__dict__[ke...
def save(self): '''Save all changes on this item (if any) back to Redmine.''' self._check_custom_fields() if not self._changes: return None for tag in self._remap_to_id: self._remap_tag_to_tag_id(tag, self._changes) # Check for custom handlers for tags for tag, type in self._field_type.items(): try: raw_data = self._ch...
continue # Convert date type to a date string that Redmine expects if type == 'date': try: self._changes[tag] = raw_data.strftime('%Y-%m-%d') except AttributeError: continue try: self._update(self._changes) except: raise else: # Successful save, woot! Now clear the changes dict self._changes.clear()
def refresh(self): '''Refresh this item from data on the server. Will save any unsaved data first.''' if not self._item_path: raise AttributeError('refresh is not available for %s' % self._type) if not self.id: raise RedmineError('%s did not come from the Redmine server - no link.' % self._type) try: self.save() except...
self._redmine.unwrap_json(self._type, json_data) self._update_data(data=data)
def _get_changes(self): '''Get all changed values.''' result = dict( (f['id'], f.get('value','')) for f in self._data if f.get('changed', False) ) self._clear_changes return result
def iteritems(self, **options): '''Return a query interator with (id, object) pairs.''' iter = self.query(**options) while True: obj = iter.next() yield (obj.id, obj)
def _objectify(self, json_data=None, data={}): '''Return an object derived from the given json data.''' if json_data: # Parse the data try: data = json.loads(json_data) except ValueError: # If parsing failed, then raise the string which likely contains an error message instead of data raise RedmineError(json_data) # Ch...
try: data = data[self._item_type] except KeyError: pass # Either returns a new item or updates the item in the cache and returns that return self._redmine.check_cache(self._item_type, data, self._object)
def new(self, **dict): '''Create a new item with the provided dict information. Returns the new item.''' if not self._item_new_path: raise AttributeError('new is not available for %s' % self._item_name) # Remap various tag to tag_id for tag in self._object._remap_to_id: self._object._remap_tag_to_tag_id(tag, dict) targ...
def get(self, id, **options): '''Get a single item with the given ID''' if not self._item_path: raise AttributeError('get is not available for %s' % self._item_name) target = self._item_path % id json_data = self._redmine.get(target, **options) data = self._redmine.unwrap_json(self._item_type, json_data) data['_source_...
def update(self, id, **dict): '''Update a given item with the passed data.''' if not self._item_path: raise AttributeError('update is not available for %s' % self._item_name) target = (self._update_path or self._item_path) % id payload = json.dumps({self._item_type:dict}) self._redmine.put(target, payload) return None
def delete(self, id): '''Delete a single item with the given ID''' if not self._item_path: raise AttributeError('delete is not available for %s' % self._item_name) target = self._item_path % id self._redmine.delete(target) return None
def query(self, **options): '''Return an iterator for the given items.''' if not self._query_path: raise AttributeError('query is not available for %s' % self._item_name) last_item = 0 offset = 0 current_item = None limit = options.get('limit', 25) options['limit'] = limit target = self._query_path while True: options[...
json try: data = json.loads(json_data) except: raise RedmineError(json_data) # The data is enclosed in the _query_container item # That is, {'issues':{(issue1),(issue2)...}, 'total_count':##} data_container = data[self._query_container] for item_data in data_container: yield(self._objectify(data=item_data)) # If the co...
except: # If we don't even have a 'total_count', we're done. break
def _setup_authentication(self, username, password): '''Create the authentication object with the given credentials.''' ## BUG WORKAROUND if self.version < 1.1: # Version 1.0 had a bug when using the key parameter. # Later versions have the opposite bug (a key in the username doesn't function) if not username: username...
same combination on my luggage! (required dummy value) #realm = 'Redmine API' - doesn't always work # create a password manager password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() password_mgr.add_password(None, self._url, username, password ) handler = urllib2.HTTPBasicAuthHandler( password_mgr ) # create "opener...
def open_raw(self, page, parms=None, payload=None, HTTPrequest=None, payload_type='application/json' ): '''Opens a page from the server with optional XML. Returns a response file-like object''' if not parms: parms={} # if we're using a key, but it's not going in the header, add it to the parms array if self._key and no...
'?' + urllib.urlencode( parms ) fullUrl = self._url + page #debug if self.debug: print fullUrl + urldata # register this url to be used with the opener # must be registered for each unique path try: self._opener.open( fullUrl ) except AttributeError: # No authentication pass # Set up the request if HTTPrequest: request...
+ urldata ) # If the key is set and in the header, add it if self._key and self.key_in_header: request.add_header('X-Redmine-API-Key', self._key) # If impersonation is set, add header if self.impersonate and self.impersonation_supported: request.add_header('X-Redmine-Switch-User', self.impersonate) # get the data and r...
def open(self, page, parms=None, payload=None, HTTPrequest=None ): '''Opens a page from the server with optional content. Returns the string response.''' response = self.open_raw( page, parms, payload, HTTPrequest ) return response.read()
def post(self, page, payload, parms=None ): '''Posts a string payload to the server - used to make new Redmine items. Returns an JSON string or error.''' if self.readonlytest: print 'Redmine read only test: Pretending to create: ' + page return payload else: return self.open( page, parms, payload )
def put(self, page, payload, parms=None ): '''Puts an XML object on the server - used to update Redmine items. Returns nothing useful.''' if self.readonlytest: print 'Redmine read only test: Pretending to update: ' + page else: return self.open( page, parms, payload, HTTPrequest=self.PUT_Request )
def delete(self, page ): '''Deletes a given object on the server - used to remove items from Redmine. Use carefully!''' if self.readonlytest: print 'Redmine read only test: Pretending to delete: ' + page else: return self.open( page, HTTPrequest=self.DELETE_Request )
def unwrap_json(self, type, json_data): '''Decodes a json string, and unwraps any 'type' it finds within.''' # Parse the data try: data = json.loads(json_data) except ValueError: # If parsing failed, then raise the string which likely contains an error message instead of data raise RedmineError(json_data) # Check to se...
try: data = data[type] except KeyError: pass return data
def find_all_item_classes(self): '''Finds and stores a reference to all Redmine_Item subclasses for later use.''' # This is a circular import, but performed after the class is defined and an object is instatiated. # We do this in order to get references to any objects definitions in the redmine.py file # without requir...
with the proper name. import redmine as public_classes item_class = {} for key, value in public_classes.__dict__.items(): try: if issubclass(value, Redmine_Item): item_class[key.lower()] = value except: continue self.item_class = item_class