code stringlengths 1 18.2k |
|---|
def prune(tdocs): """ Prune terms which are totally subsumed by a phrase This could be better if it just removes the individual keywords that occur in a phrase for each time that phrase occurs. """ all_terms = set([t for toks in tdocs for t in toks]) terms = set() phrases = set() for t in all_terms: if gram_size(t) > 1... |
term=t) for d in tdocs): cleared.add(t) redundant = redundant.difference(cleared) pruned_tdocs = [] for doc in tdocs: pruned_tdocs.append([t for t in doc if t not in redundant]) return pruned_tdocs |
def build_CLASS(prefix): """ Function to dowwnload CLASS from github and and build the library """ # latest class version and download link args = (package_basedir, package_basedir, CLASS_VERSION, os.path.abspath(prefix)) command = 'sh %s/depends/install_class.sh %s %s %s' %args ret = os.system(command) if ret != 0: ra... |
def format_number(number): """ >>> format_number(1) 1 >>> format_number(22) 22 >>> format_number(333) 333 >>> format_number(4444) '4,444' >>> format_number(55555) '55,555' >>> format_number(666666) '666,666' >>> format_number(7777777) '7,777,777' """ char_list = list(str(number)) length = len(char_list) if length <= 3:... |
def generate_key(url, page_number): """ >>> url_a = 'http://localhost:5009/search?keywords=a' >>> generate_key(url_a, 10) 'http://localhost:5009/search?keywords=a&page=10' >>> url_b = 'http://localhost:5009/search?keywords=b&page=1' >>> generate_key(url_b, 10) 'http://localhost:5009/search?keywords=b&page=10' """ index... |
def generate_pagination(total_page_num, current_page_num): """ >>> PAGE_SIZE = 10 >>> generate_pagination(total_page_num=9, current_page_num=1) {'start': 1, 'end': 9, 'current': 1} >>> generate_pagination(total_page_num=20, current_page_num=12) {'start': 8, 'end': 17, 'current': 12} >>> generate_pagination(total_page_n... |
def main(filename): """ Creates a PDF by embedding the first page from the given image and writes some text to it. @param[in] filename The source filename of the image to embed. """ # Prepare font. font_family = 'arial' font = Font(font_family, bold=True) if not font: raise RuntimeError('No font found for %r' % font_fa... |
def login(self, password): """Login to filemail as the current user. :param password: :type password: ``str`` """ method, url = get_URL('login') payload = { 'apikey': self.config.get('apikey'), 'username': self.username, 'password': password, 'source': 'Desktop' } res = getattr(self.session, method)(url, params=payload... |
def logout(self): """Logout of filemail and closing the session.""" # Check if all transfers are complete before logout self.transfers_complete payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken') } method, url = get_URL('logout') res = getattr(self.session, method)(url,... |
def transfers_complete(self): """Check if all transfers are completed.""" for transfer in self.transfers: if not transfer.is_complete: error = { 'errorcode': 4003, 'errormessage': 'You must complete transfer before logout.' } hellraiser(error) |
def get_sent(self, expired=False, for_all=False): """Retreve information on previously sent transfers. :param expired: Whether or not to return expired transfers. :param for_all: Get transfers for all users. Requires a Filemail Business account. :type for_all: bool :type expired: bool :rtype: ``list`` of :class:`pyfile... |
def get_user_info(self, save_to_config=True): """Get user info and settings from Filemail. :param save_to_config: Whether or not to save settings to config file :type save_to_config: ``bool`` :rtype: ``dict`` containig user information and default settings. """ method, url = get_URL('user_get') payload = { 'apikey': se... |
def update_user_info(self, **kwargs): """Update user info and settings. :param \*\*kwargs: settings to be merged with :func:`User.get_configfile` setings and sent to Filemail. :rtype: ``bool`` """ if kwargs: self.config.update(kwargs) method, url = get_URL('user_update') res = getattr(self.session, method)(url, params=... |
def get_received(self, age=None, for_all=True): """Retrieve a list of transfers sent to you or your company from other people. :param age: between 1 and 90 days. :param for_all: If ``True`` will return received files for all users in the same business. (Available for business account members only). :type age: ``int`` :... |
def _restore_transfers(self, response): """Restore transfers from josn retreived Filemail :param response: response object from request :rtype: ``list`` with :class:`Transfer` objects """ transfers = [] for transfer_data in response.json()['transfers']: transfer = Transfer(self, _restore=True) transfer.transfer_info.up... |
def get_contact(self, email): """Get Filemail contact based on email. :param email: address of contact :type email: ``str``, ``unicode`` :rtype: ``dict`` with contact information """ contacts = self.get_contacts() for contact in contacts: if contact['email'] == email: return contact msg = 'No contact with email: "{emai... |
def update_contact(self, contact): """Update name and/or email for contact. :param contact: with updated info :type contact: ``dict`` :rtype: ``bool`` """ if not isinstance(contact, dict): raise AttributeError('contact must be a <dict>') method, url = get_URL('contacts_update') payload = { 'apikey': self.config.get('ap... |
def get_group(self, name): """Get contact group by name :param name: name of group :type name: ``str``, ``unicode`` :rtype: ``dict`` with group data """ groups = self.get_groups() for group in groups: if group['contactgroupname'] == name: return group msg = 'No group named: "{name}" found.' raise FMBaseError(msg.format... |
def delete_group(self, name): """Delete contact group :param name: of group :type name: ``str``, ``unicode`` :rtype: ``bool`` """ group = self.get_group(name) method, url = get_URL('group_delete') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'contactgroupid': gr... |
def rename_group(self, group, newname): """Rename contact group :param group: group data or name of group :param newname: of group :type group: ``str``, ``unicode``, ``dict`` :type newname: ``str``, ``unicode`` :rtype: ``bool`` """ if isinstance(group, basestring): group = self.get_contact(group) method, url = get_URL(... |
def add_contact_to_group(self, contact, group): """Add contact to group :param contact: name or contact object :param group: name or group object :type contact: ``str``, ``unicode``, ``dict`` :type group: ``str``, ``unicode``, ``dict`` :rtype: ``bool`` """ if isinstance(contact, basestring): contact = self.get_contact(... |
def get_company_info(self): """Get company settings from Filemail :rtype: ``dict`` with company data """ method, url = get_URL('company_get') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken') } res = getattr(self.session, method)(url, params=payload) if res.status_cod... |
def update_company(self, company): """Update company settings :param company: updated settings :type company: ``dict`` :rtype: ``bool`` """ if not isinstance(company, dict): raise AttributeError('company must be a <dict>') method, url = get_URL('company_update') payload = { 'apikey': self.config.get('apikey'), 'loginto... |
def get_company_user(self, email): """Get company user based on email. :param email: address of contact :type email: ``str``, ``unicode`` :rtype: ``dict`` with contact information """ users = self.get_company_users() for user in users: if user['email'] == email: return user msg = 'No user with email: "{email}" associat... |
def company_add_user(self, email, name, password, receiver, admin): """Add a user to the company account. :param email: :param name: :param password: Pass without storing in plain text :param receiver: Can user receive files :param admin: :type email: ``str`` or ``unicode`` :type name: ``str`` or ``unicode`` :type pass... |
def update_company_user(self, email, userdata): """Update a company users settings :param email: current email address of user :param userdata: updated settings :type email: ``str`` or ``unicode`` :type userdata: ``dict`` :rtype: ``bool`` """ if not isinstance(userdata, dict): raise AttributeError('userdata must be a <... |
def home(request): """This view generates the data for the home page. This login restricted view passes dictionaries containing the current cages, animals and strains as well as the totals for each. This data is passed to the template home.html""" cage_list = Animal.objects.values("Cage").distinct() cage_list_current =... |
def col_widths(self): # type: () -> defaultdict """Get MAX possible width of each column in the table. :return: defaultdict """ _widths = defaultdict(int) all_rows = [self.headers] all_rows.extend(self._rows) for row in all_rows: for idx, col in enumerate(row): _col_l = len(col) if _col_l > _widths[idx]: _widths[idx] =... |
def _marker_line(self): # type: () -> str """Generate a correctly sized marker line. e.g. '+------------------+---------+----------+---------+' :return: str """ output = '' for col in sorted(self.col_widths): line = self.COLUMN_MARK + (self.DASH * (self.col_widths[col] + self.PADDING * 2)) output += line output += self... |
def _row_to_str(self, row): # type: (List[str]) -> str """Converts a list of strings to a correctly spaced and formatted row string. e.g. ['some', 'foo', 'bar'] --> '| some | foo | bar |' :param row: list :return: str """ _row_text = '' for col, width in self.col_widths.items(): _row_text += self.COLUMN_SEP l_pad, r_pa... |
def _table_to_str(self): # type: () -> str """Return single formatted table string. :return: str """ _marker_line = self._marker_line() output = _marker_line + self._row_to_str(self.headers) + _marker_line for row in self._rows: output += self._row_to_str(row) output += _marker_line return output |
def sift4(s1, s2, max_offset=5): """ This is an implementation of general Sift4. """ t1, t2 = list(s1), list(s2) l1, l2 = len(t1), len(t2) if not s1: return l2 if not s2: return l1 # Cursors for each string c1, c2 = 0, 0 # Largest common subsequence lcss = 0 # Local common substring local_cs = 0 # Number of transpositi... |
ofs['c1']) if is_trans: trans += 1 elif not ofs['trans']: ofs['trans'] = True trans += 1 break elif c1 > ofs['c2'] and c2 > ofs['c1']: del offsets[i] else: i += 1 offsets.append({ 'c1': c1, 'c2': c2, 'trans': is_trans }) else: lcss += local_cs local_cs = 0 if c1 != c2: c1 = c2 = min(c1, c2) for i in range(max_offset): ... |
local_cs local_cs = 0 c1 = c2 = min(c1, c2) lcss += local_cs return round(max(l1, l2) - lcss + trans) |
def save(self, *args, **kwargs): '''The slug field is auto-populated during the save from the name field.''' if not self.id: self.slug = slugify(self.name) super(Cohort, self).save(*args, **kwargs) |
def pick(self, filenames: Iterable[str]) -> str: """Pick one filename based on priority rules.""" filenames = sorted(filenames, reverse=True) # e.g., v2 before v1 for priority in sorted(self.rules.keys(), reverse=True): patterns = self.rules[priority] for pattern in patterns: for filename in filenames: if pattern.searc... |
def train_tf(tokens_stream, out=None, **kwargs): """ Train a map of term frequencies on a list of files (parallelized). """ print('Counting terms...') results = parallel(count_tf, tokens_stream, n_jobs=-1) print('Merging...') tf = merge(results) if out is not None: with open(out, 'w') as f: json.dump(tf, f) return tf |
def count_tf(tokens_stream): """ Count term frequencies for a single file. """ tf = defaultdict(int) for tokens in tokens_stream: for token in tokens: tf[token] += 1 return tf |
def validate_config(cls, config): """ Validates a config dictionary parsed from a cluster config file. Checks that a discovery method is defined and that at least one of the balancers in the config are installed and available. """ if "discovery" not in config: raise ValueError("No discovery method defined.") installed_... |
def apply_config(self, config): """ Sets the `discovery` and `meta_cluster` attributes, as well as the configured + available balancer attributes from a given validated config. """ self.discovery = config["discovery"] self.meta_cluster = config.get("meta_cluster") for balancer_name in Balancer.get_installed_classes().k... |
def command(state, args): """Search Animanager database.""" args = parser.parse_args(args[1:]) where_queries = [] params = {} if args.watching or args.available: where_queries.append('regexp IS NOT NULL') if args.query: where_queries.append('title LIKE :title') params['title'] = _compile_sql_query(args.query) if not wh... |
def _is_video(filepath) -> bool: """Check filename extension to see if it's a video file.""" if os.path.exists(filepath): # Could be broken symlink extension = os.path.splitext(filepath)[1] return extension in ('.mkv', '.mp4', '.avi') else: return False |
def _find_files(dirpath: str) -> 'Iterable[str]': """Find files recursively. Returns a generator that yields paths in no particular order. """ for dirpath, dirnames, filenames in os.walk(dirpath, topdown=True, followlinks=True): if os.path.basename(dirpath).startswith('.'): del dirnames[:] for filename in filenames: yi... |
def current(cls): """ Helper method for getting the current peer of whichever host we're running on. """ name = socket.getfqdn() ip = socket.gethostbyname(name) return cls(name, ip) |
def serialize(self): """ Serializes the Peer data as a simple JSON map string. """ return json.dumps({ "name": self.name, "ip": self.ip, "port": self.port }, sort_keys=True) |
def deserialize(cls, value): """ Generates a Peer instance via a JSON string of the sort generated by `Peer.deserialize`. The `name` and `ip` keys are required to be present in the JSON map, if the `port` key is not present the default is used. """ parsed = json.loads(value) if "name" not in parsed: raise ValueError("N... |
def default(self, obj): """ if input object is a ndarray it will be converted into a dict holding dtype, shape and the data base64 encoded """ if isinstance(obj, np.ndarray): data_b64 = base64.b64encode(obj.data).decode('utf-8') return dict(__ndarray__=data_b64, dtype=str(obj.dtype), shape=obj.shape) elif sps.issparse(... |
def _extract_meta_value(self, tag): # type: (str, List[str]) -> str """Find a target value by `tag` from given meta data. :param tag: str :param meta_data: list :return: str """ try: return [l[len(tag):] for l in self.meta_data if l.startswith(tag)][0] except IndexError: return '* Not Found *' |
def get_markup_choices(): """ Receives available markup options as list. """ available_reader_list = [] module_dir = os.path.realpath(os.path.dirname(__file__)) module_names = filter( lambda x: x.endswith('_reader.py'), os.listdir(module_dir)) for module_name in module_names: markup = module_name.split('_')[0] reader =... |
def apply_config(self, config): """ Takes the given config dictionary and sets the hosts and base_path attributes. If the kazoo client connection is established, its hosts list is updated to the newly configured value. """ self.hosts = config["hosts"] old_base_path = self.base_path self.base_path = config["path"] if no... |
def connect(self): """ Creates a new KazooClient and establishes a connection. Passes the client the `handle_connection_change` method as a callback to fire when the Zookeeper connection changes state. """ self.client = client.KazooClient(hosts=",".join(self.hosts)) self.client.add_listener(self.handle_connection_chang... |
def disconnect(self): """ Stops and closes the kazoo connection. """ logger.info("Disconnecting from Zookeeper.") self.client.stop() self.client.close() |
def handle_connection_change(self, state): """ Callback for handling changes in the kazoo client's connection state. If the connection becomes lost or suspended, the `connected` Event is cleared. Other given states imply that the connection is established so `connected` is set. """ if state == client.KazooState.LOST: i... |
def start_watching(self, cluster, callback): """ Initiates the "watching" of a cluster's associated znode. This is done via kazoo's ChildrenWatch object. When a cluster's znode's child nodes are updated, a callback is fired and we update the cluster's `nodes` attribute based on the existing child znodes and fire a pass... |
try: if self.client.exists(znode_path): break except exceptions.ConnectionClosedError: break wait_on_any( self.stop_events[znode_path], self.shutdown, timeout=NO_NODE_INTERVAL ) logger.debug("setting up ChildrenWatch for %s", znode_path) @self.client.ChildrenWatch(znode_path) def watch(children): if should_stop(): retu... |
def stop_watching(self, cluster): """ Causes the thread that launched the watch of the cluster path to end by setting the proper stop event found in `self.stop_events`. """ znode_path = "/".join([self.base_path, cluster.name]) if znode_path in self.stop_events: self.stop_events[znode_path].set() |
def report_up(self, service, port): """ Report the given service's present node as up by creating/updating its respective znode in Zookeeper and setting the znode's data to the serialized representation of the node. Waits for zookeeper to be connected before taking any action. """ wait_on_any(self.connected, self.shutd... |
def report_down(self, service, port): """ Reports the given service's present node as down by deleting the node's znode in Zookeeper if the znode is present. Waits for the Zookeeper connection to be established before further action is taken. """ wait_on_any(self.connected, self.shutdown) node = Node.current(service, p... |
def path_of(self, service, node): """ Helper method for determining the Zookeeper path for a given cluster member node. """ return "/".join([self.base_path, service.name, node.name]) |
def rating_score(obj, user): """ Returns the score a user has given an object """ if not user.is_authenticated() or not hasattr(obj, '_ratings_field'): return False ratings_descriptor = getattr(obj, obj._ratings_field) try: rating = ratings_descriptor.get(user=user).score except ratings_descriptor.model.DoesNotExist: r... |
def rate_url(obj, score=1): """ Generates a link to "rate" the given object with the provided score - this can be used as a form target or for POSTing via Ajax. """ return reverse('ratings_rate_object', args=( ContentType.objects.get_for_model(obj).pk, obj.pk, score, )) |
def unrate_url(obj): """ Generates a link to "un-rate" the given object - this can be used as a form target or for POSTing via Ajax. """ return reverse('ratings_unrate_object', args=( ContentType.objects.get_for_model(obj).pk, obj.pk, )) |
def command(state, args): """Reset anime watched episodes.""" args = parser.parse_args(args[1:]) aid = state.results.parse_aid(args.aid, default_key='db') query.update.reset(state.db, aid, args.episode) |
def cancel_job(agent, project_name, job_id): """ cancel a job. If the job is pending, it will be removed. If the job is running, it will be terminated. """ prevstate = agent.cancel(project_name, job_id)['prevstate'] if prevstate == 'pending': sqllite_agent.execute(ScrapydJobExtInfoSQLSet.DELETE_BY_ID, (job_id,)) |
def packing_job_ext_info(job_lsit_DO): """ Packing additional information of the job into the job_list_DO(JobListDO) """ ext_info = sqllite_agent.execute(ScrapydJobExtInfoSQLSet.SELECT_BY_ID, (job_lsit_DO.job_id,)) if ext_info is None or len(ext_info) <= 0: return ext_info = ext_info[0] job_lsit_DO.args = ext_info[1] j... |
def get_all_job_list(agent): """ Get all job list by each project name then return three job list on the base of different status(pending,running,finished). """ project_list = agent.get_project_list() if project_list['status'] == 'error': raise ScrapydTimeoutException project_list = project_list['projects'] pending_job... |
def get_job_amounts(agent, project_name, spider_name=None): """ Get amounts that pending job amount, running job amount, finished job amount. """ job_list = agent.get_job_list(project_name) pending_job_list = job_list['pending'] running_job_list = job_list['running'] finished_job_list = job_list['finished'] job_amounts... |
def corba_name_to_string(name): '''Convert a CORBA CosNaming.Name to a string.''' parts = [] if type(name) is not list and type(name) is not tuple: raise NotCORBANameError(name) if len(name) == 0: raise NotCORBANameError(name) for nc in name: if not nc.kind: parts.append(nc.id) else: parts.append('{0}.{1}'.format(nc.id... |
def reparse(self): '''Reparse all children of this directory. This effectively rebuilds the tree below this node. This operation takes an unbounded time to complete; if there are a lot of objects registered below this directory's context, they will all need to be parsed. ''' self._remove_all_children() self._parse_cont... |
def unbind(self, name): '''Unbind an object from the context represented by this directory. Warning: this is a dangerous operation. You may unlink an entire section of the tree and be unable to recover it. Be careful what you unbind. The name should be in the format used in paths. For example, 'manager.mgr' or 'Console... |
def tokenize(self, docs): """ Tokenizes a document, using a lemmatizer. Args: | doc (str) -- the text document to process. Returns: | list -- the list of tokens. """ if self.n_jobs == 1: return [self._tokenize(doc) for doc in docs] else: return parallel(self._tokenize, docs, self.n_jobs) |
def main(codelabel, submit): """Command line interface for testing and submitting calculations. This script extends submit.py, adding flexibility in the selected code/computer. Run './cli.py --help' to see options. """ code = Code.get_from_string(codelabel) # set up calculation calc = code.new_calc() calc.label = "comp... |
def command(state, args): """Register watching regexp for an anime.""" args = parser.parse_args(args[1:]) aid = state.results.parse_aid(args.aid, default_key='db') if args.query: # Use regexp provided by user. regexp = '.*'.join(args.query) else: # Make default regexp. title = query.select.lookup(state.db, aid, fields=... |
def from_definition(self, table: Table, version: int): """Add all columns from the table added in the specified version""" self.table(table) self.add_columns(*table.columns.get_with_version(version)) return self |
def keygen(self, keyBitLength, rawKey): """ This must be called on the object before any encryption or decryption can take place. Provide it the key bit length, which must be 128, 192, or 256, and the key, which may be a sequence of bytes or a simple string. Does not return any value. Raises an exception if the argumen... |
def encrypt(self, plainText): """Encrypt an arbitrary-length block of data. NOTE: This function formerly worked only on 16-byte blocks of `plainText`. code that assumed this should still work fine, but can optionally be modified to call `encrypt_block` instead. Args: plainText (str): data to encrypt. If the data is not... |
def decrypt(self, cipherText): """Decrypt an arbitrary-length block of data. NOTE: This function formerly worked only on 16-byte blocks of `cipherText`. code that assumed this should still work fine, but can optionally be modified to call `decrypt_block` instead. Args: cipherText (str): data to decrypt. If the data is ... |
cipherText[index:index + BLOCK_SIZE] # Pad to required length if needed if len(block) < BLOCK_SIZE: block = zero_pad(block, BLOCK_SIZE) decryptedResult += self.decrypt_block(block) return decryptedResult |
def encrypt_block(self, plainText): """Encrypt a 16-byte block of data. NOTE: This function was formerly called `encrypt`, but was changed when support for encrypting arbitrary-length strings was added. Args: plainText (str): 16-byte data. Returns: 16-byte str. Raises: TypeError if CamCrypt object has not been initiali... |
def decrypt_block(self, cipherText): """Decrypt a 16-byte block of data. NOTE: This function was formerly called `decrypt`, but was changed when support for decrypting arbitrary-length strings was added. Args: cipherText (str): 16-byte data. Returns: 16-byte str. Raises: TypeError if CamCrypt object has not been initia... |
def use_backup_if_fail(app, key): """ Return a error flag for prompt message in front-end if failure times (unceasing fail) greater than max failure times else return backup data (latest data in the cache) """ lock.acquire() try: if key not in backup: backup[key] = {} if key in fail_times and fail_times[key] % app.conf... |
def is_sleep(key): """ Determine return data by use cache if this key is in the sleep time window(happened error) """ lock.acquire() try: if key not in sleep_record: return False return time.time() < sleep_record[key] finally: lock.release() |
def command(state, args): """Add an anime from an AniDB search.""" args = parser.parse_args(args[1:]) if args.watching: rows = query.select.select(state.db, 'regexp IS NOT NULL', [], ['aid']) aids = [anime.aid for anime in rows] elif args.incomplete: rows = query.select.select(state.db, 'enddate IS NULL', [], ['aid']) ... |
def restart(self): """ Performs a soft reload of the HAProxy process. """ version = self.get_version() command = [ "haproxy", "-f", self.config_file_path, "-p", self.pid_file_path ] if version and version >= (1, 5, 0): command.extend(["-L", self.peer.name]) if os.path.exists(self.pid_file_path): with open(self.pid_file... |
def get_version(self): """ Returns a tuple representing the installed HAProxy version. The value of the tuple is (<major>, <minor>, <patch>), e.g. if HAProxy version 1.5.3 is installed, this will return `(1, 5, 3)`. """ command = ["haproxy", "-v"] try: output = subprocess.check_output(command) version_line = output.spl... |
def get_info(self): """ Parses the output of a "show info" HAProxy command and returns a simple dictionary of the results. """ info_response = self.send_command("show info") if not info_response: return {} def convert_camel_case(string): return all_cap_re.sub( r'\1_\2', first_cap_re.sub(r'\1_\2', string) ).lower() retu... |
def get_active_nodes(self): """ Returns a dictionary of lists, where the key is the name of a service and the list includes all active nodes associated with that service. """ # the -1 4 -1 args are the filters <proxy_id> <type> <server_id>, # -1 for all proxies, 4 for servers only, -1 for all servers stats_response = s... |
def enable_node(self, service_name, node_name): """ Enables a given node name for the given service name via the "enable server" HAProxy command. """ logger.info("Enabling server %s/%s", service_name, node_name) return self.send_command( "enable server %s/%s" % (service_name, node_name) ) |
def disable_node(self, service_name, node_name): """ Disables a given node name for the given service name via the "disable server" HAProxy command. """ logger.info("Disabling server %s/%s", service_name, node_name) return self.send_command( "disable server %s/%s" % (service_name, node_name) ) |
def send_command(self, command): """ Sends a given command to the HAProxy control socket. Returns the response from the socket as a string. If a known error response (e.g. "Permission denied.") is given then the appropriate exception is raised. """ logger.debug("Connecting to socket %s", self.socket_file_path) sock = s... |
def process_command_response(self, command, response): """ Takes an HAProxy socket command and its response and either raises an appropriate exception or returns the formatted response. """ if response.startswith(b"Unknown command."): raise UnknownCommandError(command) if response == b"Permission denied.\n": raise Perm... |
def levenshtein(source, target): """ Cribbed from <https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python> """ if len(source) < len(target): return levenshtein(target, source) # So now we have len(source) >= len(target). if len(target) == 0: return len(source) # We call tuple() to fo... |
same (cost of 0). current_row[1:] = np.minimum( current_row[1:], np.add(previous_row[:-1], target != s)) # Deletion (target grows shorter than source): current_row[1:] = np.minimum( current_row[1:], current_row[0:-1] + 1) previous_row = current_row return previous_row[-1] |
def alphafilter(request, queryset, template): """ Render the template with the filtered queryset """ qs_filter = {} for key in list(request.GET.keys()): if '__istartswith' in key: qs_filter[str(key)] = request.GET[key] break return render_to_response( template, {'objects': queryset.filter(**qs_filter), 'unfiltered_obje... |
def to_array(self, channels=2): """Return the array of multipliers for the dynamic""" if channels == 1: return self.volume_frames.reshape(-1, 1) if channels == 2: return np.tile(self.volume_frames, (2, 1)).T raise Exception( "RawVolume doesn't know what to do with %s channels" % channels) |
def generate_simhash(self, item): """ Generate simhash based on title, description, keywords, p_texts and links_text. """ list = item['p_texts'] + item['links_text'] list.append(item['title']) list.append(item['description']) list.append(item['keywords']) return Simhash(','.join(list).strip()).hash |
def train_phrases(paths, out='data/bigram_model.phrases', tokenizer=word_tokenize, **kwargs): """ Train a bigram phrase model on a list of files. """ n = 0 for path in paths: print('Counting lines for {0}...'.format(path)) n += sum(1 for line in open(path, 'r')) print('Processing {0} lines...'.format(n)) # Change to us... |
def _phrase_doc_stream(paths, n, tokenizer=word_tokenize): """ Generator to feed sentences to the phrase model. """ i = 0 p = Progress() for path in paths: with open(path, 'r') as f: for line in f: i += 1 p.print_progress(i/n) for sent in sent_tokenize(line.lower()): tokens = tokenizer(sent) yield tokens |
def _default_hashfunc(content, hashbits): """ Default hash function is variable-length version of Python's builtin hash. :param content: data that needs to hash. :return: return a decimal number. """ if content == "": return 0 x = ord(content[0]) << 7 m = 1000003 mask = 2 ** hashbits - 1 for c in content: x = ((x * m) ... |
def _default_tokenizer_func(content, keyword_weight_pair): """ Default tokenizer function that uses jieba tokenizer. :param keyword_weight_pair: maximum pair number of the keyword-weight list. :return: return keyword-weight list. Example: [('Example',0.4511233019962264),('Hello',0.25548051420382073),...]. """ seg_list ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.