docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Search word from FM-index Params: <str> | <Sequential> query <bool> _or <list <str> > ignores Return: <list>SEARCH_RESULT(<int> document_id, <list <int> > counts <str> doc)
def search(self, query, _or=False, ignores=[]): if isinstance(query, str): dids = MapIntInt({}) self.fm.search(query, dids) dids = dids.asdict() result = [] for did in sorted(dids.keys()): doc = self.fm.get_document(did) ...
991,750
Count word from FM-index Params: <str> | <Sequential> query <bool> _or <list <str> > ignores Return: <int> counts
def count(self, query, _or=False): if isinstance(query, str): return self.fm.count(query, MapIntInt({})) else: search_results = [] for q in query: dids = MapIntInt({}) self.fm.search(q, dids) search_results.appe...
991,751
Handles token authentication for Neurio Client. Args: key (string): your Neurio API key secret (string): your Neurio API secret
def __init__(self, key, secret): self.__key = key self.__secret = secret if self.__key is None or self.__secret is None: raise ValueError("Key and secret must be set.")
992,192
The Neurio API client. Args: token_provider (TokenProvider): object providing authentication services
def __init__(self, token_provider): if token_provider is None: raise ValueError("token_provider is required") if not isinstance(token_provider, TokenProvider): raise ValueError("token_provider must be instance of TokenProvider") self.__token = token_provider.get_token()
992,194
Get the information for a specified appliance Args: appliance_id (string): identifiying string of appliance Returns: list: dictionary object containing information about the specified appliance
def get_appliance(self, appliance_id): url = "https://api.neur.io/v1/appliances/%s"%(appliance_id) headers = self.__gen_headers() headers["Content-Type"] = "application/json" r = requests.get(url, headers=headers) return r.json()
992,196
Get the appliances added for a specified location. Args: location_id (string): identifiying string of appliance Returns: list: dictionary objects containing appliances data
def get_appliances(self, location_id): url = "https://api.neur.io/v1/appliances" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "locationId": location_id, } url = self.__append_url_params(url, params) r = requests.get(url, headers=headers...
992,197
Gets current sample from *local* Neurio device IP address. This is a static method. It doesn't require a token to authenticate. Note, call get_user_information to determine local Neurio IP addresses. Args: ip (string): address of local Neurio device Returns: dictionary object containing ...
def get_local_current_sample(ip): valid_ip_pat = re.compile( "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" ) if not valid_ip_pat.match(ip): raise ValueError("ip address invalid") url = "http://%s/current-sample" % (ip) headers = { "Content-...
992,200
Get recent samples, one sample per second for up to the last 2 minutes. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` last (string): starting range, as ISO8601 timestamp Returns: list: dictionary objects containing sample data
def get_samples_live(self, sensor_id, last=None): url = "https://api.neur.io/v1/samples/live" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "sensorId": sensor_id } if last: params["last"] = last url = self.__append_url_params(url, params) ...
992,201
Get the last sample recorded by the sensor. Args: sensor_id (string): hexadecimal id of the sensor to query, e.g. ``0x0013A20040B65FAD`` Returns: list: dictionary objects containing sample data
def get_samples_live_last(self, sensor_id): url = "https://api.neur.io/v1/samples/live/last" headers = self.__gen_headers() headers["Content-Type"] = "application/json" params = { "sensorId": sensor_id } url = self.__append_url_params(url, params) r = requests.get(url, headers=headers) ...
992,202
Gets the current user information, including sensor ID Args: None Returns: dictionary object containing information about the current user
def get_user_information(self): url = "https://api.neur.io/v1/users/current" headers = self.__gen_headers() headers["Content-Type"] = "application/json" r = requests.get(url, headers=headers) return r.json()
992,204
A simple wrapper function that creates a handler function by using on the retry_loop function. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount time to delay between retries. ...
def retry_handler(retries=0, delay=timedelta(), conditions=[]): delay_in_seconds = delay.total_seconds() return partial(retry_loop, retries, delay_in_seconds, conditions)
992,576
A decorator for making a function that retries on failure. Args: retries (Integral): The number of times to retry if a failure occurs. delay (timedelta, optional, 0 seconds): A timedelta representing the amount of time to delay between retries. conditions (list): A list of retry...
def retry(retries=0, delay=timedelta(), conditions=[]): delay_in_seconds = delay.total_seconds() def decorator(function): @wraps(function) def wrapper(*args, **kwargs): func = partial(function, *args, **kwargs) return retry_loop(retries, delay_...
992,577
Returns a retry condition which will run the supplied function in either on_value or on_exception depending if kind == 'exception' or 'value' Args: function: The function to run. kind: the type of condition exception or value based.
def __init__(self, function, kind='exception'): self._function = function self._kind = kind if kind != 'exception' and kind != 'value': raise ValueError(kind)
992,579
Latest trading day w.r.t given dt Args: dt: date of reference cal: trading calendar Returns: pd.Timestamp: last trading day Examples: >>> trade_day('2018-12-25').strftime('%Y-%m-%d') '2018-12-24'
def trade_day(dt, cal='US'): from xone import calendar dt = pd.Timestamp(dt).date() return calendar.trading_dates(start=dt - pd.Timedelta('10D'), end=dt, calendar=cal)[-1]
992,690
on axes plot the signal contributions args: :: ax : matplotlib.axes.AxesSubplot object z : np.ndarray T : list, [tstart, tstop], which timeinterval ylims : list, set range of yaxis to scale with other plots fancy : bool, scaling_factor : float, scaling facto...
def plot_signal_sum(ax, z, fname='LFPsum.h5', unit='mV', ylabels=True, scalebar=True, vlimround=None, T=[0, 1000], color='k', label=''): #open file and get data, samplingrate f = h5py.File(fname) data = f['data'].value dataT = data.T -...
992,736
mls on axes plot the correlation between x0 and x1 args: :: x0 : first dataset x1 : second dataset - e.g., the multichannel LFP ax : matplotlib.axes.AxesSubplot object title : text to be used as current axis object title
def plot_correlation(z_vec, x0, x1, ax, lag=20., title='firing_rate vs LFP'): zvec = np.r_[z_vec] zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]] xcorr_all=np.zeros((np.size(z_vec), x0.shape[0])) for i, z in enumerate(z_vec): x2 = x1[i, ] xcorr1 = np.correlate(normalize(x0), ...
992,743
Decorator to profile functions with cProfile Args: func: python function Returns: profile report References: https://osf.io/upav8/
def profile(func): def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() res = func(*args, **kwargs) pr.disable() s = io.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats('cumulative') ps.print_stats() print(s.getvalue()) r...
992,813
Represent a number-string in the form of a tuple of digits. "868.0F" -> (8, 6, 8, '.', 0, 15) Args: string - Number represented as a string of digits. Returns: Number represented as an iterable container of digits >>> represent_as_tuple('868.0F') (8, 6, 8, '.', 0, 15)
def represent_as_tuple(string): keep = (".", "[", "]") return tuple(str_digit_to_int(c) if c not in keep else c for c in string)
992,995
Represent a number in the form of a string. (8, 6, 8, '.', 0, 15) -> "868.0F" Args: iterable - Number represented as an iterable container of digits. Returns: Number represented as a string of digits. >>> represent_as_string((8, 6, 8, '.', 0, 15)) '868.0F'
def represent_as_string(iterable): keep = (".", "[", "]") return "".join(tuple(int_to_str_digit(i) if i not in keep else i for i in iterable))
992,996
Returns a tuple of the integer and fractional parts of a number. Args: number(iterable container): A number in the following form: (..., ".", int, int, int, ...) Returns: (integer_part, fractional_part): tuple. Example: >>> integer_fractional_parts((1,2,3,"."...
def integer_fractional_parts(number): radix_point = number.index(".") integer_part = number[:radix_point] fractional_part = number[radix_point:] return(integer_part, fractional_part)
992,999
Converts a decimal integer to a specific base. Args: decimal(int) A base 10 number. output_base(int) base to convert to. Returns: A tuple of digits in the specified base. Examples: >>> from_base_10_int(255) (2, 5, 5) >>> from_base_10_int(255, 16...
def from_base_10_int(decimal, output_base=10): if decimal <= 0: return (0,) if output_base == 1: return (1,) * decimal length = digits(decimal, output_base) converted = tuple(digit(decimal, i, output_base) for i in range(length)) return converted[::-1]
993,000
Converts an integer in any base into it's decimal representation. Args: n - An integer represented as a tuple of digits in the specified base. input_base - the base of the input number. Returns: integer converted into base 10. Example: >>> to_base_10_int((8,1), 1...
def to_base_10_int(n, input_base): return sum(c * input_base ** i for i, c in enumerate(n[::-1]))
993,001
Removes trailing zeros. Args: n: The number to truncate. This number should be in the following form: (..., '.', int, int, int, ..., 0) Returns: n with all trailing zeros removed >>> truncate((9, 9, 9, '.', 9, 9, 9, 9, 0, 0, 0, 0)) (9, 9, 9, '.', 9, 9...
def truncate(n): count = 0 for digit in n[-1::-1]: if digit != 0: break count += 1 return n[:-count] if count > 0 else n
993,003
Converts a string character to a decimal number. Where "A"->10, "B"->11, "C"->12, ...etc Args: chr(str): A single character in the form of a string. Returns: The integer value of the input string digit.
def str_digit_to_int(chr): # 0 - 9 if chr in ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"): n = int(chr) else: n = ord(chr) # A - Z if n < 91: n -= 55 # a - z or higher else: n -= 61 return n
993,004
Converts a positive integer, to a single string character. Where: 9 -> "9", 10 -> "A", 11 -> "B", 12 -> "C", ...etc Args: n(int): A positve integer number. Returns: The character representation of the input digit of value n (str).
def int_to_str_digit(n): # 0 - 9 if n < 10: return str(n) # A - Z elif n < 36: return chr(n + 55) # a - z or higher else: return chr(n + 61)
993,005
Expands a recurring pattern within a number. Args: number(tuple): the number to process in the form: (int, int, int, ... ".", ... , int int int) repeat: the number of times to expand the pattern. Returns: The original number with recurring pattern expanded. E...
def expand_recurring(number, repeat=5): if "[" in number: pattern_index = number.index("[") pattern = number[pattern_index + 1:-1] number = number[:pattern_index] number = number + pattern * (repeat + 1) return number
993,007
Provide interface for multiprocessing Args: func: callable functions keys: keys in kwargs that want to use process max_procs: max number of processes show_proc: whether to show process affinity: CPU affinity **kwargs: kwargs for func
def run(func, keys, max_procs=None, show_proc=False, affinity=None, **kwargs): if max_procs is None: max_procs = cpu_count() kw_arr = saturate_kwargs(keys=keys, **kwargs) if len(kw_arr) == 0: return if isinstance(affinity, int): win32process.SetProcessAffinityMask(win32api.GetCurrentProces...
993,357
Saturate all combinations of kwargs Args: keys: keys in kwargs that want to use process **kwargs: kwargs for func
def saturate_kwargs(keys, **kwargs): # Validate if keys are in kwargs and if they are iterable if isinstance(keys, str): keys = [keys] keys = [k for k in keys if k in kwargs and hasattr(kwargs.get(k, None), '__iter__')] if len(keys) == 0: return [] # Saturate coordinates of kwargs kw_corr ...
993,358
Trading dates for given exchange Args: start: start date end: end date calendar: exchange as string Returns: pd.DatetimeIndex: datetime index Examples: >>> bus_dates = ['2018-12-24', '2018-12-26', '2018-12-27'] >>> trd_dates = trading_dates(start='2018-12-2...
def trading_dates(start, end, calendar='US'): kw = dict(start=pd.Timestamp(start, tz='UTC').date(), end=pd.Timestamp(end, tz='UTC').date()) us_cal = getattr(sys.modules[__name__], f'{calendar}TradingCalendar')() return pd.bdate_range(**kw).drop(us_cal.holidays(**kw))
993,522
on colorplot and as background plot the summed CSD contributions args: :: ax : matplotlib.axes.AxesSubplot object T : list, [tstart, tstop], which timeinterval ylims : list, set range of yaxis to scale with other plots fancy : bool, N : integer, set to number of LFP...
def plot_signal_sum_colorplot(ax, params, fname='LFPsum.h5', unit='mV', N=1, ylabels = True, T=[800, 1000], ylim=[-1500, 0], fancy=False, colorbar=True, cmap='spectral_r', absmax=None, transient=200, rasterized=True): f = h5py.File(fname) data = f...
993,590
on axes plot the LFP power spectral density The whole signal duration is used. args: :: ax : matplotlib.axes.AxesSubplot object fancy : bool,
def plot_signal_power_colorplot(ax, params, fname, transient=200, Df=None, mlab=True, NFFT=1000, window=plt.mlab.window_hanning, noverlap=0, cmap = plt.cm.get_cmap('jet', 21), ...
993,592
mls on axes plot the correlation between x0 and x1 args: :: x0 : first dataset x1 : second dataset - the LFP usually here ax : matplotlib.axes.AxesSubplot object title : text to be used as current axis object title normalize : if True, signals are z-scored before...
def plotting_correlation(params, x0, x1, ax, lag=20., scaling=None, normalize=True, color='k', unit=r'$cc=%.3f$' , title='firing_rate vs LFP', scalebar=True, **kwargs): zvec = np.r_[params.electrodeParams['z']] zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1...
993,594
Data file Args: symbol: symbol func: use function to categorize data has_date: contains date in data file root: root path date_type: parameters pass to utils.cur_time, [date, time, time_path, ...] Returns: str: date file
def cache_file(symbol, func, has_date, root, date_type='date'): cur_mod = sys.modules[func.__module__] data_tz = getattr(cur_mod, 'DATA_TZ') if hasattr(cur_mod, 'DATA_TZ') else 'UTC' cur_dt = utils.cur_time(typ=date_type, tz=data_tz, trading=False) if has_date: if hasattr(cur_mod, 'FILE_WI...
993,792
Decorator to save data more easily. Use parquet as data format Args: func: function to load data from data source Returns: wrapped function
def update_data(func): default = dict([ (param.name, param.default) for param in inspect.signature(func).parameters.values() if param.default != getattr(inspect, '_empty') ]) @wraps(func) def wrapper(*args, **kwargs): default.update(kwargs) kwargs.update(de...
993,793
Data file name for given infomation Args: file_fmt: file format in terms of f-strings info: dict, to be hashed and then pass to f-string using 'hash_key' these info will also be passed to f-strings **kwargs: arguments for f-strings Returns: str: data file name
def data_file(file_fmt, info=None, **kwargs): if isinstance(info, dict): kwargs['hash_key'] = hashlib.sha256(json.dumps(info).encode('utf-8')).hexdigest() kwargs.update(info) return utils.fstr(fmt=file_fmt, **kwargs)
993,795
Check the result of an API response. Ideally, this should be done by checking that the value of the ``resultCode`` attribute is 0, but there are endpoints that simply do not follow this rule. Args: data (dict): Response obtained from the API endpoint. key (string): Key to check for existen...
def check_result(data, key=''): if not isinstance(data, dict): return False if key: if key in data: return True return False if 'resultCode' in data.keys(): # OpenBus return True if data.get('resultCode', -1) == 0 else False elif 'code' in dat...
994,201
Build a date string using the provided day, month, year numbers. Automatically adds a leading zero to ``day`` and ``month`` if they only have one digit. Args: day (int): Day number. month(int): Month number. year(int): Year number. hour (int): Hour of the day in 24h format....
def datetime_string(day, month, year, hour, minute): # Overflow if hour < 0 or hour > 23: hour = 0 if minute < 0 or minute > 60: minute = 0 return '%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute)
994,202
Convert a list of integers to a *|* separated string. Args: ints (list[int]|int): List of integer items to convert or single integer to convert. Returns: str: Formatted string
def ints_to_string(ints): if not isinstance(ints, list): return six.u(str(ints)) return '|'.join(six.u(str(l)) for l in ints)
994,203
Obtain the relevant response data in a list. If the response does not already contain the result in a list, a new one will be created to ease iteration in the parser methods. Args: data (dict): API response. key (str): Attribute of the response that contains the result values. Returns...
def response_list(data, key): if key not in data: return None if isinstance(data[key], list): return data[key] else: return [data[key],]
994,204
Calling this function initializes the printer. Args: None Returns: None Raises: None
def initialize(self): self.fonttype = self.font_types['bitmap'] self.send(chr(27)+chr(64))
994,484
Select international character set and changes codes in code table accordingly Args: charset: String. The character set we want. Returns: None Raises: RuntimeError: Invalid charset.
def select_charset(self, charset): charsets = {'USA':0, 'France':1, 'Germany':2, 'UK':3, 'Denmark':4, 'Sweden':5, 'Italy':6, 'Spain':7, 'Japan':8, ...
994,485
Select character code table, from tree built in ones. Args: table: The desired character code table. Choose from 'standard', 'eastern european', 'western european', and 'spare' Returns: None Raises: RuntimeError: Invalid chartable.
def select_char_code_table(self, table): tables = {'standard': 0, 'eastern european': 1, 'western european': 2, 'spare': 3 } if table in tables: self.send(chr(27)+'t'+chr(tables[table])) else: ...
994,486
Set cut setting for printer. Args: cut: The type of cut setting we want. Choices are 'full', 'half', 'chain', and 'special'. Returns: None Raises: RuntimeError: Invalid cut type.
def cut_setting(self, cut): cut_settings = {'full' : 0b00000001, 'half' : 0b00000010, 'chain': 0b00000100, 'special': 0b00001000 } if cut in cut_settings: self.send(chr(27)+'iC'+...
994,487
Calling this function applies the desired action to the printing orientation of the printer. Args: action: The desired printing orientation. 'rotate' enables rotated printing. 'normal' disables rotated printing. Returns: None Raises: RuntimeEr...
def rotated_printing(self, action): if action=='rotate': action='1' elif action=='cancel': action='0' else: raise RuntimeError('Invalid action.') self.send(chr(27)+chr(105)+chr(76)+action)
994,488
Calling this function sets the form feed amount to the specified setting. Args: amount: the form feed setting you desire. Options are '1/8', '1/6', 'x/180', and 'x/60', with x being your own desired amount. X must be a minimum of 24 for 'x/180' and 8 for 'x/60' Returns: ...
def feed_amount(self, amount): n = None if amount=='1/8': amount = '0' elif amount=='1/6': amount = '2' elif re.search('/180', amount): n = re.search(r"(\d+)/180", amount) n = n.group(1) amount = '3' elif re.sea...
994,489
Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000.
def page_length(self, length): mH = length/256 mL = length%256 if length < 12000: self.send(chr(27)+'('+'C'+chr(2)+chr(0)+chr(mL)+chr(mH)) else: raise RuntimeError('Length must be less than 12000.')
994,490
Specify settings for top and bottom margins. Physically printable area depends on media. Args: topmargin: the top margin, in dots. The top margin must be less than the bottom margin. bottommargin: the bottom margin, in dots. The bottom margin must be less than the top margin. ...
def page_format(self, topmargin, bottommargin): tL = topmargin%256 tH = topmargin/256 BL = bottommargin%256 BH = topmargin/256 if (tL+tH*256) < (BL + BH*256): self.send(chr(27)+'('+'c'+chr(4)+chr(0)+chr(tL)+chr(tH)+chr(BL)+chr(BH)) else: r...
994,491
Specify the left margin. Args: margin: The left margin, in character width. Must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter.
def left_margin(self, margin): if margin <= 255 and margin >= 0: self.send(chr(27)+'I'+chr(margin)) else: raise RuntimeError('Invalid margin parameter.')
994,492
Specify the right margin. Args: margin: The right margin, in character width, must be less than the media's width. Returns: None Raises: RuntimeError: Invalid margin parameter
def right_margin(self, margin): if margin >=1 and margin <=255: self.send(chr(27)+'Q'+chr(margin)) else: raise RuntimeError('Invalid margin parameter in function rightMargin')
994,493
Sets tab positions, up to a maximum of 32 positions. Also can clear tab positions. Args: positions -- Either a list of tab positions (between 1 and 255), or 'clear'. Returns: None Raises: RuntimeError: Invalid position parameter. RuntimeEr...
def vert_tab_pos(self, positions): if positions == 'clear': self.send(chr(27)+'B'+chr(0)) return if positions.min < 1 or positions.max >255: raise RuntimeError('Invalid position parameter in function horzTabPos') sendstr = chr(27) + 'D' if...
994,494
Calling this function finishes input of the current line, then moves the vertical print position forward by x/300 inch. Args: amount: how far foward you want the position moved. Actual movement is calculated as amount/300 inches. Returns: None ...
def forward_feed(self, amount): if amount <= 255 and amount >=0: self.send(chr(27)+'J'+chr(amount)) else: raise RuntimeError('Invalid foward feed, must be less than 255 and >= 0')
994,495
Specify vertical print position from the top margin position. Args: amount: The distance from the top margin you'd like, from 0 to 32767 Returns: None Raises: RuntimeError: Invalid vertical position.
def abs_vert_pos(self, amount): mL = amount%256 mH = amount/256 if amount < 32767 and amount > 0: self.send(chr(27)+'('+'V'+chr(2)+chr(0)+chr(mL)+chr(mH)) else: raise RuntimeError('Invalid vertical position in function absVertPos')
994,496
Calling this function sets the absoulte print position for the next data, this is the position from the left margin. Args: amount: desired positioning. Can be a number from 0 to 2362. The actual positioning is calculated as (amount/60)inches from the left margin. ...
def abs_horz_pos(self, amount): n1 = amount%256 n2 = amount/256 self.send(chr(27)+'${n1}{n2}'.format(n1=chr(n1), n2=chr(n2)))
994,497
Sets the alignment of the printer. Args: align: desired alignment. Options are 'left', 'center', 'right', and 'justified'. Anything else will throw an error. Returns: None Raises: RuntimeError: Invalid alignment.
def alignment(self, align): if align=='left': align = '0' elif align=='center': align = '1' elif align=='right': align = '2' elif align=='justified': align = '3' else: raise RuntimeError('Invalid alignment in fu...
994,499
Places/removes frame around text Args: action -- Enable or disable frame. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def frame(self, action): choices = {'on': '1', 'off': '0'} if action in choices: self.send(chr(27)+'if'+choices[action]) else: raise RuntimeError('Invalid action for function frame, choices are on and off')
994,500
Enable/cancel bold printing Args: action: Enable or disable bold printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def bold(self, action): if action =='on': action = 'E' elif action == 'off': action = 'F' else: raise RuntimeError('Invalid action for function bold. Options are on and off') self.send(chr(27)+action)
994,501
Enable/cancel italic printing Args: action: Enable or disable italic printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def italic(self, action): if action =='on': action = '4' elif action=='off': action = '5' else: raise RuntimeError('Invalid action for function italic. Options are on and off') self.send(chr(27)+action)
994,502
Enable/cancel doublestrike printing Args: action: Enable or disable doublestrike printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def double_strike(self, action): if action == 'on': action = 'G' elif action == 'off': action = 'H' else: raise RuntimeError('Invalid action for function doubleStrike. Options are on and off') self.send(chr(27)+action)
994,503
Enable/cancel doublewidth printing Args: action: Enable or disable doublewidth printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def double_width(self, action): if action == 'on': action = '1' elif action == 'off': action = '0' else: raise RuntimeError('Invalid action for function doubleWidth. Options are on and off') self.send(chr(27)+'W'+action)
994,504
Enable/cancel compressed character printing Args: action: Enable or disable compressed character printing. Options are 'on' and 'off' Returns: None Raises: RuntimeError: Invalid action.
def compressed_char(self, action): if action == 'on': action = 15 elif action == 'off': action = 18 else: raise RuntimeError('Invalid action for function compressedChar. Options are on and off') self.send(chr(action))
994,505
Enable/cancel underline printing Args: action -- Enable or disable underline printing. Options are '1' - '4' and 'cancel' Returns: None Raises: None
def underline(self, action): if action == 'off': action = '0' self.send(chr(27)+chr(45)+action) else: self.send(chr(27)+chr(45)+action)
994,506
Select font type Choices are: <Bit map fonts> 'brougham' 'lettergothicbold' 'brusselsbit' 'helsinkibit' 'sandiego' <Outline fonts> 'lettergothic' 'brusselsoutline' 'helsinkioutline' Args: font:...
def select_font(self, font): fonts = {'brougham': 0, 'lettergothicbold': 1, 'brusselsbit' : 2, 'helsinkibit': 3, 'sandiego': 4, 'lettergothic': 9, 'brusselsoutline': 10, 'helsink...
994,508
Sets the character style. Args: style: The desired character style. Choose from 'normal', 'outline', 'shadow', and 'outlineshadow' Returns: None Raises: RuntimeError: Invalid character style
def char_style(self, style): styleset = {'normal': 0, 'outline': 1, 'shadow': 2, 'outlineshadow': 3 } if style in styleset: self.send(chr(27) + 'q' + chr(styleset[style])) else: raise...
994,509
Specifies proportional characters. When turned on, the character spacing set with charSpacing. Args: action: Turn proportional characters on or off. Returns: None Raises: RuntimeError: Invalid action.
def proportional_char(self, action): actions = {'off': 0, 'on': 1 } if action in actions: self.send(chr(27)+'p'+action) else: raise RuntimeError('Invalid action in function proportionalChar')
994,510
Specifes character spacing in dots. Args: dots: the character spacing you desire, in dots Returns: None Raises: RuntimeError: Invalid dot amount.
def char_spacing(self, dots): if dots in range(0,127): self.send(chr(27)+chr(32)+chr(dots)) else: raise RuntimeError('Invalid dot amount in function charSpacing')
994,511
Choose a template Args: template: String, choose which template you would like. Returns: None Raises: None
def choose_template(self, template): n1 = int(template)/10 n2 = int(template)%10 self.send('^TS'+'0'+str(n1)+str(n2))
994,513
Perform machine operations Args: operations: which operation you would like Returns: None Raises: RuntimeError: Invalid operation
def machine_op(self, operation): operations = {'feed2start': 1, 'feedone': 2, 'cut': 3 } if operation in operations: self.send('^'+'O'+'P'+chr(operations[operation])) else: raise RuntimeEr...
994,514
Set print start trigger. Args: type: The type of trigger you desire. Returns: None Raises: RuntimeError: Invalid type.
def print_start_trigger(self, type): types = {'recieved': 1, 'filled': 2, 'num_recieved': 3} if type in types: self.send('^PT'+chr(types[type])) else: raise RuntimeError('Invalid type.')
994,515
Set print command Args: command: the type of command you desire. Returns: None Raises: RuntimeError: Command too long.
def print_start_command(self, command): size = len(command) if size > 20: raise RuntimeError('Command too long') n1 = size/10 n2 = size%10 self.send('^PS'+chr(n1)+chr(n2)+command)
994,516
Set recieved char count limit Args: count: the amount of received characters you want to stop at. Returns: None Raises: None
def received_char_count(self, count): n1 = count/100 n2 = (count-(n1*100))/10 n3 = (count-((n1*100)+(n2*10))) self.send('^PC'+chr(n1)+chr(n2)+chr(n3))
994,517
Select desired delimeter Args: delim: The delimeter character you want. Returns: None Raises: RuntimeError: Delimeter too long.
def select_delim(self, delim): size = len(delim) if size > 20: raise RuntimeError('Delimeter too long') n1 = size/10 n2 = size%10 self.send('^SS'+chr(n1)+chr(n2))
994,518
Insert text into selected object. Args: data: The data you want to insert. Returns: None Raises: None
def insert_into_obj(self, data): if not data: data = '' size = len(data) n1 = size%256 n2 = size/256 self.send('^DI'+chr(n1)+chr(n2)+data)
994,519
Combines selection and data insertion into one function Args: name: the name of the object you want to insert into data: the data you want to insert Returns: None Raises: None
def select_and_insert(self, name, data): self.select_obj(name) self.insert_into_obj(data)
994,520
Initialization of the API module. Args: wrapper (Wrapper): Object that performs the requests to endpoints.
def __init__(self, wrapper): self._wrapper = wrapper self.make_request = self._wrapper.request_parking
994,883
Obtain detailed info of a given POI. Args: family (str): Family code of the POI (3 chars). lang (str): Language code (*es* or *en*). id (int): Optional, ID of the POI to query. Passing value -1 will result in information from all POIs. Returns: ...
def detail_poi(self, **kwargs): # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'family': kwargs.get('family') } if kwargs.get('id'): params['id'] = kwargs['id'] # Request result = self.ma...
994,885
Obtain a list of elements that have an associated icon. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[IconDescription]), or message string in case of error.
def icon_description(self, **kwargs): # Endpoint parameters params = {'language': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('icon_description', {}, **params) if not util.check_result(result): return False, result.get('mess...
994,886
Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error.
def list_features(self, **kwargs): # Endpoint parameters params = { 'language': util.language_code(kwargs.get('lang')), 'publicData': True } # Request result = self.make_request('list_features', {}, **params) if not util.check_result(res...
994,888
Obtain a list of parkings. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Parking]), or message string in case of error.
def list_parking(self, **kwargs): # Endpoint parameters url_args = {'lang': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('list_parking', url_args) if not util.check_result(result): return False, result.get('message', 'UNKNOWN...
994,889
Obtain a list of addresses and POIs. This endpoint uses an address to perform the search Args: lang (str): Language code (*es* or *en*). address (str): Address in which to perform the search. Returns: Status boolean and parsed response (list[ParkingPoi]), o...
def list_street_poi_parking(self, **kwargs): # Endpoint parameters url_args = { 'language': util.language_code(kwargs.get('lang')), 'address': kwargs.get('address', '') } # Request result = self.make_request('list_street_poi_parking', url_args) ...
994,890
Obtain a list of families, types and categories of POI. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[ParkingPoiType]), or message string in case of error.
def list_types_poi(self, **kwargs): # Endpoint parameters url_args = {'language': util.language_code(kwargs.get('lang'))} # Request result = self.make_request('list_poi_types', url_args) if not util.check_result(result): return False, result.get('message', ...
994,891
Initialization of the API module. Args: wrapper (Wrapper): Object that performs the requests to endpoints.
def __init__(self, wrapper): self._wrapper = wrapper self.make_request = self._wrapper.request_openbus
995,132
Obtain bus arrival info in target stop. Args: stop_number (int): Stop number to query. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Arrival]), or message string in case of error.
def get_arrive_stop(self, **kwargs): # Endpoint parameters params = { 'idStop': kwargs.get('stop_number'), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_arrive_stop', **params) #...
995,133
Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error.
def get_groups(self, **kwargs): # Endpoint parameters params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_groups', **params) if not util.check_result(result): return False, ...
995,134
Obtain a list of POI in the given radius. Args: latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. types (list[int] | int): POI IDs (or empty list to get all). radius (int): Radius (in meters) of the search. ...
def get_poi(self, **kwargs): # Endpoint parameters params = { 'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'tipos': util.ints_to_string(kwargs.get('types')), 'Radius': kwargs.get('radius'), 'cultureInf...
995,136
Obtain POI types. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[PoiType]), or message string in case of error.
def get_poi_types(self, **kwargs): # Endpoint parameters params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_poi_types', **params) # Parse values = result.get('types', []) ...
995,137
Obtain information on the stops of the given lines. Arguments: lines (list[int] | int): Lines to query, may be empty to get all the lines. direction (str): Optional, either *forward* or *backward*. lang (str): Language code (*es* or *en*). Returns: ...
def get_stops_line(self, **kwargs): # Endpoint parameters params = { 'line': util.ints_to_string(kwargs.get('lines', [])), 'direction': util.direction_code(kwargs.get('direction', '')), 'cultureInfo': util.language_code(kwargs.get('lang')) } ...
995,139
Obtain a list of streets around the specified point. Args: latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. radius (int): Radius (in meters) of the search. lang (str): Language code (*es* or *en*). Returns...
def get_street_from_xy(self, **kwargs): # Endpoint parameters params = { 'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'Radius': kwargs.get('radius'), 'cultureInfo': util.language_code(kwargs.get('lang')) }...
995,141
Obtain stop IDs, coordinates and line information. Args: nodes (list[int] | int): nodes to query, may be empty to get all nodes. Returns: Status boolean and parsed response (list[NodeLinesItem]), or message string in case of error.
def get_nodes_lines(self, **kwargs): # Endpoint parameters params = {'Nodes': util.ints_to_string(kwargs.get('nodes', []))} # Request result = self.make_request('bus', 'get_nodes_lines', **params) if not util.check_result(result): return False, result.get('...
995,290
Initialize the interface attributes. Initialization may also be performed at a later point by manually calling the ``initialize()`` method. Args: emt_id (str): ID given by the server upon registration emt_pass (str): Token given by the server upon registration
def __init__(self, emt_id='', emt_pass=''): if emt_id and emt_pass: self.initialize(emt_id, emt_pass)
995,796
Manual initialization of the interface attributes. This is useful when the interface must be declare but initialized later on with parsed configuration values. Args: emt_id (str): ID given by the server upon registration emt_pass (str): Token given by the server upon re...
def initialize(self, emt_id, emt_pass): self._emt_id = emt_id self._emt_pass = emt_pass # Initialize modules self.bus = BusApi(self) self.geo = GeoApi(self) self.parking = ParkingApi(self)
995,797
Answer will provide all necessary feedback for the caller Args: c (int): HTTP Code details (dict): Response payload Returns: dict: Response payload Raises: ErrAtlasBadRequest ErrAtlasUnauthorized ...
def answer(self, c, details): if c in [Settings.SUCCESS, Settings.CREATED, Settings.ACCEPTED]: return details elif c == Settings.BAD_REQUEST: raise ErrAtlasBadRequest(c, details) elif c == Settings.UNAUTHORIZED: raise ErrAtlasUnauthorized(c, details) ...
997,183
Get request Args: uri (str): URI Returns: Json: API response Raises: Exception: Network issue
def get(self, uri): r = None try: r = requests.get(uri, allow_redirects=True, timeout=Settings.requests_timeout, headers={}, auth=HTTPDigestAuth(self.user, se...
997,184
Add multiple roles Args: databaseName (str): Database Name roleNames (list of RoleSpecs): roles Keyword Args: collectionName (str): Collection Raises: ErrRoleException: role not compatible with the databaseName and/or...
def add_roles(self, databaseName, roleNames, collectionName=None): for roleName in roleNames: self.add_role(databaseName, roleName, collectionName)
997,302
Add one role Args: databaseName (str): Database Name roleName (RoleSpecs): role Keyword Args: collectionName (str): Collection Raises: ErrRole: role not compatible with the databaseName and/or collectionName
def add_role(self, databaseName, roleName, collectionName=None): role = {"databaseName" : databaseName, "roleName" : roleName} if collectionName: role["collectionName"] = collectionName # Check atlas constraints if collectionName and...
997,303
Remove multiple roles Args: databaseName (str): Database Name roleNames (list of RoleSpecs): roles Keyword Args: collectionName (str): Collection
def remove_roles(self, databaseName, roleNames, collectionName=None): for roleName in roleNames: self.remove_role(databaseName, roleName, collectionName)
997,304
Remove one role Args: databaseName (str): Database Name roleName (RoleSpecs): role Keyword Args: collectionName (str): Collection
def remove_role(self, databaseName, roleName, collectionName=None): role = {"databaseName" : databaseName, "roleName" : roleName} if collectionName: role["collectionName"] = collectionName if role in self.roles: self.roles.remove...
997,305
Formatting JSON API Error Object Constructing an error object based on JSON API standard ref: http://jsonapi.org/format/#error-objects Args: status: Can be a http status codes title: A summary of error detail: A descriptive error message code: Application error codes (if any)...
def format_error(status=None, title=None, detail=None, code=None): error = {} error.update({ 'title': title }) if status is not None: error.update({ 'status': status }) if detail is not None: error.update({ 'detail': detail }) if code is not None: error.update({ 'code...
997,392
List of errors Put all errors into a list of errors ref: http://jsonapi.org/format/#errors Args: *args: A tuple contain errors Returns: A dictionary contains a list of errors
def return_an_error(*args): list_errors = [] list_errors.extend(list(args)) errors = { 'errors': list_errors } return errors
997,393
Intermediate fetching Args: pageNum (int): Page number itemsPerPage (int): Number of Users per Page Returns: dict: Response payload
def fetch(self, pageNum, itemsPerPage): return self.get_all_alerts(self.status, pageNum, itemsPerPage)
997,476
Check ISBN is a string, and passes basic sanity checks. Args: isbn (str): SBN, ISBN-10 or ISBN-13 checksum (bool): ``True`` if ``isbn`` includes checksum character Returns: ``str``: ISBN with hyphenation removed, including when called with a SBN Raises: TypeErr...
def _isbn_cleanse(isbn, checksum=True): if not isinstance(isbn, string_types): raise TypeError('ISBN must be a string, received %r' % isbn) if PY2 and isinstance(isbn, str): # pragma: Python 2 isbn = unicode(isbn) uni_input = False else: # pragma: Python 3 uni_input =...
997,667