Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def output_sub_line(gandi, key, val, justify): msg = ('\t%%-%ds:%%s' % justify) % (key, (' %s' % val) if val else '') gandi.echo(msg)
[ " Base helper to output a key value using left justify." ]
Please provide a description of the function:def output_sub_generic(gandi, data, output_keys, justify=10): for key in output_keys: if key in data: output_sub_line(gandi, key, data[key], justify)
[ " Generic helper to output info from a data dict." ]
Please provide a description of the function:def output_service(gandi, service, status, justify=10): output_line(gandi, service, status, justify)
[ " Helper to output a status service information." ]
Please provide a description of the function:def output_domain(gandi, domain, output_keys, justify=12): if 'nameservers' in domain: domain['nameservers'] = format_list(domain['nameservers']) if 'services' in domain: domain['services'] = format_list(domain['services']) if 'tags' in dom...
[ " Helper to output a domain information." ]
Please provide a description of the function:def output_mailbox(gandi, mailbox, output_keys, justify=16): quota = 'quota' in output_keys responder = 'responder' in output_keys if quota: output_keys.pop(output_keys.index('quota')) if responder: output_keys.pop(output_keys.index('re...
[ " Helper to output a mailbox information." ]
Please provide a description of the function:def output_forward(gandi, domain, forward, justify=14): for dest in forward['destinations']: output_line(gandi, forward['source'], dest, justify)
[ " Helper to output a mail forward information." ]
Please provide a description of the function:def output_dns_records(gandi, records, output_keys, justify=12): for key in output_keys: real_key = 'rrset_%s' % key if real_key in records: val = records[real_key] if key == 'values': val = format_list(records...
[ " Helper to output a dns records information." ]
Please provide a description of the function:def list(gandi, datacenter, type, id, attached, detached, version, reverse, vm, vlan): if attached and detached: gandi.echo("You can't set --attached and --detached at the same time.") return output_keys = ['ip', 'state', 'dc', 'type'] ...
[ "List ips." ]
Please provide a description of the function:def info(gandi, resource): output_keys = ['ip', 'state', 'dc', 'type', 'vm', 'reverse'] datacenters = gandi.datacenter.list() ip = gandi.ip.info(resource) iface = gandi.iface.info(ip['iface_id']) vms = None if iface.get('vm_id'): vm = g...
[ "Display information about an ip.\n\n Resource can be an ip or id.\n " ]
Please provide a description of the function:def update(gandi, ip, reverse, background): if not reverse: return return gandi.ip.update(ip, {'reverse': reverse}, background)
[ "Update an ip." ]
Please provide a description of the function:def attach(gandi, ip, vm, background, force): try: ip_ = gandi.ip.info(ip) vm_ = gandi.iaas.info(vm) except UsageError: gandi.error("Can't find this ip %s" % ip) iface = gandi.iface.info(ip_['iface_id']) if iface.get('vm_id'): ...
[ "Attach an ip to a vm.\n\n ip can be an ip id or ip\n vm can be a vm id or name.\n " ]
Please provide a description of the function:def create(gandi, datacenter, bandwidth, ip_version, vlan, ip, attach, background): if ip_version != 4 and vlan: gandi.echo('You must have an --ip-version to 4 when having a vlan.') return if ip and not vlan: gandi.echo('You m...
[ "Create a public or private ip\n " ]
Please provide a description of the function:def detach(gandi, resource, background, force): if not force: proceed = click.confirm('Are you sure you want to detach ip %s?' % resource) if not proceed: return return gandi.ip.detach(resource, backgr...
[ "Detach an ip from it's currently attached vm.\n\n resource can be an ip id or ip.\n " ]
Please provide a description of the function:def delete(gandi, resource, background, force): resource = sorted(tuple(set(resource))) possible_resources = gandi.ip.resource_list() # check that each IP can be deleted for item in resource: if item not in possible_resources: gandi....
[ "Delete one or more IPs (after detaching them from VMs if necessary).\n\n resource can be an ip id or ip.\n " ]
Please provide a description of the function:def get(gandi, g, key): val = gandi.get(key=key, global_=g) if not val: gandi.echo("No value found.") sys.exit(1) gandi.echo(val)
[ "Display value of a given config key." ]
Please provide a description of the function:def set(gandi, g, key, value): gandi.configure(global_=g, key=key, val=value)
[ "Update or create config key/value." ]
Please provide a description of the function:def edit(gandi, g): config_file = gandi.home_config if g else gandi.local_config path = os.path.expanduser(config_file) editor = gandi.get('editor') if not editor: try: editor = click.prompt("Please enter the path of your prefered " ...
[ "Edit config file with prefered text editor", "\nWarning: editor is not configured.\nYou can use both 'gandi config set [-g] editor <value>'\nor the $EDITOR environment variable to configure it." ]
Please provide a description of the function:def delete(gandi, g, key): gandi.delete(global_=g, key=key)
[ "Delete a key/value pair from configuration" ]
Please provide a description of the function:def create(cls, name, datacenter, backends, vhosts, algorithm, ssl_enable, zone_alter): datacenter_id_ = int(Datacenter.usable_id(datacenter)) params = { 'datacenter_id': datacenter_id_, 'name': name, ...
[ " Create a webaccelerator " ]
Please provide a description of the function:def update(cls, resource, new_name, algorithm, ssl_enable, ssl_disable): params = {} if new_name: params['name'] = new_name if algorithm: params['lb'] = {'algorithm': algorithm} if ssl_enable: param...
[ " Update a webaccelerator" ]
Please provide a description of the function:def delete(cls, name): result = cls.call('hosting.rproxy.delete', cls.usable_id(name)) cls.echo('Deleting your webaccelerator named %s' % name) cls.display_progress(result) cls.echo('Webaccelerator have been deleted') return r...
[ " Delete a webaccelerator " ]
Please provide a description of the function:def backend_add(cls, name, backend): oper = cls.call( 'hosting.rproxy.server.create', cls.usable_id(name), backend) cls.echo('Adding backend %s:%s into webaccelerator' % (backend['ip'], backend['port'])) cls.displ...
[ " Add a backend into a webaccelerator " ]
Please provide a description of the function:def backend_disable(cls, backend): server = cls.backend_list(backend) oper = cls.call('hosting.rproxy.server.disable', server[0]['id']) cls.echo('Desactivating backend on server %s' % server[0]['ip']) ...
[ " Disable a backend for a server " ]
Please provide a description of the function:def vhost_add(cls, resource, params): try: oper = cls.call( 'hosting.rproxy.vhost.create', cls.usable_id(resource), params) cls.echo('Adding your virtual host (%s) into %s' % (params['vhost'], reso...
[ " Add a vhost into a webaccelerator " ]
Please provide a description of the function:def vhost_remove(cls, name): oper = cls.call('hosting.rproxy.vhost.delete', name) cls.echo('Deleting your virtual host %s' % name) cls.display_progress(oper) cls.echo('Your virtual host have been removed') return oper
[ " Delete a vhost in a webaccelerator " ]
Please provide a description of the function:def probe(cls, resource, enable, disable, test, host, interval, http_method, http_response, threshold, timeout, url, window): params = { 'host': host, 'interval': interval, 'method': http_method, ...
[ " Set a probe for a webaccelerator " ]
Please provide a description of the function:def probe_enable(cls, resource): oper = cls.call('hosting.rproxy.probe.enable', cls.usable_id(resource)) cls.echo('Activating probe on %s' % resource) cls.display_progress(oper) cls.echo('The probe have been activated') return...
[ " Activate a probe on a webaccelerator " ]
Please provide a description of the function:def probe_disable(cls, resource): oper = cls.call('hosting.rproxy.probe.disable', cls.usable_id(resource)) cls.echo('Desactivating probe on %s' % resource) cls.display_progress(oper) cls.echo('The probe have be...
[ " Disable a probe on a webaccelerator " ]
Please provide a description of the function:def usable_id(cls, id): try: # id is maybe a hostname qry_id = cls.from_name(id) if not qry_id: # id is maybe an ip qry_id = cls.from_ip(id) if not qry_id: qry_id...
[ " Retrieve id from input which can be hostname, vhost, id. " ]
Please provide a description of the function:def from_name(cls, name): result = cls.list({'items_per_page': 500}) webaccs = {} for webacc in result: webaccs[webacc['name']] = webacc['id'] return webaccs.get(name)
[ "Retrieve webacc id associated to a webacc name." ]
Please provide a description of the function:def from_ip(cls, ip): result = cls.list({'items_per_page': 500}) webaccs = {} for webacc in result: for server in webacc['servers']: webaccs[server['ip']] = webacc['id'] return webaccs.get(ip)
[ "Retrieve webacc id associated to a webacc ip" ]
Please provide a description of the function:def from_vhost(cls, vhost): result = cls.list({'items_per_page': 500}) webaccs = {} for webacc in result: for vhost in webacc['vhosts']: webaccs[vhost['name']] = webacc['id'] return webaccs.get(vhost)
[ "Retrieve webbacc id associated to a webacc vhost" ]
Please provide a description of the function:def descriptions(cls): schema = cls.json_get('%s/status/schema' % cls.api_url, empty_key=True, send_key=False) descs = {} for val in schema['fields']['status']['value']: descs.update(val) retu...
[ " Retrieve status descriptions from status.gandi.net. " ]
Please provide a description of the function:def services(cls): return cls.json_get('%s/services' % cls.api_url, empty_key=True, send_key=False)
[ "Retrieve services statuses from status.gandi.net." ]
Please provide a description of the function:def status(cls): return cls.json_get('%s/status' % cls.api_url, empty_key=True, send_key=False)
[ "Retrieve global status from status.gandi.net." ]
Please provide a description of the function:def events(cls, filters): current = filters.pop('current', False) current_params = [] if current: current_params = [('current', 'true')] filter_url = uparse.urlencode(sorted(list(filters.items())) + current_params) # noq...
[ "Retrieve events details from status.gandi.net." ]
Please provide a description of the function:def list(gandi, state, id, vhosts, type, limit): options = { 'items_per_page': limit, } if state: options['state'] = state output_keys = ['name', 'state'] if id: output_keys.append('id') if vhosts: output_keys.app...
[ "List PaaS instances." ]
Please provide a description of the function:def info(gandi, resource, stat): output_keys = ['name', 'type', 'size', 'memory', 'console', 'vhost', 'dc', 'sftp_server', 'git_server', 'snapshot'] paas = gandi.paas.info(resource) paas_hosts = [] list_vhost = gandi.vhost.list({'paas...
[ "Display information about a PaaS instance.\n\n Resource can be a vhost, a hostname, or an ID\n Cache statistics are based on 24 hours data.\n " ]
Please provide a description of the function:def clone(gandi, name, vhost, directory, origin): if vhost != 'default': directory = vhost else: directory = name if not directory else directory return gandi.paas.clone(name, vhost, directory, origin)
[ "Clone a remote vhost in a local git repository." ]
Please provide a description of the function:def attach(gandi, name, vhost, remote): return gandi.paas.attach(name, vhost, remote)
[ "Add remote for an instance's default vhost to the local git repository.\n " ]
Please provide a description of the function:def create(gandi, name, size, type, quantity, duration, datacenter, vhosts, password, snapshotprofile, background, sshkey, ssl, private_key, poll_cert): try: gandi.datacenter.is_opened(datacenter, 'paas') except DatacenterLimited as...
[ "Create a new PaaS instance and initialize associated git repository.\n\n you can specify a configuration entry named 'sshkey' containing\n path to your sshkey file\n\n $ gandi config set [-g] sshkey ~/.ssh/id_rsa.pub\n\n or getting the sshkey \"my_key\" from your gandi ssh keyring\n\n $ gandi config...
Please provide a description of the function:def update(gandi, resource, name, size, quantity, password, sshkey, upgrade, console, snapshotprofile, reset_mysql_password, background, delete_snapshotprofile): if snapshotprofile and delete_snapshotprofile: raise UsageError('You must...
[ "Update a PaaS instance.\n\n Resource can be a Hostname or an ID\n " ]
Please provide a description of the function:def restart(gandi, resource, background, force): output_keys = ['id', 'type', 'step'] possible_resources = gandi.paas.resource_list() for item in resource: if item not in possible_resources: gandi.echo('Sorry PaaS instance %s does not ex...
[ "Restart a PaaS instance.\n\n Resource can be a vhost, a hostname, or an ID\n " ]
Please provide a description of the function:def types(gandi): options = {} types = gandi.paas.type_list(options) for type_ in types: gandi.echo(type_['name']) return types
[ "List types PaaS instances." ]
Please provide a description of the function:def list(gandi, id, limit): options = { 'items_per_page': limit, } output_keys = ['name', 'fingerprint'] if id: output_keys.append('id') result = gandi.sshkey.list(options) for num, sshkey in enumerate(result): if num: ...
[ " List SSH keys. " ]
Please provide a description of the function:def info(gandi, resource, id, value): output_keys = ['name', 'fingerprint'] if id: output_keys.append('id') if value: output_keys.append('value') ret = [] for item in resource: sshkey = gandi.sshkey.info(item) ret.ap...
[ "Display information about an SSH key.\n\n Resource can be a name or an ID\n " ]
Please provide a description of the function:def create(gandi, name, value=None, filename=None): if not value and not filename: raise UsageError('You must set value OR filename.') if value and filename: raise UsageError('You must not set value AND filename.') if filename: valu...
[ " Create a new SSH key. " ]
Please provide a description of the function:def create(gandi): contact = {} for field, label, checks in FIELDS: ask_field(gandi, contact, field, label, checks) default_pwd = randomstring(16) contact['password'] = click.prompt('Please enter your password', ...
[ " Create a new contact.\n " ]
Please provide a description of the function:def creditusage(cls): rating = cls.call('hosting.rating.list') if not rating: return 0 rating = rating.pop() usage = [sum(resource.values()) for resource in rating.values() if isinstance(...
[ "Get credit usage per hour" ]
Please provide a description of the function:def all(cls): account = cls.info() creditusage = cls.creditusage() if not creditusage: return account left = account['credits'] / creditusage years, hours = divmod(left, 365 * 24) months, hours = divmod(h...
[ " Get all informations about this account " ]
Please provide a description of the function:def list(gandi, only_paas, only_vm): target = None if only_paas and not only_vm: target = 'paas' if only_vm and not only_paas: target = 'vm' output_keys = ['id', 'name', 'kept_total', 'target'] result = gandi.snapshotprofile.list({},...
[ " List snapshot profiles. " ]
Please provide a description of the function:def info(gandi, resource): output_keys = ['id', 'name', 'kept_total', 'target', 'quota_factor', 'schedules'] result = gandi.snapshotprofile.info(resource) output_snapshot_profile(gandi, result, output_keys) return result
[ " Display information about a snapshot profile.\n\n Resource can be a profile name or ID\n " ]
Please provide a description of the function:def packages(gandi): gandi.echo('/!\ "gandi certificate packages" is deprecated.') gandi.echo('Please use "gandi certificate plans".') return _plans(gandi, with_name=True)
[ " List certificate packages.\n /!\\\\ deprecated call.\n " ]
Please provide a description of the function:def list(gandi, id, altnames, csr, cert, all_status, status, dates, limit): options = {'items_per_page': limit} if not all_status: options['status'] = ['valid', 'pending'] output_keys = ['cn', 'plan'] if id: output_keys.append('id') ...
[ " List certificates. " ]
Please provide a description of the function:def info(gandi, resource, id, altnames, csr, cert, all_status): output_keys = ['cn', 'date_created', 'date_end', 'plan', 'status'] if id: output_keys.append('id') if altnames: output_keys.append('altnames') if csr: output_keys....
[ " Display information about a certificate.\n\n Resource can be a CN or an ID\n " ]
Please provide a description of the function:def export(gandi, resource, output, force, intermediate): ids = [] for res in resource: ids.extend(gandi.certificate.usable_ids(res)) if output and len(ids) > 1: gandi.echo('Too many certs found, you must specify which cert you ' ...
[ " Write the certificate to <output> or <fqdn>.crt.\n\n Resource can be a CN or an ID\n " ]
Please provide a description of the function:def create(gandi, csr, private_key, common_name, country, state, city, organisation, branch, duration, package, type, max_altname, warranty, altnames, dcv_method): if not (csr or common_name): gandi.echo('You need a CSR or a CN to creat...
[ "Create a new certificate." ]
Please provide a description of the function:def update(gandi, resource, csr, private_key, country, state, city, organisation, branch, altnames, dcv_method): ids = gandi.certificate.usable_ids(resource) if len(ids) > 1: gandi.echo('Will not update, %s is not precise enough.' % resource)...
[ " Update a certificate CSR.\n\n Resource can be a CN or an ID\n " ]
Please provide a description of the function:def follow(gandi, resource): oper = gandi.oper.info(int(resource)) assert(oper['type'].startswith('certificate_')) output_cert_oper(gandi, oper) return oper
[ " Get the operation status\n\n Resource is an operation ID\n " ]
Please provide a description of the function:def change_dcv(gandi, resource, dcv_method): ids = gandi.certificate.usable_ids(resource) if len(ids) > 1: gandi.echo('Will not update, %s is not precise enough.' % resource) gandi.echo(' * cert : ' + '\n * cert : '.join([st...
[ " Change the DCV for a running certificate operation.\n\n Resource can be a CN or an ID\n " ]
Please provide a description of the function:def resend_dcv(gandi, resource): ids = gandi.certificate.usable_ids(resource) if len(ids) > 1: gandi.echo('Will not update, %s is not precise enough.' % resource) gandi.echo(' * cert : ' + '\n * cert : '.join([str(id_) for i...
[ " Resend the DCV mail.\n\n Resource can be a CN or an ID\n " ]
Please provide a description of the function:def delete(gandi, resource, background, force): ids = gandi.certificate.usable_ids(resource) if len(ids) > 1: gandi.echo('Will not delete, %s is not precise enough.' % resource) gandi.echo(' * cert : ' + '\n * cert : '.join(...
[ " Revoke the certificate.\n\n Resource can be a CN or an ID\n " ]
Please provide a description of the function:def list(gandi, id, vhosts, dates, fqdns, limit): justify = 10 options = {'items_per_page': limit, 'state': 'created'} output_keys = [] if id: output_keys.append('id') output_keys.append('subject') if dates: output_keys.extend...
[ " List hosted certificates. " ]
Please provide a description of the function:def info(gandi, resource): output_keys = ['id', 'subject', 'date_created', 'date_expire', 'fqdns', 'vhosts'] result = gandi.hostedcert.infos(resource) for num, hcert in enumerate(result): if num: gandi.separator_line()...
[ " Display information about a hosted certificate.\n\n Resource can be a FQDN or an ID\n " ]
Please provide a description of the function:def create(gandi, private_key, certificate, certificate_id): if not certificate and not certificate_id: gandi.echo('One of --certificate or --certificate-id is needed.') return if certificate and certificate_id: gandi.echo('Only one of --...
[ " Create a new hosted certificate. " ]
Please provide a description of the function:def delete(gandi, resource, force): infos = gandi.hostedcert.infos(resource) if not infos: return if not force: proceed = click.confirm('Are you sure to delete the following hosted ' 'certificates ?\n' + ...
[ " Delete a hosted certificate.\n\n Resource can be a FQDN or an ID\n " ]
Please provide a description of the function:def flatten(l, types=(list, float)): l = [item if isinstance(item, types) else [item] for item in l] return [item for sublist in l for item in sublist]
[ "\n Flat nested list of lists into a single list.\n " ]
Please provide a description of the function:def _find_links(self): processed = {} links = [] body = re.search('<[^>]*body[^>]*>(.+?)</body>', self.text, re.S).group(1) bodyr = body[::-1] href = "href"[::-1] span = "span"[::-1] mark_rev = "t-mark-rev"[::-...
[ "\n The link follow by the span.t-mark-rev will contained c++xx information.\n Consider the below case\n <a href=\"LinkA\">LinkA</a>\n <a href=\"LinkB\">LinkB</a>\n <span class=\"t-mark-rev\">(C++11)</span>\n We're reversing the body so it is easier to write the regex...
Please provide a description of the function:def escape_pre_section(table): def replace_newline(g): return g.group(1).replace('\n', '\n.br\n') return re.sub('<pre.*?>(.*?)</pre>', replace_newline, table, flags=re.S)
[ "Escape <pre> section in table." ]
Please provide a description of the function:def html2groff(data, name): # Remove sidebar try: data = data[data.index('<div class="C_doc">'):] except ValueError: pass # Pre replace all for rp in pre_rps: data = re.compile(rp[0], rp[2]).sub(rp[1], data) for table in...
[ "Convert HTML text from cplusplus.com to Groff-formatted text." ]
Please provide a description of the function:def update_mandb_path(): manpath_file = os.path.join(environ.HOME, ".manpath") man_dir = environ.cache_dir manindex_dir = environ.manindex_dirl lines = [] try: with open(manpath_file, 'r') as f: lines = f.readlines() ...
[ "Add $XDG_CACHE_HOME/cppman/man to $HOME/.manpath", " read all lines ", " remove MANDATORY_MANPATH and MANDB_MAP entry " ]
Please provide a description of the function:def get_width(): # Get terminal size ws = struct.pack("HHHH", 0, 0, 0, 0) ws = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, ws) lines, columns, x, y = struct.unpack("HHHH", ws) width = min(columns * 39 // 40, columns - 2) return width
[ "Get terminal width" ]
Please provide a description of the function:def groff2man(data): width = get_width() cmd = 'groff -t -Tascii -m man -rLL=%dn -rLT=%dn' % (width, width) handle = subprocess.Popen( cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) man_text, stde...
[ "Read groff-formatted text and output man pages." ]
Please provide a description of the function:def html2man(data, formatter): groff_text = formatter(data) man_text = groff2man(groff_text) return man_text
[ "Convert HTML text from cplusplus.com to man pages." ]
Please provide a description of the function:def html2groff(data, name): # Remove header and footer try: data = data[data.index('<div id="cpp-content-base">'):] data = data[:data.index('<div class="printfooter">') + 25] except ValueError: pass # Remove non-printable charact...
[ "Convert HTML text from cppreference.com to Groff-formatted text." ]
Please provide a description of the function:def extract_name(self, data): name = re.search('<h1[^>]*>(.+?)</h1>', data).group(1) name = re.sub(r'<([^>]+)>', r'', name) name = re.sub(r'&gt;', r'>', name) name = re.sub(r'&lt;', r'<', name) return name
[ "Extract man page name from web page." ]
Please provide a description of the function:def rebuild_index(self): try: os.remove(environ.index_db_re) except: pass self.db_conn = sqlite3.connect(environ.index_db_re) self.db_cursor = self.db_conn.cursor() self.db_cursor.execute('CREATE TABLE...
[ "Rebuild index database from cplusplus.com and cppreference.com." ]
Please provide a description of the function:def process_document(self, doc, std): if doc.url not in self.blacklist: print("Indexing '%s' %s..." % (doc.url, std)) name = self.extract_name(doc.text) self.results.add((name, doc.url, std)) else: prin...
[ "callback to insert index" ]
Please provide a description of the function:def parse_expression(self, expr): m = re.match(r'^(.*?(?:::)?(?:operator)?)((?:::[^:]*|[^:]*)?)$', expr); prefix = m.group(1) tail = m.group(2) return [prefix, tail]
[ "\n split expression into prefix and expression\n tested with\n ```\n operator==\n !=\n std::rel_ops::operator!=\n std::atomic::operator=\n std::array::operator[]\n std::function::operator()\n std::vector::...
Please provide a description of the function:def parse_title(self, title): m = re.match(r'^\s*((?:\(size_type\)|(?:.|\(\))*?)*)((?:\([^)]+\))?)\s*$', title) postfix = m.group(2) t_names = m.group(1).split(',') t_names = [n.strip() for n in t_names] prefix = self.parse_e...
[ "\n split of the last parenthesis operator==,!=,<,<=(std::vector)\n tested with\n ```\n operator==,!=,<,<=,>,>=(std::vector) \n operator==,!=,<,<=,>,>=(std::vector)\n operator==,!=,<,<=,>,>= \n operator==,!=,<,<=,>,>=\n ...
Please provide a description of the function:def insert_index(self, table, name, url, std=""): names = self.parse_title(name); for n in names: self.db_cursor.execute( 'INSERT INTO "%s" (name, url, std) VALUES (?, ?, ?)' % table, ( n, url, std))
[ "callback to insert index" ]
Please provide a description of the function:def cache_all(self): respond = input( 'By default, cppman fetches pages on-the-fly if corresponding ' 'page is not found in the cache. The "cache-all" option is only ' 'useful if you want to view man pages offline. ...
[ "Cache all available man pages" ]
Please provide a description of the function:def cache_man_page(self, source, url, name): # Skip if already exists, override if forced flag is true outname = self.get_page_path(source, name) if os.path.exists(outname) and not self.forced: return try: os....
[ "callback to cache new man page" ]
Please provide a description of the function:def man(self, pattern): try: avail = os.listdir(os.path.join(environ.cache_dir, environ.source)) except OSError: avail = [] if not os.path.exists(environ.index_db): raise RuntimeError("can't find index.db"...
[ "Call viewer.sh to view man page" ]
Please provide a description of the function:def find(self, pattern): if not os.path.exists(environ.index_db): raise RuntimeError("can't find index.db") conn = sqlite3.connect(environ.index_db) cursor = conn.cursor() selected = cursor.execute( 'SELECT *...
[ "Find pages in database." ]
Please provide a description of the function:def update_mandb(self, quiet=True): if not environ.config.UpdateManPath: return print('\nrunning mandb...') cmd = 'mandb %s' % (' -q' if quiet else '') subprocess.Popen(cmd, shell=True).wait()
[ "Update mandb." ]
Please provide a description of the function:def set_default(self): try: os.makedirs(os.path.dirname(self._configfile)) except: pass self._config = configparser.RawConfigParser() self._config.add_section('Settings') for key, val in self.DEFAULTS...
[ "Set config to default." ]
Please provide a description of the function:def save(self): try: os.makedirs(os.path.dirname(self._configfile)) except: pass with open(self._configfile, 'w') as f: self._config.write(f)
[ "Store config back to file." ]
Please provide a description of the function:def grab_gpus(num_gpus=1, gpu_select=None, gpu_fraction=0.95, max_procs=-1): # Set the visible devices to blank. os.environ['CUDA_VISIBLE_DEVICES'] = "" if num_gpus == 0: return 0 # Try connect with NVIDIA drivers logger = logging.getLogger...
[ "\n Checks for gpu availability and sets CUDA_VISIBLE_DEVICES as such.\n\n Note that this function does not do anything to 'reserve' gpus, it only\n limits what GPUS your program can see by altering the CUDA_VISIBLE_DEVICES\n variable. Other programs can still come along and snatch your gpu. This\n f...
Please provide a description of the function:def get_free_gpus(max_procs=0): # Try connect with NVIDIA drivers logger = logging.getLogger(__name__) try: py3nvml.nvmlInit() except: str_ = warnings.warn(str_, RuntimeWarning) logger.warn(str_) return [] nu...
[ "\n Checks the number of processes running on your GPUs.\n\n Parameters\n ----------\n max_procs : int\n Maximum number of procs allowed to run on a gpu for it to be considered\n 'available'\n\n Returns\n -------\n availabilities : list(bool)\n List of length N for an N-gpu...
Please provide a description of the function:def get_num_procs(): # Try connect with NVIDIA drivers logger = logging.getLogger(__name__) try: py3nvml.nvmlInit() except: str_ = warnings.warn(str_, RuntimeWarning) logger.warn(str_) return [] num_gpus = py...
[ " Gets the number of processes running on each gpu\n\n Returns\n -------\n num_procs : list(int)\n Number of processes running on each gpu\n\n Note\n ----\n If function can't query the driver will return an empty list rather than raise an\n Exception.\n\n Note\n ----\n If functi...
Please provide a description of the function:def _extractNVMLErrorsAsClasses(): this_module = sys.modules[__name__] nvmlErrorsNames = [x for x in dir(this_module) if x.startswith("NVML_ERROR_")] for err_name in nvmlErrorsNames: # e.g. Turn NVML_ERROR_ALREADY_INITIALIZED into NVMLError_AlreadyIn...
[ "\n Generates a hierarchy of classes on top of NVMLError class.\n\n Each NVML Error gets a new NVMLError subclass. This way try,except blocks\n can filter appropriate exceptions more easily.\n\n NVMLError is a parent class. Each NVML_ERROR_* gets it's own subclass. e.g.\n NVML_ERROR_ALREADY_INITIALI...
Please provide a description of the function:def nvmlInit(): r _LoadNvmlLibrary() # # Initialize the library # fn = _nvmlGetFunctionPointer("nvmlInit_v2") ret = fn() _nvmlCheckReturn(ret) # Atomically update refcount global _nvmlLib_refcount libLoadLock.acquire() _nvmlL...
[ "\n /**\n * Initialize NVML, but don't initialize any GPUs yet.\n *\n * \\note nvmlInit_v3 introduces a \"flags\" argument, that allows passing boolean values\n * modifying the behaviour of nvmlInit().\n * \\note In NVML 5.319 new nvmlInit_v2 has replaced nvmlInit\"_v1\" (default in NVM...
Please provide a description of the function:def _LoadNvmlLibrary(): global nvmlLib if (nvmlLib is None): # lock to ensure only one caller loads the library libLoadLock.acquire() try: # ensure the library still isn't loaded if (nvmlLib is None): ...
[ "\n Load the library if it isn't loaded already\n " ]
Please provide a description of the function:def nvmlShutdown(): r # # Leave the library loaded, but shutdown the interface # fn = _nvmlGetFunctionPointer("nvmlShutdown") ret = fn() _nvmlCheckReturn(ret) # Atomically update refcount global _nvmlLib_refcount libLoadLock.acquire()...
[ "\n /**\n * Shut down NVML by releasing all GPU resources previously allocated with \\ref nvmlInit().\n *\n * For all products.\n *\n * This method should be called after NVML work is done, once for each call to \\ref nvmlInit()\n * A reference count of the number of initializations is ma...
Please provide a description of the function:def nvmlSystemGetNVMLVersion(): r c_version = create_string_buffer(NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE) fn = _nvmlGetFunctionPointer("nvmlSystemGetNVMLVersion") ret = fn(c_version, c_uint(NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE)) _nvmlCheckReturn(ret) r...
[ "\n /**\n * Retrieves the version of the NVML library.\n *\n * For all products.\n *\n * The version identifier is an alphanumeric string. It will not exceed 80 characters in length\n * (including the NULL terminator). See \\ref nvmlConstants::NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE.\n ...
Please provide a description of the function:def nvmlSystemGetProcessName(pid): r c_name = create_string_buffer(1024) fn = _nvmlGetFunctionPointer("nvmlSystemGetProcessName") ret = fn(c_uint(pid), c_name, c_uint(1024)) _nvmlCheckReturn(ret) return bytes_to_str(c_name.value)
[ "\n /**\n * Gets name of the process with provided process id\n *\n * For all products.\n *\n * Returned process name is cropped to provided length.\n * name string is encoded in ANSI.\n *\n * @param pid The identifier of the process\n * @param...
Please provide a description of the function:def nvmlSystemGetDriverVersion(): r c_version = create_string_buffer(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE) fn = _nvmlGetFunctionPointer("nvmlSystemGetDriverVersion") ret = fn(c_version, c_uint(NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE)) _nvmlCheckReturn(re...
[ "\n /**\n * Retrieves the version of the system's graphics driver.\n *\n * For all products.\n *\n * The version identifier is an alphanumeric string. It will not exceed 80 characters in length\n * (including the NULL terminator). See \\ref nvmlConstants::NVML_SYSTEM_DRIVER_VERSION_BUFF...
Please provide a description of the function:def nvmlSystemGetHicVersion(): r c_count = c_uint(0) hics = None fn = _nvmlGetFunctionPointer("nvmlSystemGetHicVersion") # get the count ret = fn(byref(c_count), None) # this should only fail with insufficient size if ((ret != NVML_SUCCESS) ...
[ "\n /**\n * Retrieves the IDs and firmware versions for any Host Interface Cards (HICs) in the system.\n *\n * For S-class products.\n *\n * The \\a hwbcCount argument is expected to be set to the size of the input \\a hwbcEntries array.\n * The HIC must be connected to an S-class system ...
Please provide a description of the function:def nvmlUnitGetCount(): r c_count = c_uint() fn = _nvmlGetFunctionPointer("nvmlUnitGetCount") ret = fn(byref(c_count)) _nvmlCheckReturn(ret) return bytes_to_str(c_count.value)
[ "\n /**\n * Retrieves the number of units in the system.\n *\n * For S-class products.\n *\n * @param unitCount Reference in which to return the number of units\n *\n * @return\n * - \\ref NVML_SUCCESS if \\a unitCount has been se...