_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q260600
delete_locks
validation
def delete_locks(context, network_ids, addresses): """Deletes locks for each IP address that is no longer null-routed.""" addresses_no_longer_null_routed = _find_addresses_to_be_unlocked( context, network_ids, addresses) LOG.info("Deleting %s lock holders on IPAddress with ids: %s", len...
python
{ "resource": "" }
q260601
create_locks
validation
def create_locks(context, network_ids, addresses): """Creates locks for each IP address that is null-routed. The function creates the IP address if it is not present in the database. """ for address in addresses: address_model = None try: address_model = _find_or_create_ad...
python
{ "resource": "" }
q260602
IronicDriver.select_ipam_strategy
validation
def select_ipam_strategy(self, network_id, network_strategy, **kwargs): """Return relevant IPAM strategy name. :param network_id: neutron network id. :param network_strategy: default strategy for the network. NOTE(morgabra) This feels like a hack but I can't think of a better i...
python
{ "resource": "" }
q260603
IronicDriver._get_base_network_info
validation
def _get_base_network_info(self, context, network_id, base_net_driver): """Return a dict of extra network information. :param context: neutron request context. :param network_id: neturon network id. :param net_driver: network driver associated with network_id. :raises IronicExce...
python
{ "resource": "" }
q260604
IronicDriver.create_port
validation
def create_port(self, context, network_id, port_id, **kwargs): """Create a port. :param context: neutron api request context. :param network_id: neutron network id. :param port_id: neutron port id. :param kwargs: required keys - device_id: neutron port device_id (ins...
python
{ "resource": "" }
q260605
IronicDriver.update_port
validation
def update_port(self, context, port_id, **kwargs): """Update a port. :param context: neutron api request context. :param port_id: neutron port id. :param kwargs: optional kwargs. :raises IronicException: If the client is unable to update the downstream port for any r...
python
{ "resource": "" }
q260606
IronicDriver.diag_port
validation
def diag_port(self, context, port_id, **kwargs): """Diagnose a port. :param context: neutron api request context. :param port_id: neutron port id. :param kwargs: optional kwargs. :raises IronicException: If the client is unable to fetch the downstream port for any re...
python
{ "resource": "" }
q260607
Tag.set
validation
def set(self, model, value): """Set tag on model object.""" self.validate(value) self._pop(model) value = self.serialize(value) model.tags.append(value)
python
{ "resource": "" }
q260608
Tag.get
validation
def get(self, model): """Get a matching valid tag off the model.""" for tag in model.tags: if self.is_tag(tag): value = self.deserialize(tag) try: self.validate(value) return value except TagValidationErr...
python
{ "resource": "" }
q260609
Tag._pop
validation
def _pop(self, model): """Pop all matching tags off the model and return them.""" tags = [] # collect any exsiting tags with matching prefix for tag in model.tags: if self.is_tag(tag): tags.append(tag) # remove collected tags from model if ta...
python
{ "resource": "" }
q260610
Tag.pop
validation
def pop(self, model): """Pop all matching tags off the port, return a valid one.""" tags = self._pop(model) if tags: for tag in tags: value = self.deserialize(tag) try: self.validate(value) return value ...
python
{ "resource": "" }
q260611
Tag.has_tag
validation
def has_tag(self, model): """Does the given port have this tag?""" for tag in model.tags: if self.is_tag(tag): return True return False
python
{ "resource": "" }
q260612
VlanTag.validate
validation
def validate(self, value): """Validates a VLAN ID. :param value: The VLAN ID to validate against. :raises TagValidationError: Raised if the VLAN ID is invalid. """ try: vlan_id_int = int(value) assert vlan_id_int >= self.MIN_VLAN_ID assert vla...
python
{ "resource": "" }
q260613
TagRegistry.get_all
validation
def get_all(self, model): """Get all known tags from a model. Returns a dict of {<tag_name>:<tag_value>}. """ tags = {} for name, tag in self.tags.items(): for mtag in model.tags: if tag.is_tag(mtag): tags[name] = tag.get(model) ...
python
{ "resource": "" }
q260614
TagRegistry.set_all
validation
def set_all(self, model, **tags): """Validate and set all known tags on a port.""" for name, tag in self.tags.items(): if name in tags: value = tags.pop(name) if value: try: tag.set(model, value) ...
python
{ "resource": "" }
q260615
SecurityGroupsClient.serialize_rules
validation
def serialize_rules(self, rules): """Creates a payload for the redis server.""" # TODO(mdietz): If/when we support other rule types, this comment # will have to be revised. # Action and direction are static, for now. The implementation may # support 'deny' and 'egre...
python
{ "resource": "" }
q260616
SecurityGroupsClient.serialize_groups
validation
def serialize_groups(self, groups): """Creates a payload for the redis server The rule schema is the following: REDIS KEY - port_device_id.port_mac_address/sg REDIS VALUE - A JSON dump of the following: port_mac_address must be lower-cased and stripped of non-alphanumeric ...
python
{ "resource": "" }
q260617
SecurityGroupsClient.apply_rules
validation
def apply_rules(self, device_id, mac_address, rules): """Writes a series of security group rules to a redis server.""" LOG.info("Applying security group rules for device %s with MAC %s" % (device_id, mac_address)) rule_dict = {SECURITY_GROUP_RULE_KEY: rules} redis_key =...
python
{ "resource": "" }
q260618
SecurityGroupsClient.get_security_group_states
validation
def get_security_group_states(self, interfaces): """Gets security groups for interfaces from Redis Returns a dictionary of xapi.VIFs with values of the current acknowledged status in Redis. States not explicitly handled: * ack key, no rules - This is the same as just tagging th...
python
{ "resource": "" }
q260619
SecurityGroupsClient.update_group_states_for_vifs
validation
def update_group_states_for_vifs(self, vifs, ack): """Updates security groups by setting the ack field""" vif_keys = [self.vif_key(vif.device_id, vif.mac_address) for vif in vifs] self.set_fields(vif_keys, SECURITY_GROUP_ACK, ack)
python
{ "resource": "" }
q260620
run_migrations_offline
validation
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
python
{ "resource": "" }
q260621
run_migrations_online
validation
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ engine = create_engine( neutron_config.database.connection, poolclass=pool.NullPool) connection = engine.connect() ...
python
{ "resource": "" }
q260622
do_notify
validation
def do_notify(context, event_type, payload): """Generic Notifier. Parameters: - `context`: session context - `event_type`: the event type to report, i.e. ip.usage - `payload`: dict containing the payload to send """ LOG.debug('IP_BILL: notifying {}'.format(payload)) notifie...
python
{ "resource": "" }
q260623
notify
validation
def notify(context, event_type, ipaddress, send_usage=False, *args, **kwargs): """Method to send notifications. We must send USAGE when a public IPv4 address is deallocated or a FLIP is associated. Parameters: - `context`: the context for notifier - `event_type`: the event type for IP a...
python
{ "resource": "" }
q260624
build_payload
validation
def build_payload(ipaddress, event_type, event_time=None, start_time=None, end_time=None): """Method builds a payload out of the passed arguments. Parameters: `ipaddress`: the models.IPAddress object `event_type`: USAGE,CRE...
python
{ "resource": "" }
q260625
build_full_day_ips
validation
def build_full_day_ips(query, period_start, period_end): """Method to build an IP list for the case 1 when the IP was allocated before the period start and is still allocated after the period end. This method only looks at public IPv4 addresses. """ # Filter out only IPv4 that have not been dea...
python
{ "resource": "" }
q260626
calc_periods
validation
def calc_periods(hour=0, minute=0): """Returns a tuple of start_period and end_period. Assumes that the period is 24-hrs. Parameters: - `hour`: the hour from 0 to 23 when the period ends - `minute`: the minute from 0 to 59 when the period ends This method will calculate the end of the p...
python
{ "resource": "" }
q260627
_make_job_dict
validation
def _make_job_dict(job): """Creates the view for a job while calculating progress. Since a root job does not have a transaction id (TID) it will return its id as the TID. """ body = {"id": job.get('id'), "action": job.get('action'), "completed": job.get('completed'), ...
python
{ "resource": "" }
q260628
get_mac_address_range
validation
def get_mac_address_range(context, id, fields=None): """Retrieve a mac_address_range. : param context: neutron api request context : param id: UUID representing the network to fetch. : param fields: a list of strings that are valid keys in a network dictionary as listed in the RESOURCE_ATTRIBUT...
python
{ "resource": "" }
q260629
delete_mac_address_range
validation
def delete_mac_address_range(context, id): """Delete a mac_address_range. : param context: neutron api request context : param id: UUID representing the mac_address_range to delete. """ LOG.info("delete_mac_address_range %s for tenant %s" % (id, context.tenant_id)) if not context.i...
python
{ "resource": "" }
q260630
delete_segment_allocation_range
validation
def delete_segment_allocation_range(context, sa_id): """Delete a segment_allocation_range. : param context: neutron api request context : param id: UUID representing the segment_allocation_range to delete. """ LOG.info("delete_segment_allocation_range %s for tenant %s" % (sa_id, contex...
python
{ "resource": "" }
q260631
filter_factory
validation
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def wrapper(app): return ResponseAsyncIdAdder(app, conf) return wrapper
python
{ "resource": "" }
q260632
get_used_ips
validation
def get_used_ips(session, **kwargs): """Returns dictionary with keys segment_id and value used IPs count. Used IP address count is determined by: - allocated IPs - deallocated IPs whose `deallocated_at` is within the `reuse_after` window compared to the present time, excluding IPs that are accounte...
python
{ "resource": "" }
q260633
get_unused_ips
validation
def get_unused_ips(session, used_ips_counts, **kwargs): """Returns dictionary with key segment_id, and value unused IPs count. Unused IP address count is determined by: - adding subnet's cidr's size - subtracting IP policy exclusions on subnet - subtracting used ips per segment """ LOG.debu...
python
{ "resource": "" }
q260634
XapiClient.get_interfaces
validation
def get_interfaces(self): """Returns a set of VIFs from `get_instances` return value.""" LOG.debug("Getting interfaces from Xapi") with self.sessioned() as session: instances = self.get_instances(session) recs = session.xenapi.VIF.get_all_records() interfaces = ...
python
{ "resource": "" }
q260635
XapiClient.update_interfaces
validation
def update_interfaces(self, added_sg, updated_sg, removed_sg): """Handles changes to interfaces' security groups Calls refresh_interfaces on argument VIFs. Set security groups on added_sg's VIFs. Unsets security groups on removed_sg's VIFs. """ if not (added_sg or updated_sg or ...
python
{ "resource": "" }
q260636
update_network
validation
def update_network(context, id, network): """Update values of a network. : param context: neutron api request context : param id: UUID representing the network to update. : param network: dictionary with keys indicating fields to update. valid keys are those that have a value of True for 'allow...
python
{ "resource": "" }
q260637
get_network
validation
def get_network(context, id, fields=None): """Retrieve a network. : param context: neutron api request context : param id: UUID representing the network to fetch. : param fields: a list of strings that are valid keys in a network dictionary as listed in the RESOURCE_ATTRIBUTE_MAP object...
python
{ "resource": "" }
q260638
get_networks
validation
def get_networks(context, limit=None, sorts=['id'], marker=None, page_reverse=False, filters=None, fields=None): """Retrieve a list of networks. The contents of the list depends on the identity of the user making the request (as indicated by the context) as well as any filters. : p...
python
{ "resource": "" }
q260639
get_networks_count
validation
def get_networks_count(context, filters=None): """Return the number of networks. The result depends on the identity of the user making the request (as indicated by the context) as well as any filters. : param context: neutron api request context : param filters: a dictionary with keys that are vali...
python
{ "resource": "" }
q260640
delete_network
validation
def delete_network(context, id): """Delete a network. : param context: neutron api request context : param id: UUID representing the network to delete. """ LOG.info("delete_network %s for tenant %s" % (id, context.tenant_id)) with context.session.begin(): net = db_api.network_find(conte...
python
{ "resource": "" }
q260641
make_case2
validation
def make_case2(context): """This is a helper method for testing. When run with the current context, it will create a case 2 entries in the database. See top of file for what case 2 is. """ query = context.session.query(models.IPAddress) period_start, period_end = billing.calc_periods() ip_l...
python
{ "resource": "" }
q260642
main
validation
def main(notify, hour, minute): """Runs billing report. Optionally sends notifications to billing""" # Read the config file and get the admin context config_opts = ['--config-file', '/etc/neutron/neutron.conf'] config.init(config_opts) # Have to load the billing module _after_ config is parsed so ...
python
{ "resource": "" }
q260643
QuarkAsyncPluginBase.start_rpc_listeners
validation
def start_rpc_listeners(self): """Configure all listeners here""" self._setup_rpc() if not self.endpoints: return [] self.conn = n_rpc.create_connection() self.conn.create_consumer(self.topic, self.endpoints, fanout=False) ret...
python
{ "resource": "" }
q260644
QuarkAsyncPluginBase.context
validation
def context(self): """Provides an admin context for workers.""" if not self._context: self._context = context.get_admin_context() return self._context
python
{ "resource": "" }
q260645
QuarkSGAsyncProcessCallback.update_sg
validation
def update_sg(self, context, sg, rule_id, action): """Begins the async update process.""" db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE) if not db_sg: return None with context.session.begin(): job_body = dict(action="%s sg rule %s" % (action,...
python
{ "resource": "" }
q260646
QuarkSGProducerCallback.populate_subtasks
validation
def populate_subtasks(self, context, sg, parent_job_id): """Produces a list of ports to be updated async.""" db_sg = db_api.security_group_find(context, id=sg, scope=db_api.ONE) if not db_sg: return None ports = db_api.sg_gather_associated_ports(context, db_sg) if len...
python
{ "resource": "" }
q260647
QuarkSGConsumerCallback.update_ports_for_sg
validation
def update_ports_for_sg(self, context, portid, jobid): """Updates the ports through redis.""" port = db_api.port_find(context, id=portid, scope=db_api.ONE) if not port: LOG.warning("Port not found") return net_driver = port_api._get_net_driver(port.network, port=p...
python
{ "resource": "" }
q260648
sg_gather_associated_ports
validation
def sg_gather_associated_ports(context, group): """Gather all ports associated to security group. Returns: * list, or None """ if not group: return None if not hasattr(group, "ports") or len(group.ports) <= 0: return [] return group.ports
python
{ "resource": "" }
q260649
security_group_rule_update
validation
def security_group_rule_update(context, rule, **kwargs): '''Updates a security group rule. NOTE(alexm) this is non-standard functionality. ''' rule.update(kwargs) context.session.add(rule) return rule
python
{ "resource": "" }
q260650
segment_allocation_find
validation
def segment_allocation_find(context, lock_mode=False, **filters): """Query for segment allocations.""" range_ids = filters.pop("segment_allocation_range_ids", None) query = context.session.query(models.SegmentAllocation) if lock_mode: query = query.with_lockmode("update") query = query.fil...
python
{ "resource": "" }
q260651
NikoHomeControlConnection.send
validation
def send(self, s): """ Sends the given command to Niko Home Control and returns the output of the system. Aliases: write, put, sendall, send_all """ self._socket.send(s.encode()) return self.read()
python
{ "resource": "" }
q260652
if_
validation
def if_(*args): """Implements the 'if' operator with support for multiple elseif-s.""" for i in range(0, len(args) - 1, 2): if args[i]: return args[i + 1] if len(args) % 2: return args[-1] else: return None
python
{ "resource": "" }
q260653
soft_equals
validation
def soft_equals(a, b): """Implements the '==' operator, which does type JS-style coertion.""" if isinstance(a, str) or isinstance(b, str): return str(a) == str(b) if isinstance(a, bool) or isinstance(b, bool): return bool(a) is bool(b) return a == b
python
{ "resource": "" }
q260654
less
validation
def less(a, b, *args): """Implements the '<' operator with JS-style type coertion.""" types = set([type(a), type(b)]) if float in types or int in types: try: a, b = float(a), float(b) except TypeError: # NaN return False return a < b and (not args or l...
python
{ "resource": "" }
q260655
less_or_equal
validation
def less_or_equal(a, b, *args): """Implements the '<=' operator with JS-style type coertion.""" return ( less(a, b) or soft_equals(a, b) ) and (not args or less_or_equal(b, *args))
python
{ "resource": "" }
q260656
minus
validation
def minus(*args): """Also, converts either to ints or to floats.""" if len(args) == 1: return -to_numeric(args[0]) return to_numeric(args[0]) - to_numeric(args[1])
python
{ "resource": "" }
q260657
merge
validation
def merge(*args): """Implements the 'merge' operator for merging lists.""" ret = [] for arg in args: if isinstance(arg, list) or isinstance(arg, tuple): ret += list(arg) else: ret.append(arg) return ret
python
{ "resource": "" }
q260658
get_var
validation
def get_var(data, var_name, not_found=None): """Gets variable value from data dictionary.""" try: for key in str(var_name).split('.'): try: data = data[key] except TypeError: data = data[int(key)] except (KeyError, TypeError, ValueError): ...
python
{ "resource": "" }
q260659
missing
validation
def missing(data, *args): """Implements the missing operator for finding missing variables.""" not_found = object() if args and isinstance(args[0], list): args = args[0] ret = [] for arg in args: if get_var(data, arg, not_found) is not_found: ret.append(arg) return re...
python
{ "resource": "" }
q260660
missing_some
validation
def missing_some(data, min_required, args): """Implements the missing_some operator for finding missing variables.""" if min_required < 1: return [] found = 0 not_found = object() ret = [] for arg in args: if get_var(data, arg, not_found) is not_found: ret.append(arg)...
python
{ "resource": "" }
q260661
jsonLogic
validation
def jsonLogic(tests, data=None): """Executes the json-logic with given data.""" # You've recursed to a primitive, stop! if tests is None or not isinstance(tests, dict): return tests data = data or {} operator = list(tests.keys())[0] values = tests[operator] # Easy syntax for unary...
python
{ "resource": "" }
q260662
PyIndenterMode.indent
validation
def indent(self): """ Performs an indentation """ if not self.tab_always_indent: super(PyIndenterMode, self).indent() else: cursor = self.editor.textCursor() assert isinstance(cursor, QtGui.QTextCursor) if cursor.hasSelection(): ...
python
{ "resource": "" }
q260663
PyIndenterMode.unindent
validation
def unindent(self): """ Performs an un-indentation """ if self.tab_always_indent: cursor = self.editor.textCursor() if not cursor.hasSelection(): cursor.select(cursor.LineUnderCursor) self.unindent_selection(cursor) else: ...
python
{ "resource": "" }
q260664
PyAutoIndentMode._handle_indent_between_paren
validation
def _handle_indent_between_paren(self, column, line, parent_impl, tc): """ Handle indent between symbols such as parenthesis, braces,... """ pre, post = parent_impl next_char = self._get_next_char(tc) prev_char = self._get_prev_char(tc) prev_open = prev_char in ['...
python
{ "resource": "" }
q260665
PyAutoIndentMode._at_block_start
validation
def _at_block_start(tc, line): """ Improve QTextCursor.atBlockStart to ignore spaces """ if tc.atBlockStart(): return True column = tc.columnNumber() indentation = len(line) - len(line.lstrip()) return column <= indentation
python
{ "resource": "" }
q260666
PyConsole.update_terminal_colors
validation
def update_terminal_colors(self): """ Update terminal color scheme based on the pygments color scheme colors """ self.color_scheme = self.create_color_scheme( background=self.syntax_highlighter.color_scheme.background, foreground=self.syntax_highlighter.color_sche...
python
{ "resource": "" }
q260667
PyInteractiveConsole.mouseMoveEvent
validation
def mouseMoveEvent(self, e): """ Extends mouseMoveEvent to display a pointing hand cursor when the mouse cursor is over a file location """ super(PyInteractiveConsole, self).mouseMoveEvent(e) cursor = self.cursorForPosition(e.pos()) assert isinstance(cursor, QtGui...
python
{ "resource": "" }
q260668
PyInteractiveConsole.mousePressEvent
validation
def mousePressEvent(self, e): """ Emits open_file_requested if the press event occured over a file location string. """ super(PyInteractiveConsole, self).mousePressEvent(e) cursor = self.cursorForPosition(e.pos()) p = cursor.positionInBlock() usd = cursor...
python
{ "resource": "" }
q260669
MainWindow.setup_actions
validation
def setup_actions(self): """ Connects slots to signals """ self.actionOpen.triggered.connect(self.on_open) self.actionNew.triggered.connect(self.on_new) self.actionSave.triggered.connect(self.on_save) self.actionSave_as.triggered.connect(self.on_save_as) self.actionQuit.t...
python
{ "resource": "" }
q260670
MainWindow.setup_editor
validation
def setup_editor(self, editor): """ Setup the python editor, run the server and connect a few signals. :param editor: editor to setup. """ editor.cursorPositionChanged.connect(self.on_cursor_pos_changed) try: m = editor.modes.get(modes.GoToAssignmentsMode) ...
python
{ "resource": "" }
q260671
MainWindow.open_file
validation
def open_file(self, path, line=None): """ Creates a new GenericCodeEdit, opens the requested file and adds it to the tab widget. :param path: Path of the file to open :return The opened editor if open succeeded. """ editor = None if path: int...
python
{ "resource": "" }
q260672
MainWindow.on_new
validation
def on_new(self): """ Add a new empty code editor to the tab widget """ interpreter, pyserver, args = self._get_backend_parameters() self.setup_editor(self.tabWidget.create_new_document( extension='.py', interpreter=interpreter, server_script=pyserver, arg...
python
{ "resource": "" }
q260673
MainWindow.on_open
validation
def on_open(self): """ Shows an open file dialog and open the file if the dialog was accepted. """ filename, filter = QtWidgets.QFileDialog.getOpenFileName(self, 'Open') if filename: self.open_file(filename) self.actionRun.setEnabled(True) sel...
python
{ "resource": "" }
q260674
MainWindow.on_save_as
validation
def on_save_as(self): """ Save the current editor document as. """ path = self.tabWidget.current_widget().file.path path = os.path.dirname(path) if path else '' filename, filter = QtWidgets.QFileDialog.getSaveFileName( self, 'Save', path) if filename: ...
python
{ "resource": "" }
q260675
MainWindow.setup_mnu_style
validation
def setup_mnu_style(self, editor): """ setup the style menu for an editor tab """ menu = QtWidgets.QMenu('Styles', self.menuEdit) group = QtWidgets.QActionGroup(self) self.styles_group = group current_style = editor.syntax_highlighter.color_scheme.name group.triggered.con...
python
{ "resource": "" }
q260676
MainWindow.on_current_tab_changed
validation
def on_current_tab_changed(self): """ Update action states when the current tab changed. """ self.menuEdit.clear() self.menuModes.clear() self.menuPanels.clear() editor = self.tabWidget.current_widget() self.menuEdit.setEnabled(editor is not None) ...
python
{ "resource": "" }
q260677
MainWindow.on_run
validation
def on_run(self): """ Run the current current script """ filename = self.tabWidget.current_widget().file.path wd = os.path.dirname(filename) args = Settings().get_run_config_for_file(filename) self.interactiveConsole.start_process( Settings().interpret...
python
{ "resource": "" }
q260678
MainWindow.on_goto_out_of_doc
validation
def on_goto_out_of_doc(self, assignment): """ Open the a new tab when goto goes out of the current document. :param assignment: Destination """ editor = self.open_file(assignment.module_path) if editor: TextHelper(editor).goto_line(assignment.line, assignment...
python
{ "resource": "" }
q260679
calltips
validation
def calltips(request_data): """ Worker that returns a list of calltips. A calltips is a tuple made of the following parts: - module_name: name of the module of the function invoked - call_name: name of the function that is being called - params: the list of parameter names. - index:...
python
{ "resource": "" }
q260680
goto_assignments
validation
def goto_assignments(request_data): """ Go to assignements worker. """ code = request_data['code'] line = request_data['line'] + 1 column = request_data['column'] path = request_data['path'] # encoding = request_data['encoding'] encoding = 'utf-8' script = jedi.Script(code, line,...
python
{ "resource": "" }
q260681
defined_names
validation
def defined_names(request_data): """ Returns the list of defined names for the document. """ global _old_definitions ret_val = [] path = request_data['path'] toplvl_definitions = jedi.names( request_data['code'], path, 'utf-8') for d in toplvl_definitions: definition = _e...
python
{ "resource": "" }
q260682
quick_doc
validation
def quick_doc(request_data): """ Worker that returns the documentation of the symbol under cursor. """ code = request_data['code'] line = request_data['line'] + 1 column = request_data['column'] path = request_data['path'] # encoding = 'utf-8' encoding = 'utf-8' script = jedi.Scr...
python
{ "resource": "" }
q260683
run_pep8
validation
def run_pep8(request_data): """ Worker that run the pep8 tool on the current editor text. :returns a list of tuples (msg, msg_type, line_number) """ import pycodestyle from pyqode.python.backend.pep8utils import CustomChecker WARNING = 1 code = request_data['code'] path = request_da...
python
{ "resource": "" }
q260684
icon_from_typename
validation
def icon_from_typename(name, icon_type): """ Returns the icon resource filename that corresponds to the given typename. :param name: name of the completion. Use to make the distinction between public and private completions (using the count of starting '_') :pram typename: the typename reported...
python
{ "resource": "" }
q260685
JediCompletionProvider.complete
validation
def complete(code, line, column, path, encoding, prefix): """ Completes python code using `jedi`_. :returns: a list of completion. """ ret_val = [] try: script = jedi.Script(code, line + 1, column, path, encoding) completions = script.completions(...
python
{ "resource": "" }
q260686
make_python_patterns
validation
def make_python_patterns(additional_keywords=[], additional_builtins=[]): """Strongly inspired from idlelib.ColorDelegator.make_pat""" kw = r"\b" + any("keyword", kwlist + additional_keywords) + r"\b" kw_namespace = r"\b" + any("namespace", kw_namespace_list) + r"\b" word_operators = r"\b" + any("operat...
python
{ "resource": "" }
q260687
GoToAssignmentsMode._check_word_cursor
validation
def _check_word_cursor(self, tc=None): """ Request a go to assignment. :param tc: Text cursor which contains the text that we must look for its assignment. Can be None to go to the text that is under the text cursor. :type tc: QtGui.QTextCursor ...
python
{ "resource": "" }
q260688
GoToAssignmentsMode._unique
validation
def _unique(self, seq): """ Not performant but works. """ # order preserving checked = [] for e in seq: present = False for c in checked: if str(c) == str(e): present = True break ...
python
{ "resource": "" }
q260689
read_bgen
validation
def read_bgen(filepath, metafile_filepath=None, samples_filepath=None, verbose=True): r""" Read a given BGEN file. Parameters ---------- filepath : str A bgen file path. metafile_filepath : str, optional If ``None``, it will try to read the ``filepath + ".metadata"`` file. If this i...
python
{ "resource": "" }
q260690
create_metafile
validation
def create_metafile(bgen_filepath, metafile_filepath, verbose=True): r"""Create variants metadata file. Variants metadata file helps speed up subsequent reads of the associated bgen file. Parameters ---------- bgen_filepath : str Bgen file path. metafile_file : str Metafile...
python
{ "resource": "" }
q260691
CheckLiteral.match
validation
def match(self, subsetLines, offsetOfSubset, fileName): """ Search through lines for match. Raise an Exception if fail to match If match is succesful return the position the match was found """ for (offset,l) in enumerate(subsetLines): column = l....
python
{ "resource": "" }
q260692
CheckNot.match
validation
def match(self, subsetLines, offsetOfSubset, fileName): """ Search through lines for match. Raise an Exception if a match """ for (offset,l) in enumerate(subsetLines): for t in self.regex: m = t.Regex.search(l) if m != None: ...
python
{ "resource": "" }
q260693
isA
validation
def isA(instance, typeList): """ Return true if ``instance`` is an instance of any the Directive types in ``typeList`` """ return any(map(lambda iType: isinstance(instance,iType), typeList))
python
{ "resource": "" }
q260694
_touch
validation
def _touch(fname, mode=0o666, dir_fd=None, **kwargs): """ Touch a file. Credits to <https://stackoverflow.com/a/1160227>. """ flags = os.O_CREAT | os.O_APPEND with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f: os.utime( f.fileno() if os.utime in os.suppo...
python
{ "resource": "" }
q260695
allele_frequency
validation
def allele_frequency(expec): r""" Compute allele frequency from its expectation. Parameters ---------- expec : array_like Allele expectations encoded as a samples-by-alleles matrix. Returns ------- :class:`numpy.ndarray` Allele frequencies encoded as a variants-by-alleles m...
python
{ "resource": "" }
q260696
compute_dosage
validation
def compute_dosage(expec, alt=None): r""" Compute dosage from allele expectation. Parameters ---------- expec : array_like Allele expectations encoded as a samples-by-alleles matrix. alt : array_like, optional Alternative allele index. If ``None``, the allele having the minor ...
python
{ "resource": "" }
q260697
allele_expectation
validation
def allele_expectation(bgen, variant_idx): r""" Allele expectation. Compute the expectation of each allele from the genotype probabilities. Parameters ---------- bgen : bgen_file Bgen file handler. variant_idx : int Variant index. Returns ------- :class:`numpy.ndar...
python
{ "resource": "" }
q260698
Windows.find_libname
validation
def find_libname(self, name): """Try to infer the correct library name.""" names = ["{}.lib", "lib{}.lib", "{}lib.lib"] names = [n.format(name) for n in names] dirs = self.get_library_dirs() for d in dirs: for n in names: if exists(join(d, n)): ...
python
{ "resource": "" }
q260699
SimilarityDistance.fit
validation
def fit(self, X, y=None): """Fit distance-based AD. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Returns ------- self : object ...
python
{ "resource": "" }