code
stringlengths
1
18.2k
def p_try_statement_3(self, p): """try_statement : TRY block catch finally""" p[0] = ast.Try(statements=p[2], catch=p[3], fin=p[4])
def p_catch(self, p): """catch : CATCH LPAREN identifier RPAREN block""" p[0] = ast.Catch(identifier=p[3], elements=p[5])
def p_function_declaration(self, p): """ function_declaration \ : FUNCTION identifier LPAREN RPAREN LBRACE function_body RBRACE | FUNCTION identifier LPAREN formal_parameter_list RPAREN LBRACE \ function_body RBRACE """ if len(p) == 8: p[0] = ast.FuncDecl( identifier=p[2], parameters=None, elements=p[6]) else: p[0] = a...
def p_function_expr_1(self, p): """ function_expr \ : FUNCTION LPAREN RPAREN LBRACE function_body RBRACE | FUNCTION LPAREN formal_parameter_list RPAREN \ LBRACE function_body RBRACE """ if len(p) == 7: p[0] = ast.FuncExpr( identifier=None, parameters=None, elements=p[5]) else: p[0] = ast.FuncExpr( identifier=None, para...
def raise_null_argument(func): """decorator, to intercept num argument TypeError and raise as NullArgument""" def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except TypeError as ex: if any(statement in ex.args[0] for statement in ['takes exactly', 'required positional argument']): raise NullArgument('Wr...
def list_provincie_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Provincie` to json. """ return { 'niscode': obj.niscode, 'naam': obj.naam, 'gewest': { 'id': obj.gewest.id, 'naam': obj.gewest.naam } }
def list_straten_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Straat` to json. """ return { 'id': obj.id, 'label': obj.label, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie }, }
def list_huisnummers_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Huisnummer` to json. """ return { 'id': obj.id, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie }, 'label': obj.huisnummer }
def list_gebouwen_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Gebouw` to json. """ return { 'id': obj.id, 'aard': { 'id': obj.aard.id, 'naam': obj.aard.naam, 'definitie': obj.aard.definitie }, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.de...
def list_subadres_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Subadres` to json. """ return { 'id': obj.id, 'subadres': obj.subadres, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie } }
def list_adresposities_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Adrespositie` to json. """ return { 'id': obj.id, 'herkomst': { 'id': obj.herkomst.id, 'naam': obj.herkomst.naam, 'definitie': obj.herkomst.definitie } }
def item_gewest_adapter(obj, request): """ Adapter for rendering an object of :class:`crabpy.gateway.crab.Gewest` to json. """ return { 'id': obj.id, 'namen': obj._namen, 'centroid': obj.centroid, 'bounding_box': obj.bounding_box }
def item_provincie_adapter(obj, request): """ Adapter for rendering a object of :class:`crabpy.gateway.crab.Provincie` to json. """ return { 'niscode': obj.niscode, 'naam': obj.naam, 'gewest': { 'id': obj.gewest.id, 'naam': obj.gewest.naam } }
def item_gemeente_adapter(obj, request): """ Adapter for rendering an object of :class:`crabpy.gateway.crab.Gemeente` to json. """ return { 'id': obj.id, 'niscode': obj.niscode, 'naam': obj.naam, 'centroid': obj.centroid, 'bounding_box': obj.bounding_box, 'metadata': { 'begin_tijd': obj.metadata.begin_tijd, 'begin_datu...
def item_deelgemeente_adapter(obj, request): """ Adapter for rendering a object of :class:`crabpy.gateway.crab.Deelgemeente` to json. """ return { 'id': obj.id, 'naam': obj.naam, 'gemeente': { 'id': obj.gemeente.id, 'naam': obj.gemeente.naam } }
def item_straat_adapter(obj, request): """ Adapter for rendering an object of :class:`crabpy.gateway.crab.Straat` to json. """ return { 'id': obj.id, 'label': obj.label, 'namen': obj.namen, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie }, 'taal': { 'id': obj.taal.id, 'naam'...
def item_huisnummer_adapter(obj, request): """ Adapter for rendering an object of :class:`crabpy.gateway.crab.Huisnummer` to json. """ return { 'id': obj.id, 'huisnummer': obj.huisnummer, 'postadres': obj.postadres, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie }, 'metadata...
def item_perceel_crab_adapter(obj, request): """ Adapter for rendering an object of :class:`crabpy.gateway.crab.Perceel` to json. """ return { 'id': obj.id, 'centroid': obj.centroid, 'postadressen': obj.postadressen, 'metadata': { 'begin_tijd': obj.metadata.begin_tijd, 'begin_datum': obj.metadata.begin_datum, 'begin_be...
def item_gebouw_adapter(obj, request): """ Adapter for rendering an object of :class:`crabpy.gateway.crab.Gebouw` to json. """ return { 'id': obj.id, 'aard': { 'id': obj.aard.id, 'naam': obj.aard.naam, 'definitie': obj.aard.definitie }, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.d...
def item_wegobject_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.Wegobject` to json. """ return { 'id': obj.id, 'aard': { 'id': obj.aard.id, 'naam': obj.aard.naam, 'definitie': obj.aard.definitie }, 'centroid': obj.centroid, 'bounding_box': obj.bounding_box, 'metadata': { 'begin_tijd...
def item_subadres_adapter(obj, request): """ Adapter for rendering an item of :class:`crabpy.gateway.Subadres` to json. """ return { 'id': obj.id, 'subadres': obj.subadres, 'postadres': obj.postadres, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie }, 'aard': { 'id': obj.aard...
def item_adrespositie_adapter(obj, request): """ Adapter for rendering an item of :class:`crabpy.gateway.Adrespositie` to json. """ return { 'id': obj.id, 'herkomst': { 'id': obj.herkomst.id, 'naam': obj.herkomst.naam, 'definitie': obj.herkomst.definitie }, 'geometrie': obj.geometrie, 'aard': { 'id': obj.aard.id, 'naam...
def item_land_adapter(obj, request): """ Adapter for rendering an item of :class: `pycountry.db.Data` to json. """ return { 'id': obj.alpha_2, 'alpha2': obj.alpha_2, 'alpha3': obj.alpha_3, 'naam': _(obj.name) }
def run_dot(dot): """Converts a graph in DOT format into an IPython displayable object.""" global impl if impl is None: impl = guess_impl() if impl == "dot": return run_dot_dot(dot) elif impl == "js": return run_dot_js(dot) else: raise ValueError("unknown implementation {}".format(impl))
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() if name in CELESTIAL_COORDINATE_TYPES: domain = 'Celestial Coordinate Systems' coordinate_name = CELESTIAL_COORDINATE_TYPES[name] elif name in GEOGRAPHIC_COORDINATE_TYP...
def _get_agent_key(self, proxy=None): """Gets an agent key for session management. Side effect of setting a new proxy if one is sent along, and initializing the provider session map if agent key has not been seen before """ if self._proxy is None: self._proxy = proxy if self._proxy is not None and self._proxy.has_effec...
def _get_provider_sessions(self): """Gets list of all known provider sessions.""" agent_key = self._get_agent_key() sessions = [] for session_name in self._provider_sessions[agent_key]: sessions.append(self._provider_sessions[agent_key][session_name]) return sessions
def extra_create_kwargs(self): """ Inject the domain of the current user in the new model instances. """ user = self.get_agnocomplete_context() if user: _, domain = user.email.split('@') return { 'domain': domain } return {}
def get_pseudo_salt(length, *args): """ generate a pseudo salt (used, if user is wrong) """ temp = "".join([arg for arg in args]) return hash_hexdigest(temp)[:length]
def hexlify_pbkdf2(password, salt, iterations, length, digest=hashlib.sha1): """ >>> hash = hexlify_pbkdf2("not secret", "a salt value", iterations=100, length=16) >>> hash == '0b919231515dde16f76364666cf07107' True """ # log.debug("hexlify_pbkdf2 with iterations=%i", iterations) hash = crypto.pbkdf2(password, salt, it...
def salt_hash_from_plaintext(password): """ Create a XOR encrypted PBKDF2 salted checksum from a plaintext password. >>> seed_generator.DEBUG=True # Generate always the same seed for tests >>> salt, data = salt_hash_from_plaintext("test") >>> salt == 'DEBUG' True >>> data =='pbkdf2_sha1$5$DEBUG$a2220ab7dea891f260edd481...
def _simulate_client(plaintext_password, init_pbkdf2_salt, cnonce, server_challenge): """ A implementation of the JavaScript client part. Needful for finding bugs. """ # log.debug("_simulate_client(plaintext_password='%s', init_pbkdf2_salt='%s', cnonce='%s', server_challenge='%s')", # plaintext_password, init_pbkdf2_sa...
def check_secure_js_login(secure_password, encrypted_part, server_challenge): """ first_pbkdf2_part = xor_decrypt(encrypted_part, key=second_pbkdf2_part) test_hash = pbkdf2(first_pbkdf2_part, key=cnonce + server_challenge) compare test_hash with transmitted pbkdf2_hash """ # log.debug("check_secure_js_login(secure_pass...
def xor(self, txt, key): """ >>> crypted = XorCryptor().xor(b"1234", b"ABCD") >>> crypted == b'pppp' True >>> txt = XorCryptor().xor(b'pppp', b"ABCD") >>> txt == b'1234' True """ assert isinstance(txt, six.binary_type), "txt: %s is not binary type!" % repr(txt) assert isinstance(key, six.binary_type), "key: %s is not b...
def encrypt(self, txt, key): """ XOR ciphering with a PBKDF2 checksum """ # log.debug("encrypt(txt='%s', key='%s')", txt, key) assert isinstance(txt, six.text_type), "txt: %s is not text type!" % repr(txt) assert isinstance(key, six.text_type), "key: %s is not text type!" % repr(key) if len(txt) != len(key): raise Secu...
def decrypt(self, txt, key): """ 1. Decrypt a XOR crypted String. 2. Compare the inserted SHA salt-hash checksum. """ # log.debug("decrypt(txt='%s', key='%s')", txt, key) assert isinstance(txt, six.text_type), "txt: %s is not text type!" % repr(txt) assert isinstance(key, six.text_type), "key: %s is not text type!" % r...
decrypted = self.xor(crypted, key) try: decrypted = force_text(decrypted) except UnicodeDecodeError: raise SecureJSLoginError("Can't decode data.") test = PBKDF2SHA1Hasher1().verify(decrypted, pbkdf2_hash) if not test: raise SecureJSLoginError("XOR decrypted data: PBKDF2 hash test failed") return decrypted
def forecast(place, series=True): """NOAA weather forecast for a location""" lat, lon = place url = "http://graphical.weather.gov/xml/SOAP_server/ndfdXMLclient.php?" + \ "whichClient=NDFDgen&" + "lat=%s&lon=%s&" % (lat, lon) + \ "Unit=e&temp=temp&wspd=wspd&sky=sky&wx=wx&rh=rh&" + \ "product=time-series&Submit=Submit" l...
def _cast_float(temp_dt): """returns utc timestamp""" if type(temp_dt) == str: fmt = '%Y-%m-%dT%H:%M:00' base_dt = temp_dt[0:19] tz_offset = eval(temp_dt[19:22]) temp_dt = datetime.datetime.strptime(base_dt, fmt) - \ datetime.timedelta(hours=tz_offset) return (temp_dt - datetime.datetime(1970, 1, 1)).total_seconds()
def herp_derp_interp(place): """simple interpolation of GFS forecast""" lat, lon = place #begin=2014-02-14T00%3A00%3A00&end=2018-02-22T00%3A00%3A00 fmt = '%Y-%m-%dT00:00:00' fmt = '%Y-%m-%dT%H:%M:00' begin = (datetime.datetime.now()-datetime.timedelta(hours=12)).strftime(fmt) #end=(datetime.datetime.now()+datetime.time...
cc_interp(_cast_float(forecast_dt)).item() series.append(temp_dict) except: pass return series
def get_agent_lookup_session(self): """Gets the ``OsidSession`` associated with the agent lookup service. return: (osid.authentication.AgentLookupSession) - an ``AgentLookupSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_agent_lookup()`` is ``false`` *compliance: optional...
def get_agent_lookup_session_for_agency(self, agency_id): """Gets the ``OsidSession`` associated with the agent lookup service for the given agency. arg: agency_id (osid.id.Id): the ``Id`` of the agency return: (osid.authentication.AgentLookupSession) - ``an _agent_lookup_session`` raise: NotFound - ``agency_id`` not f...
def get_type_data(name): """Return dictionary representation of type. Can be used to initialize primordium.type.primitives.Type """ name = name.upper() if name in CALENDAR_TYPES: domain = 'Calendar Types' calendar_name = CALENDAR_TYPES[name] elif name in ANCIENT_CALENDAR_TYPES: domain = 'Ancient Calendar Types' calenda...
def write_index(path,index_file,verbose=False,samtools=False): """ Index file is a gzipped TSV file with these fields: 1. qname 2. target range 3. bgzf file block start 4. bgzf inner block start 5. aligned base count 6. flag :param path: bamfile :param index_file: bam index to write :param verbose: default False :param...
e.value('qname') if name not in reads: reads[name] = {} type = 'u' if e.check_flag(64): type = 'l' #left mate elif e.check_flag(128): type = 'r' #right mate if not e.check_flag(2304): if type not in reads[name]: reads[name][type] = 0 reads[name][type] += 1 # we have one if reads[name][type] > 1: fail_primary = True bre...
b2 = BAMFile(path) z = 0 for e in b2: z += 1 if verbose: if z %1000==0: sys.stderr.write(str(z)+"\r") name = e.value('qname') type = 'u' if e.check_flag(64): type = 'l' #left mate elif e.check_flag(128): type = 'r' #right mate if name not in best: best[name] = {} # get length l = 0 if e.is_aligned(): l = e.get_aligned_...
if verbose: if z%1000==0: sys.stderr.write(str(z)+" reads indexed\r") myflag = e.value('flag') if fail_primary: # see if this should be a primary if z not in bestlinenumbers: myflag = myflag | 2304 rng = e.get_target_range() if rng: l = e.get_aligned_bases_count() of.write(e.value('qname')+"\t"+rng.get_range_string()+"...
def check_ordered(self): """ True if each chromosome is listed together as a chunk and if the range starts go from smallest to largest otherwise false :return: is it ordered? :rtype: bool """ sys.stderr.write("error unimplemented check_ordered\n") sys.exit() seen_chrs = set() curr_chr = None prevstart = 0 for l in self...
def get_coords_by_name(self,name): """ .. warning:: not implemented """ sys.stderr.write("error unimplemented get_coords_by_name\n") sys.exit() return [[self._lines[x]['filestart'],self._lines[x]['innerstart']] for x in self._queries[self._name_to_num[name]]]
def get_longest_target_alignment_coords_by_name(self,name): """For a name get the best alignment :return: [filebyte,innerbyte] describing the to distance the zipped block start, and the distance within the unzipped block :rtype: list """ longest = -1 coord = None #for x in self._queries[self._name_to_num[name]]: for li...
def get_index_line(self,lnum): """ Take the 1-indexed line number and return its index information""" if lnum < 1: sys.stderr.write("ERROR: line number should be greater than zero\n") sys.exit() elif lnum > len(self._lines): sys.stderr.write("ERROR: too far this line nuber is not in index\n") sys.exit() return self._li...
def get_coord_line_number(self,coord): """return the one-indexed line number given the coordinates""" if coord[0] in self._coords: if coord[1] in self._coords[coord[0]]: return self._coords[coord[0]][coord[1]] return None
def get_unaligned_lines(self): """get the lines that are not aligned""" sys.stderr.write("error unimplemented get_unaligned_lines\n") sys.exit() return [self._lines[x-1] for x in self._unaligned]
def get_unaligned_start_coord(self): """ .. warning:: not implemented """ sys.stderr.write("error unimplemented get_unaligned_start_coord\n") sys.exit() if len(self._unaligned)==0: return None return [self._lines[self._unaligned[0]-1]['filestart'],self._lines[self._unaligned[0]-1]['innerstart']]
def get_range_start_coord(self,rng): """ .. warning:: not implemented """ sys.stderr.write("error unimplemented get_range_start_coord\n") sys.exit() if rng.chr not in self._chrs: return None for l in [self._lines[x-1] for x in self._chrs[rng.chr]]: #### y = l['rng'] c = y.cmp(rng) if c > 0: return None if c == 0: x = y...
def get_range_start_line_number(self,rng): """ .. warning:: not implemented """ sys.stderr.write("error unimplemented get_range_start_line\n") sys.exit() for i in range(0,len(self._lines)): if rng.cmp(self._lines[i]['rng'])==0: return i+1 return None
def _bin_to_extra(extra_bytes): """Pre all the reamining bytes of an entry Post an array of 1. A dict keyed by Tag with {'type':,'value':} where value is a string unless type is i 2. A string of the remainder """ #global _bam_value_type extra = StringIO(extra_bytes) tags = {} rem = '' while extra.tell() < len(extra_byt...
rem += tag+':' rem += 'i'+':' val = struct.unpack(_bam_value_type[val_type][1],extra.read(_bam_value_type[val_type][0]))[0] rem += str(val)+"\t" tags[tag] = TagDatum(val_type, val) #tags[tag] = {'type':val_type,'value':val} elif val_type == 'B': sys.sterr.write("WARNING array not implmented\n") continue rem += tag+':' ...
def lie_between(self, target_time_range): """ 判断是否落在目标时间区间内 :param target_time_range: 目标时间区间 :return: True or False """ if self.begin_dt >= target_time_range.begin_dt and self.end_dt <= \ target_time_range.end_dt: return True else: return False
def do_intersect(self, another_time_range): """ 判断与另一时间区间是否有重叠 :param another_time_range: :return: True or False """ if self.begin_dt > another_time_range.end_dt or self.end_dt < \ another_time_range.begin_dt: return False else: return True
def enqueue(self, item, queue=None): """ Enqueue items. If you define "self.filter" (sequence), this method put the item to queue after filtering. "self.filter" operates as blacklist. This method expects that "item" argument has dict type "data" attribute. """ if queue is None: queue = self.queue is_enqueue_item = True...
def _generate(self): u"""overrided in each modules.""" self._data['key'] = self.key self._data['value'] = self.value self._data['host'] = self.host self._data['clock'] = self.clock
def __set_timestamp(self, clock): """ If "clock" is None, set the time now. This function is called self.__init__() """ if clock is None: unix_timestamp = time.mktime( datetime.datetime.now().utctimetuple() ) timestamp = int(unix_timestamp) return timestamp else: return clock
def compose(first_func, second_func): """ Compose two functions. Documentation is retrieved from the first one. Parameters ---------- first_func The first, main, function. second_func The second, (less important) function. Returns function A new function. ------- """ @wraps(first_func) def composed_func(*args, **kwargs...
def escape_string(text): """Remove problematic characters. Parameters ---------- text A string with potentially problematic characters. Returns ------- string The text with characters removed. Examples ------- >>> s = r'hello_world$here' >>> escape_string(s) == r'helloworldhere' True """ if text is None: return text TO...
def chunker(iterable, size=5, fill=''): """Chunk the iterable. Parameters ---------- iterable A list. size The size of the chunks. fill Fill value if the chunk is not of length 'size'. Yields ------- chunk A chunk of length 'size'. Examples ------- >>> l = list(range(6)) >>> chunks = list(chunker(l, size=4, fill='')) >...
def round_to_nearest(number, nearest=1): """Round 'number' to the nearest multiple of 'nearest'. Parameters ---------- number A real number to round. nearest Number to round to closes multiple of. Returns ------- rounded A rounded number. Examples ------- >>> round_to_nearest(6.8, nearest = 2.5) 7.5 """ result = neares...
def all_equal(iterable): """Checks whether all items in an iterable are equal. Parameters ---------- iterable An iterable, e.g. a string og a list. Returns ------- boolean True or False. Examples ------- >>> all_equal([2, 2, 2]) True >>> all_equal([1, 2, 3]) False """ if len(iterable) in [0, 1]: return False first = it...
def min_between(min_reps=3, max_reps=8, percentile=0.33): """Function to decide the minimum number of reps to perform given `min_reps` and `max_rep`. Parameters ---------- min_reps The minimum number of repeitions. max_reps The maximum number of repetitions. percentile The percentile to cap at. Return ------- (low, hig...
def generate_reps(min_reps=3, max_reps=8, total=25, existing=None): """Generate 'total' repetitions between 'min_reps' and 'max_reps', if existing is given (not None), then some repetitions are already drawn. Parameters ---------- min_reps Lower limit for the repetitions dawing, e.g. 3. max_reps Upper limit for the rep...
generated = random.randint(min_reps, max_reps) created.append(generated) # Sort and append to the list of lists created.sort(reverse=True) possible.append(created) # Return the list of reps which is closest to the total desired number return min(possible, key=lambda l: abs(total - sum(l)))
def spread(iterable): """Returns the maximal spread of a sorted list of numbers. Parameters ---------- iterable A list of numbers. Returns ------- max_diff The maximal difference when the iterable is sorted. Examples ------- >>> spread([1, 11, 13, 15]) 10 >>> spread([1, 15, 11, 13]) 10 """ if len(iterable) == 1: return...
def create_image_base64(): """ 创建一个验证码 + 图片base64字符串流 """ code, file = create_image() b64str = "data:image/png;base64," with open(file, "rb") as f: if sys.version_info.major == 2: b64str += base64.b64encode(f.read()) else: b64str += base64.b64encode(f.read()).decode() os.remove(file) return True, {"code": code, "base64...
def secure(self, value): """Set the secure parameter and regenerate the thumbnail link.""" self._secure = value self._thumb = self._link_to_img()
def rating(self, value): """Set the rating parameter and regenerate the thumbnail link.""" self._rating = value self._thumb = self._link_to_img()
def size(self, value): """Set the size parameter and regenerate the thumbnail link.""" self._size = value self._thumb = self._link_to_img()
def default(self, value): """Set the default parameter and regenerate the thumbnail link.""" self._default = value self._thumb = self._link_to_img()
def _link_to_img(self): """ Generates a link to the user's Gravatar. >>> Gravatar('gridaphobe@gmail.com')._link_to_img() 'http://www.gravatar.com/avatar/16b87da510d278999c892cdbdd55c1b6?s=80&r=g' """ # make sure options are valid if self.rating.lower() not in RATINGS: raise InvalidRatingError(self.rating) if not (MIN_S...
def _get_profile(self): """ Retrieves the profile data of the user and formats it as a Python dictionary. """ url = PROFILE_URL + self.hash + '.json' try: profile = json.load(urlopen(url)) # set the profile as an instance variable self._profile = profile['entry'][0] except: self._profile = {}
def parse_url(url): """Return a clean URL. Remove the prefix for the Auth URL if Found. :param url: :return aurl: """ if url.startswith(('http', 'https', '//')): if url.startswith('//'): return urlparse.urlparse(url, scheme='http') else: return urlparse.urlparse(url) else: return urlparse.urlparse(urlparse.urljoin('htt...
def html_encode(path): """Return an HTML encoded Path. :param path: ``str`` :return: ``str`` """ if sys.version_info > (3, 2, 0): return urllib.parse.quote(utils.ensure_string(path)) else: return urllib.quote(utils.ensure_string(path))
def _get_url(url): """Returns a URL string. If the ``url`` parameter is a ParsedResult from `urlparse` the full url will be unparsed and made into a string. Otherwise the ``url`` parameter is returned as is. :param url: ``str`` || ``object`` """ if isinstance(url, urlparse.ParseResult): return urlparse.urlunparse(url) ...
def _report_error(self, request, exp): """When making the request, if an error happens, log it.""" message = ( "Failure to perform %s due to [ %s ]" % (request, exp) ) self.log.fatal(message) raise requests.RequestException(message)
def _request(self, method, url, headers=None, body=None, kwargs=None): """Make a request. To make a request pass the ``method`` and the ``url``. Valid methods are, ``['post', 'put', 'get', 'delete', 'patch', 'option', 'head']``. :param url: ``str`` :param headers: ``dict`` :param body: ``object`` :param kwargs: ``dict`...
def post(self, url, headers=None, body=None, kwargs=None): """Make a POST request. To make a POST request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param body: ``object`` :param kwargs: ``dict`` """ return self._request( method='post', url=url, headers=headers, body=body, kwargs=kwargs )
def head(self, url, headers=None, kwargs=None): """Make a HEAD request. To make a HEAD request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param kwargs: ``dict`` """ return self._request( method='head', url=url, headers=headers, kwargs=kwargs )
def patch(self, url, headers=None, body=None, kwargs=None): """Make a PATCH request. To make a PATCH request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param body: ``object`` :param kwargs: ``dict`` """ return self._request( method='patch', url=url, headers=headers, body=body, kwargs=kwargs )
def put(self, url, headers=None, body=None, kwargs=None): """Make a PUT request. To make a PUT request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param body: ``object`` :param kwargs: ``dict`` """ return self._request( method='put', url=url, headers=headers, body=body, kwargs=kwargs )
def delete(self, url, headers=None, kwargs=None): """Make a DELETE request. To make a DELETE request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param kwargs: ``dict`` """ return self._request( method='delete', url=url, headers=headers, kwargs=kwargs )
def get(self, url, headers=None, kwargs=None): """Make a GET request. To make a GET request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param kwargs: ``dict`` """ return self._request( method='get', url=url, headers=headers, kwargs=kwargs )
def option(self, url, headers=None, kwargs=None): """Make a OPTION request. To make a OPTION request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param kwargs: ``dict`` """ return self._request( method='option', url=url, headers=headers, kwargs=kwargs )
def __generate(self): """Generates dates patterns""" base = [] texted = [] for pat in ALL_PATTERNS: data = pat.copy() data['pattern'] = data['pattern'] data['right'] = True data['basekey'] = data['key'] base.append(data) data = pat.copy() data['basekey'] = data['key'] data['key'] += ':time_1' data['right'] = True data[...
+ 1, 'max' : data['length']['max'] + 90} texted.append(data) base.extend(texted) self.patterns = base
def match(self, text, noprefix=False): """Matches date/datetime string against date patterns and returns pattern and parsed date if matched. It's not indeded for common usage, since if successful it returns date as array of numbers and pattern that matched this date :param text: Any human readable string :type date_str...
or n > p['length']['max']: continue if p['right'] and len(basekeys) > 0 and p['basekey'] not in basekeys: continue try: r = p['pattern'].parseString(text) # Do sanity check d = r.asDict() if 'month' in d: val = int(d['month']) if val > 12 or val < 1: continue if 'day' in d: val = int(d['day']) if val > 31 or val < 1: c...
def parse(self, text, noprefix=False): """Parse date and time from given date string. :param text: Any human readable string :type date_string: str|unicode :param noprefix: If set True than doesn't use prefix based date patterns filtering settings :type noprefix: bool :return: Returns :class:`datetime <datetime.datetim...
def forwards(self, orm): "Perform a 'safe' load using Avocado's backup utilities." from avocado.core import backup backup.safe_load(u'0002_avocado_metadata', backup_path=None, using='default')
def get_next_id(self): """Gets the next Id in this list. return: (osid.id.Id) - the next Id in this list. The has_next() method should be used to test that a next Id is available before calling this method. raise: IllegalState - no more elements available in this list raise: OperationFailed - unable to complete request...
def get_catalogs_by_query(self, catalog_query): """Gets a list of ``Catalogs`` matching the given catalog query. arg: catalog_query (osid.cataloging.CatalogQuery): the catalog query return: (osid.cataloging.CatalogList) - the returned ``CatalogList`` raise: NullArgument - ``catalog_query`` is ``null`` raise: OperationF...