code stringlengths 1 18.2k |
|---|
def _get_tag(self, response, tag_name="html", encoding="utf-8"): """ Iterates response content and returns the tag if found. If not found, the response content is fully consumed so self._html equals response.content, and it returns None. """ def find_tag(tag_name): tag_start = tag_end = None found = lambda: \ tag_start... |
True: try: chunk = next(stream) self._html += chunk tag = find_tag(tag_name) if tag: return tag if len(self._html) > config.HTML_MAX_BYTESIZE: raise HTMLParseError('Maximum response size reached.') except StopIteration: response.consumed = True tag = find_tag(tag_name) return decode(tag, encoding) |
def extract(self, check_url=None, http_equiv_refresh=True): """ Downloads HTML <head> tag first, extracts data from it using specific head techniques, loads it and checks if is complete. Otherwise downloads the HTML <body> tag as well and loads data extracted by using appropriate semantic techniques. Eagerly calls chec... |
None: check_url(url=self.clean_url) encoding = config.ENCODING or response.encoding self._html = "" if config.PHANTOMJS_BIN and \ site(self.clean_url) in config.PHANTOMJS_SITES: self._html = request.phantomjs_get(self.clean_url) response.consumed = True head = self._get_tag(response, tag_name="head", encoding=encoding)... |
def piGenGosper(): """A generator function that yields the digits of Pi """ z = ((1,0,0,1),1) while True: lft = __lfts(z[1]) n = int(__next(z)) if __safe(z,n): z = __prod(z,n) yield n else: z = __cons(z,lft) |
def getPiGosper(n): """Returns a list containing first n digits of Pi """ mypi = piGenGosper() result = [] if n > 0: result += [next(mypi) for i in range(n)] mypi.close() return result |
def of_think(self, think): """ Simulate the worker processing the task for the specified amount of time. The worker is not released and the task is not paused. """ return self._compute( duration=think.duration, after=self.continuation) |
async def freeze(self, *args, **kwargs): """ Freeze users balance Accepts: - uid [integer] (users id from main server) - coinid [string] (blockchain type in uppercase) - amount [integer] (amount for freezing) Returns: - uid [integer] (users id from main server) - coinid [string] (blockchain type in uppercase) - amount_... |
fields exists if not uid and address: uid = await self.get_uid_by_address(address=address, coinid=coinid) if isinstance(uid, dict): return uid # Connect to appropriate database database = self.client[self.collection] collection = database[coinid] # Check if balance exists balance = await collection.find_one({"uid":uid}... |
async def get_active(self, *args, **kwargs): """ Get active users balance Accepts: - uid [integer] (users id) - types [list | string] (array with needed types or "all") Returns: { type [string] (blockchain type): amount } """ # Get daya from request coinids = kwargs.get("coinids") uid = kwargs.get("uid",0) address = kw... |
balance: return await self.error_404( "Get active. Balance with uid:%s and type:%s not found" % (uid, coinid)) # Collect actives actives[coinid] = int(balance["amount_active"]) if isinstance(coinids, str): actives = {} for coinid in self.coinids: database = self.client[coinid] collection = database[self.collection] # G... |
async def get_frozen(self, *args, **kwargs): """ Get frozen users balance Accepts: - uid [integer] (users id) - types [list | string] (array with needed types or "all") Returns: { type [string] (blockchain type): amount } """ super().validate(*args, **kwargs) if kwargs.get("message"): kwargs = json.loads(kwargs.get("me... |
balance balance = await collection.find_one({"uid":uid}) if not balance: return await self.error_404( "Get frozen. Balance with uid:%s and type:%s not found" % (uid, coinid)) # Collect actives actives[coinid] = int(balance["amount_frozen"]) if isinstance(coinids, str): actives = {} for coinid in self.types: database = ... |
async def collect_wallets(self, uid): """ Asynchronous generator """ logging.debug(self.types) logging.debug(uid) for coinid in self.types: logging.debug(coinid) await asyncio.sleep(0.5) # Connect to appropriate database database = self.client[self.collection] logging.debug(database) collection = database[coinid] loggi... |
async def get_wallets(self, *args, **kwargs): """ Get users wallets by uid Accepts: - uid [integer] (users id) Returns a list: - [ { "address": [string], "uid": [integer], "amount_active": [integer], "amount_frozen": [integer] }, ] """ logging.debug("\n [+] -- Get wallets debugging.") if kwargs.get("message"): kwargs =... |
async def confirmbalance(self, *args, **kwargs): """ Confirm balance after trading Accepts: - message (signed dictionary): - "txid" - str - "coinid" - str - "amount" - int Returns: - "address" - str - "coinid" - str - "amount" - int - "uid" - int - "unconfirmed" - int (0 by default) - "deposit" - int (0 by default) Ver... |
# Get offers price self.account.blockchain.setendpoint(settings.bridges[coinid]) offer = await self.account.blockchain.getoffer(cid=cid, buyer_address=buyer_address) # Get offers price for updating balance amount = int(offer["price"]) coinid = "PUT" # Get sellers account history_database = self.client[settings.HISTORY]... |
{"$unset":{"txid":1}}) if int(account["level"]) == 2: await self.account.updatelevel(**{"id":account["id"], "level":3}) return {i:updated[i] for i in updated if i != "_id" and i != "txid"} |
def _validate_config(self): """ Validate configuration file. :raises: RuntimeError """ # while set().issubset() is easier, we want to tell the user the names # of any invalid keys bad_keys = [] for k in self._config.keys(): if k not in self._example.keys(): bad_keys.append(k) if len(bad_keys) > 0: raise InvalidConfigEr... |
('logging_level' in self._config and self._config['logging_level'] not in levels): raise InvalidConfigError('logging_level must be one of %s' % levels) """ 'api_gateway_method_settings': { 'throttlingBurstLimit': None, 'throttlingRateLimit': None }, """ if 'api_gateway_method_settings' not in self._config: return ms = ... |
'omitted or a boolean') if ('throttlingBurstLimit' in ms and ms['throttlingBurstLimit'] is not None): try: assert ms['throttlingBurstLimit'] == int( ms['throttlingBurstLimit']) except (AssertionError, ValueError, TypeError): raise InvalidConfigError( 'api_gateway_method_settings throttlingBurstLimit key must ' 'be omit... |
def _load_config(self, path): """ Load configuration from JSON :param path: path to the JSON config file :type path: str :return: config dictionary :rtype: dict """ p = os.path.abspath(os.path.expanduser(path)) logger.debug('Loading configuration from: %s', p) return read_json_file(p) |
def __add_min_max_value( parser, basename, default_min, default_max, initial, help_template): """ Generates parser entries for options with a min, max, and default value. Args: parser: the parser to use. basename: the base option name. Generated options will have flags --basename-min, --basename-max, and --basename. de... |
def get_config_file(basename): """ Looks for a configuration file in 3 locations: - the current directory - the user config directory (~/.config/scriptabit) - the version installed with the package (using setuptools resource API) Args: basename (str): The base filename. Returns: str: The full path to the configuration ... |
def copy_default_config_to_user_directory( basename, clobber=False, dst_dir='~/.config/scriptabit'): """ Copies the default configuration file into the user config directory. Args: basename (str): The base filename. clobber (bool): If True, the default will be written even if a user config already exists. dst_dir (str)... |
def get_configuration(basename='scriptabit.cfg', parents=None): """Parses and returns the program configuration options, taken from a combination of ini-style config file, and command line arguments. Args: basename (str): The base filename. parents (list): A list of ArgumentParser objects whose arguments should also be... |
'--auth-section', required=False, default='habitica', help='''Name of the authentication file section containing the Habitica credentials''') parser.add( '-url', '--habitica-api-url', required=False, default='https://habitica.com/api/v3/', help='''The base Habitica API URL''') # plugins parser.add( '-r', '--run', requi... |
still exit before the limit is reached.''') parser.add( '-uf', '--update-frequency', required=False, type=int, default=-1, help='''If > 0, this specifies the preferred update frequency in minutes for plugins that run in the update loop. Note that plugins may ignore or limit this setting if the value is inappropriate fo... |
def authenticate(self, token): """ Authenticate a token :param token: """ if self.verify_token_callback: # Specified verify function overrides below return self.verify_token_callback(token) if not token: return False name = self.token_manager.verify(token) if not name: return False return True |
def parse_raw(s, lineno=0): """Parse a date from a raw string. The format must be exactly "seconds-since-epoch offset-utc". See the spec for details. """ timestamp_str, timezone_str = s.split(b' ', 1) timestamp = float(timestamp_str) try: timezone = parse_tz(timezone_str) except ValueError: raise errors.InvalidTimezone... |
def parse_tz(tz): """Parse a timezone specification in the [+|-]HHMM format. :return: the timezone offset in seconds. """ # from git_repository.py in bzr-git sign_byte = tz[0:1] # in python 3 b'+006'[0] would return an integer, # but b'+006'[0:1] return a new bytes string. if sign_byte not in (b'+', b'-'): raise ValueE... |
def p_definition_list(p): """ definition_list : definition definition_list | definition """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'") |
def p_define_service(p): """ define_service : SERVICE IDENTIFIER OPEN_CURLY_BRACKET settings operation_list CLOSE_CURLY_BRACKET | SERVICE IDENTIFIER OPEN_CURLY_BRACKET operation_list CLOSE_CURLY_BRACKET """ if len(p) == 7: body = p[4] + p[5] else: body = p[4] p[0] = DefineService(p[2], body) |
def p_setting_list(p): """ setting_list : setting setting_list | setting """ if len(p) == 3: p[0] = merge_map(p[1], p[2]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_setting_list'") |
def p_queue(p): """ queue : QUEUE COLON LIFO | QUEUE COLON FIFO """ if p[3] == "LIFO": p[0] = {"queue": LIFO()} elif p[3] == "FIFO": p[0] = {"queue": FIFO()} else: raise RuntimeError("Queue discipline '%s' is not supported!" % p[1]) |
def p_throttling(p): """ throttling : THROTTLING COLON NONE | THROTTLING COLON TAIL_DROP OPEN_BRACKET NUMBER CLOSE_BRACKET """ throttling = NoThrottlingSettings() if len(p) == 7: throttling = TailDropSettings(int(p[5])) p[0] = {"throttling": throttling} |
def p_autoscaling_setting_list(p): """ autoscaling_setting_list : autoscaling_setting autoscaling_setting_list | autoscaling_setting """ if len(p) == 3: p[0] = merge_map(p[1], p[2]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production in 'autoscaling_setting_list'") |
def p_autoscaling_setting(p): """ autoscaling_setting : PERIOD COLON NUMBER | LIMITS COLON OPEN_SQUARE_BRACKET NUMBER COMMA NUMBER CLOSE_SQUARE_BRACKET """ if len(p) == 8: p[0] = {"limits": (int(p[4]), int(p[6]))} elif len(p) == 4: p[0] = {"period": int(p[3])} else: raise RuntimeError("Invalid product in 'autoscaling_s... |
def p_operation_list(p): """ operation_list : define_operation operation_list | define_operation """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_operation_list'") |
def p_action_list(p): """ action_list : action action_list | action """ if len(p) == 3: p[0] = p[1] + p[2] elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production rules 'p_action_list'") |
def p_fail(p): """ fail : FAIL NUMBER | FAIL """ if len(p) > 2: p[0] = Fail(float(p[2])) else: p[0] = Fail() |
def p_query(p): """ query : QUERY IDENTIFIER SLASH IDENTIFIER | QUERY IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET query_option_list CLOSE_CURLY_BRACKET """ parameters = {"service": p[2], "operation": p[4]} if len(p) > 5: parameters = merge_map(parameters, p[6]) p[0] = Query(**parameters) |
def p_query_option_list(p): """ query_option_list : query_option COMMA query_option_list | query_option """ if len(p) == 2: p[0] = p[1] elif len(p) == 4: p[0] = merge_map(p[1], p[3]) else: raise RuntimeError("Invalid product rules for 'query_option_list'") |
def p_invoke(p): """ invoke : INVOKE IDENTIFIER SLASH IDENTIFIER | INVOKE IDENTIFIER SLASH IDENTIFIER OPEN_CURLY_BRACKET PRIORITY COLON NUMBER CLOSE_CURLY_BRACKET """ priority = None if len(p) > 5: priority = int(p[8]) p[0] = Trigger(p[2], p[4], priority) |
def p_retry(p): """ retry : RETRY OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET | RETRY OPEN_BRACKET retry_option_list CLOSE_BRACKET OPEN_CURLY_BRACKET action_list CLOSE_CURLY_BRACKET """ if len(p) == 5: p[0] = Retry(p[3]) elif len(p) == 8: p[0] = Retry(p[6], **p[3]) else: raise RuntimeError("Invalid product rules... |
def p_retry_option_list(p): """ retry_option_list : retry_option COMMA retry_option_list | retry_option """ if len(p) == 4: p[0] = merge_map(p[1], p[3]) elif len(p) == 2: p[0] = p[1] else: raise RuntimeError("Invalid production in 'retry_option_list'") |
def p_retry_option(p): """ retry_option : LIMIT COLON NUMBER | DELAY COLON IDENTIFIER OPEN_BRACKET NUMBER CLOSE_BRACKET """ if len(p) == 4: p[0] = {"limit": int(p[3]) } elif len(p) == 7: p[0] = {"delay": Delay(int(p[5]), p[3])} else: raise RuntimeError("Invalid production in 'retry_option'") |
def is_valid_address(self, *args, **kwargs): """ check address Accepts: - address [hex string] (withdrawal address in hex form) - coinid [string] (blockchain id (example: BTCTEST, LTCTEST)) Returns dictionary with following fields: - bool [Bool] """ client = HTTPClient(self.withdraw_server_address + self.withdraw_endpo... |
def register_token(self, *args, **kwargs): """ Register token Accepts: - token_name [string] - contract_address [hex string] - blockchain [string] token's blockchain (QTUMTEST, ETH) Returns dictionary with following fields: - success [Bool] """ client = HTTPClient(self.withdraw_server_address + self.withdraw_endpoint) ... |
def get_lines(self, config_access, visited_set): """ get the lines for this section visited_set is used to avoid visiting same section twice, if we've got a diamond in the @is setup """ if self in visited_set: return [] lines = self.lines.copy() visited_set.add(self) for identity in self.identities: if config_access.ge... |
def variable_iter(self, base): """ returns iterator over the cross product of the variables for this stanza """ base_substs = dict(('<' + t + '>', u) for (t, u) in base.items()) substs = [] vals = [] for with_defn in self.with_exprs: substs.append('<' + with_defn[0] + '>') vals.append(Host.expand_with(with_defn[1:])) f... |
def host_stanzas(self, config_access): """ returns a list of host definitions """ defn_lines = self.resolve_defn(config_access) for val_dict in self.variable_iter(config_access.get_variables()): subst = list(self.apply_substitutions(defn_lines, val_dict)) host = subst[0] lines = [ConfigOutput.to_line('Host', [host])] +... |
def parse(self, fd): """very simple parser - but why would we want it to be complex?""" def resolve_args(args): # FIXME break this out, it's in common with the templating stuff elsewhere root = self.sections[0] val_dict = dict(('<' + t + '>', u) for (t, u) in root.get_variables().items()) resolved_args = [] for arg in ... |
@args arg-name ...') if not self.is_include(): return if self._args is None or len(self._args) != len(parts): raise ParserException('required arguments not passed to include {url} ({parts})'.format( url=self._url, parts=', '.join(parts)) ) root = self.sections[0] for key, value in zip(parts, self._args): root.set_value... |
text = req.text elif parsed_url.scheme == 'file': with open(parsed_url.path) as fd: text = fd.read() elif parsed_url.scheme == '': path = os.path.expanduser(url) with open(path) as fd: text = fd.read() else: raise SecurityException('error: @includes may only use paths or https:// or file:// URLs') subconfig = SedgeEngi... |
handle_vardef(self.sections[0], keyword, parts): continue current_section = self.sections[-1] if handle_keyword(current_section, keyword, parts): continue if keyword.startswith('@'): raise ParserException("unknown expansion keyword {}".format(keyword)) # use other rather than parts to avoid messing up user # whitespace... |
def base(context, config, database, root, log_level): """Housekeeper - Access your files!""" coloredlogs.install(level=log_level) context.obj = ruamel.yaml.safe_load(config) if config else {} context.obj['database'] = database if database else context.obj['database'] context.obj['root'] = root if root else context.obj[... |
def showpath(path): """Return path in form most convenient for user to read. Return relative path when input path is within the current working directory, otherwise return same (absolute) path passed in. :param path: file system path :type path: str or unicode :returns: file system path :rtype: str """ try: retval = os... |
def lines(self): """List of file lines.""" if self._lines is None: with io.open(self.path, 'r', encoding='utf-8') as fh: self._lines = fh.read().split('\n') return self._lines |
def replace_baseline_repr(self, linenum, update): """Replace individual baseline representation. :param int linenum: location of baseline representation :param str update: new baseline representation text (with delimiters) """ # use property to access lines to read them from file if necessary lines = self.lines count =... |
= ( '{}:{}: could not find docstring'.format(self.path, linenum)) raise RuntimeError(docstr_not_found) new_content = match.group('prefix') + update + match.group('suffix') lines[linenum:] = new_content.split('\n') |
def update(self): """Replace baseline representations previously registered for update.""" for linenum in reversed(sorted(self.updates)): self.replace_baseline_repr(linenum, self.updates[linenum]) if not self.TEST_MODE: path = '{}.update{}'.format(*os.path.splitext(self.path)) with io.open(path, 'w', encoding='utf-8') ... |
def _sum(data): """_sum(data [, start]) -> value Return a high-precision sum of the given numeric data. If optional argument ``start`` is given, it is added to the total. If ``data`` is empty, ``start`` (defaulting to 0) is returned. Examples -------- >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75) 11.0 Some sources of round... |
_first(data) if n is not None: data = chain([n], data) if isinstance(n, F): return math.fsum(data) return sum(data) return 0 |
def mean(data): """Return the sample arithmetic mean of data. >>> mean([1, 2, 3, 4, 4]) 2.8 >>> from fractions import Fraction as F >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)]) Fraction(13, 21) >>> from decimal import Decimal as D >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")]) Decimal('0.5625') If ``data`` ... |
def median_grouped(data, interval=1): """"Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is continuous and grouped. In th... |
whether the data points are at least ``interval`` apart. """ data = sorted(data) n = len(data) if n == 0: raise StatisticsError("no median for empty data") elif n == 1: return data[0] # Find the value at the midpoint. Remember this corresponds to the # centre of the class interval. x = data[n//2] for obj in (x, interva... |
Number of data points in the median interval. return L + interval*(n/2 - cf)/f |
def mode(data): """Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4]) 3 This also works with nominal (non-numeric) data: >>> mode(["red",... |
def _ss(data, c=None): """Return sum of square deviations of sequence data. If ``c`` is None, the mean is calculated in one pass, and the deviations from the mean are calculated in a second pass. Otherwise, deviations are calculated from ``c`` as given. Use the second case with care, as it can lead to garbage results. ... |
def unicode_to_str(text, encoding=None, errors='strict'): """Return the str representation of text in the given encoding. Unlike .encode(encoding) this function can be applied directly to a str object without the risk of double-decoding problems (which can happen if you don't use the default 'ascii' encoding) This func... |
def url_is_from_any_domain(url, domains): """Return True if the url belongs to any of the given domains""" host = parse_url(url).netloc.lower() if host: return any(((host == d.lower()) or (host.endswith('.%s' % d.lower())) for d in domains)) else: return False |
def canonicalize_url(url, keep_params=False, keep_fragments=False): """Canonicalize the given url by applying the following procedures: # a sort query arguments, first by key, then by value # b percent encode paths and query arguments. non-ASCII characters are # c percent-encoded using UTF-8 (RFC-3986) # d normalize al... |
query params parsed = extract(norm(url)) else: # Remove unwanted params parsed = extract(url_query_cleaner(normalize(url), parameterlist=config.USEFUL_QUERY_KEYS)) # Sort params, remove blank if not wanted query = urllib.urlencode(sorted(urlparse.parse_qsl(parsed.query, keep_blank_values=keep_params))) fragment = getFr... |
def parse_url(url, encoding=None): """Return urlparsed url from the given argument (which could be an already parsed url) """ return url if isinstance(url, urlparse.ParseResult) else \ urlparse.urlparse(unicode_to_str(url, encoding)) |
def _iterable_as_config_list(s): """Format an iterable as a sequence of comma-separated strings. To match what ConfigObj expects, a single item list has a trailing comma. """ items = sorted(s) if len(items) == 1: return "%s," % (items[0],) else: return ", ".join(items) |
def _dump_stats_group(self, title, items, normal_formatter=None, verbose_formatter=None): """Dump a statistics group. In verbose mode, do so as a config file so that other processors can load the information if they want to. :param normal_formatter: the callable to apply to the value before displaying it in normal mode... |
def blob_handler(self, cmd): """Process a BlobCommand.""" self.cmd_counts[cmd.name] += 1 if cmd.mark is None: self.blobs['unmarked'].add(cmd.id) else: self.blobs['new'].add(cmd.id) # Marks can be re-used so remove it from used if already there. # Note: we definitely do NOT want to remove it from multi if # it's already... |
def commit_handler(self, cmd): """Process a CommitCommand.""" self.cmd_counts[cmd.name] += 1 self.committers.add(cmd.committer) if cmd.author is not None: self.separate_authors_found = True for fc in cmd.iter_files(): self.file_cmd_counts[fc.name] += 1 if isinstance(fc, commands.FileModifyCommand): if fc.mode & 0o111: ... |
def reset_handler(self, cmd): """Process a ResetCommand.""" self.cmd_counts[cmd.name] += 1 if cmd.ref.startswith('refs/tags/'): self.lightweight_tags += 1 else: if cmd.from_ is not None: self.reftracker.track_heads_for_ref( cmd.ref, cmd.from_) |
def start_search(self, max_page=1): """method to start send query to google. Search start from page 1. max_page determine how many result expected hint: 10 result per page for google """ for page in range(1, (max_page + 1)): start = "start={0}".format(str((page - 1) * 10)) url = "{0}{1}&{2}".format(self.google, self.qu... |
def more_search(self, more_page): """Method to add more result to an already exist result. more_page determine how many result page should be added to the current result. """ next_page = self.current_page + 1 top_page = more_page + self.current_page for page in range(next_page, (top_page + 1)): start = "start={0}".form... |
def _execute_search_request(self, url): """method to execute the query to google. The specified page and keyword must already included in the url. """ try: self.request_page = requests.get(url) except requests.ConnectionError: print("Connection to {0} failed".format(str(url))) self.current_html_page = self.request_page... |
inspect if the current page is the final page for href in results: fnl = 'repeat the search with the omitted results included' if href.get_text() == fnl: self.is_final_page = True else: pass # send the final url link to class reserved variable for link in links: self.search_result.append(link) |
def readConfig(self, configuration): """Read configuration from dict. Read configuration from a JSON configuration file. :param configuration: configuration to load. :type configuration: dict. """ self.__logger.debug("Reading configuration") self.city = configuration["name"] self.__logger.info("City name: " + self.city... |
def readConfigFromJSON(self, fileName): """Read configuration from JSON. :param fileName: path to the configuration file. :type fileName: str. """ self.__logger.debug("readConfigFromJSON: reading from " + fileName) with open(fileName) as data_file: data = load(data_file) self.readConfig(data) |
def configToJson(self, fileName): """Save the configuration of the city in a JSON. :param fileName: path to the output file. :type fileName: str. """ config = self.getConfig() with open(fileName, "w") as outfile: dump(config, outfile, indent=4, sort_keys=True) |
def getConfig(self): """Return the configuration of the city. :return: configuration of the city. :rtype: dict. """ config = {} config["name"] = self.city config["intervals"] = self.__intervals config["last_date"] = self.__lastDay config["excludedUsers"] = [] config["excludedLocations"] = [] for e in self.__excludedUse... |
def addFilter(self, field, value): """Add a filter to the seach. :param field: what field filter (see GitHub search). :type field: str. :param value: value of the filter (see GitHub search). :type value: str. """ if "<" not in value or ">" not in value or ".." not in value: value = ":" + value if self.__urlFilters: sel... |
def __processUsers(self): """Process users of the queue.""" while self.__usersToProccess.empty() and not self.__end: pass while not self.__end or not self.__usersToProccess.empty(): self.__lockGetUser.acquire() try: new_user = self.__usersToProccess.get(False) except Empty: self.__lockGetUser.release() return else: sel... |
def __addUser(self, new_user): """Add new users to the list. :param new_user: name of a GitHub user to include in the ranking :type new_user: str. """ self.__lockReadAddUser.acquire() if new_user not in self.__cityUsers and \ new_user not in self.__excludedUsers: self.__lockReadAddUser.release() self.__logger.debug("__... |
def __getPeriodUsers(self, start_date, final_date): """Get all the users given a period. :param start_date: start date of the range to search users :type start_date: time.date. :param final_date: final date of the range to search users :type final_date: time.date. """ self.__logger.info("Getting users from " + start_da... |
def getCityUsers(self, numberOfThreads=20): """Get all the users from the city. :param numberOfThreads: number of threads to run. :type numberOfThreads: int. """ if not self.__intervals: self.__logger.debug("Calculating best intervals") self.calculateBestIntervals() self.__end = False self.__threads = set() comprobatio... |
def calculateBestIntervals(self): """Calcule valid intervals of a city.""" self.__intervals = [] self.__readAPI(self.__getURL()) today = datetime.datetime.now().date() self.__validInterval(datetime.date(2008, 1, 1), today) self.__logger.info("Total number of intervals: " + str(len(self.__intervals))) self.__lastDay = t... |
def __validInterval(self, start, finish): """Check if the interval is correct. An interval is correct if it has less than 1001 users. If the interval is correct, it will be added to '_intervals' attribute. Else, interval will be split in two news intervals and these intervals will be checked. :param start: start date o... |
def export(self, template_file_name, output_file_name, sort="public", data=None, limit=0): """Export ranking to a file. Args: template_file_name (str): where is the template (moustache template) output_file_name (str): where create the file with the ranking sort (str): field to sort the users """ exportedData = {} expo... |
def getSortedUsers(self, order="public"): """Return a list with sorted users. :param order: the field to sort the users. - contributions (total number of contributions) - public (public contributions) - private (private contributions) - name - followers - join - organizations - repositories :type order: str. :return: a... |
def __exportUsers(self, sort, limit=0): """Export the users to a dictionary. :param sort: field to sort the users :type sort: str. :return: exported users. :rtype: dict. """ position = 1 dataUsers = self.getSortedUsers(sort) if limit: dataUsers = dataUsers[:limit] exportedUsers = [] for u in dataUsers: userExported = u... |
def calculeToday(self): """Calcule the intervals from the last date.""" self.__logger.debug("Add today") last = datetime.datetime.strptime(self.__lastDay, "%Y-%m-%d") today = datetime.datetime.now().date() self.__validInterval(last, today) |
def __addLocationsToURL(self, locations): """Format all locations to GitHub's URL API. :param locations: locations where to search users. :type locations: list(str). """ for l in self.__locations: self.__urlLocations += "+location:\""\ + str(quote(l)) + "\"" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.