output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def _http_req_apply_default_headers(self, request_headers, content_type, body): """Set default values for common HTTP request headers :param dict request_headers: The HTTP request headers :param content_type: The mime-type used in the request/response ...
Create a Python 3 function to set default values for common HTTP request headers.
As a python code expert, you are capable of creating scripts from specifications.
Conditionally serialize the request body value if mime_type is set and it s serializable.
Can you generate a brief explanation for the following Python 3 code def _http_req_body_serialize(self, body, content_type): if not body or not isinstance(body, (dict, list)): return body content_type = headers.parse_content_type(content_type) if content_type == CONTENT_TYPE_JSON: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Return the User - Agent value to use in HTTP requests.
Given the following Python 3 function, write the documentation def _http_req_user_agent(self): # Tornado Request Handler try: return '{}/{}'.format( self.settings['service'], self.settings['version']) except (AttributeError, KeyError): pass # Reje...
As a Python code analyst, you investigate and solve complex coding mysteries
def _http_resp_rate_limited(response): """Extract the ``Retry-After`` header value if the request was rate limited and return a future to sleep for the specified duration. :param tornado.httpclient.HTTPResponse response: The response :rtype: tornado.concurrent.Future """ ...
Write a Python 3 function that can extract the Retry - After header value if the request was rate limited and return a future to sleep for the specified duration.
As a Python code analyst, you investigate and solve complex coding mysteries
Build the session object.
How would you explain what the following Python 3 function does def get_session(): # NOTE(msimonin): We provide only a basic support which focus # Chameleon cloud and its rc files if os.environ.get("OS_IDENTITY_API_VERSION") == "3": logging.info("Creating a v3 Keystone Session") auth = v3.Pa...
As a Python code composer, you craft elegant and concise scripts.
def check_glance(session, image_name): """Check that the base image is available. Fails if the base image isn't added. This means the image should be added manually. """ gclient = glance.Client(GLANCE_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) ...
Can you create a Python 3 function that checks that the base image is available.
As a python code expert, you are capable of creating scripts from specifications.
def check_flavors(session): """Build the flavors mapping returns the mappings id <-> flavor """ nclient = nova.Client(NOVA_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) flavors = nclient.flavors.list() to_id = dict(list(map(lambda n: [n.name, n.id...
Write a Python 3 script for building the flavors mapping returns the mappings id < = > flavor
As a Python code translator, you convert algorithms and pseudocode into Python.
Check the status of the network and create a dedicated network if needed
Can you generate the documentation for the following Python 3 function def check_network(session, configure_network, network, subnet, dns_nameservers=None, allocation_pool=None): """Check the network status for the deployment. If needed, it creates a dedicated : * private network /sub...
As a python code expert, you are capable of creating scripts from specifications.
def wait_for_servers(session, servers): """Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH connection to be ready. """ nclient = nova.Client(NOVA_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) while True: deployed = ...
Can you create a Python 3 function that waits for the servers to be ready.
As a python code expert, you are capable of creating scripts from specifications.
def check_servers(session, machines, extra_prefix="", force_deploy=False, key_name=None, image_id=None, flavors='m1.medium', network=None, ext_net=None, scheduler_hints=None): """Checks the servers status for the deployment. If needed, it creates new server...
Write a Python 3 script to check the status of the servers for the deployment.
As a Python code composer, you craft elegant and concise scripts.
Check if a server is in the current deployment
Can you generate the documentation for the following Python 3 function def is_in_current_deployment(server, extra_prefix=""): return re.match(r"^%s" % '-'.join([DEFAULT_PREFIX, extra_prefix]), server.name) is not None
As a Python code analyst, you investigate and solve complex coding mysteries
def allow_address_pairs(session, network, subnet): """Allow several interfaces to be added and accessed from the other machines. This is particularly useful when working with virtual ips. """ nclient = neutron.Client('2', session=session, region_name=os.environ['OS_REGION_N...
Write a Python 3 function that can allow several interfaces to be added and accessed from other machines.
As a Python code translator, you convert algorithms and pseudocode into Python.
def check_environment(provider_conf): """Check all ressources needed by Enos.""" session = get_session() image_id = check_glance(session, provider_conf.image) flavor_to_id, id_to_flavor = check_flavors(session) ext_net, network, subnet = check_network( session, provider_conf.configur...
Write a Python 3 function that can check all ressources needed by Enos.
As a python code expert, you are capable of creating scripts from specifications.
def claims_match(value, claimspec): """ Implements matching according to section 5.5.1 of http://openid.net/specs/openid-connect-core-1_0.html The lack of value is not checked here. Also the text doesn't prohibit having both 'value' and 'values'. :param value: single value :param claimspec:...
Write a Python 3 script for determining if a claimspec matches a single value.
As a Python code analyst, you investigate and solve complex coding mysteries
def collect_user_info(endpoint_context, session, userinfo_claims=None): """ Collect information about a user. This can happen in two cases, either when constructing an IdToken or when returning user info through the UserInfo endpoint :param session: Session information :param userinfo_claims: u...
Implement a function in Python 3 to collect user info from a session.
As a Python code analyst, you investigate and solve complex coding mysteries
Collect user info claims that are to be placed in the id token.
Can you tell what is the following Python 3 function doing def userinfo_in_id_token_claims(endpoint_context, session, def_itc=None): if def_itc: itc = def_itc else: itc = {} itc.update(id_token_claims(session)) if not itc: return None _claims = by_schema(endpoint_context.i...
You are a Python code architect, reviewing and designing scalable and efficient code
def value_matrix(self): """Converted rows of tabular data. Returns: |list| or |tuple|: Table rows. """ if self.__value_matrix: return self.__value_matrix self.__value_matrix = [ [value_dp.data for value_dp in value_dp_list] for value_dp_list...
Create a Python 3 function for returning |list| or |tuple| of rows of tabular data.
As a Python code composer, you craft elegant and concise scripts.
Returns the value DP matrix for the current entry.
Here you have a function in Python 3, explain what it does def value_dp_matrix(self): if self.__value_dp_matrix is None: self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix( to_value_matrix(self.headers, self.rows) ) return self.__value_dp_matrix
You are a Python code architect, reviewing and designing scalable and efficient code
def validate_rows(self): """ :raises ValueError: """ invalid_row_idx_list = [] for row_idx, row in enumerate(self.rows): if isinstance(row, (list, tuple)) and len(self.headers) != len(row): invalid_row_idx_list.append(row_idx) if isinsta...
Can you write a function in Python 3 where it validates that the rows of the table are valid.
As a Python code composer, you craft elegant and concise scripts.
def as_dict(self): """ :return: Table data as a |dict| instance. :rtype: dict :Sample Code: .. code:: python from tabledata import TableData TableData( "sample", ["a", "b"], [[1, 2]...
Implement a Python 3 function for returning the table data as a |dict| instance.
You are a Python code analyst, evaluating scripts for potential improvements.
Return the rows of the table.
Here you have a function in Python 3, explain what it does def as_tuple(self): Row = namedtuple("Row", self.headers) for value_dp_list in self.value_dp_matrix: if typepy.is_empty_sequence(value_dp_list): continue row = Row(*[value_dp.data for value_dp in value_...
You are a Python code generator, capable of creating scripts from specifications.
def as_dataframe(self): """ :return: Table data as a ``pandas.DataFrame`` instance. :rtype: pandas.DataFrame :Sample Code: .. code-block:: python from tabledata import TableData TableData( "sample", ["...
Write a Python 3 script for returning the value matrix as a pandas. DataFrame instance.
As a Python code composer, you craft elegant and concise scripts.
Initialize a TableData instance from a pandas. DataFrame instance.
Given the following Python 3 function, write the documentation def from_dataframe(dataframe, table_name=""): return TableData(table_name, list(dataframe.columns.values), dataframe.values.tolist())
As a Python code composer, you craft elegant and concise scripts.
def call_async(func): """Decorates a function to be called async on the loop thread""" @wraps(func) def wrapper(self, *args, **kw): """Wraps instance method to be called on loop thread""" def call(): """Calls function on loop thread""" try: func(self...
Can you implement a function in Python 3 that decorates a function to be called async on the loop thread
As a python code expert, you are capable of creating scripts from specifications.
Decorator to call a function on the loop thread.
Here you have a function in Python 3, explain what it does def call_sync(func): @wraps(func) def wrapper(self, *args, **kw): """Wraps instance method to be called on loop thread""" # Just return when already on the event thread if self.thread.ident == get_ident(): return fu...
You are a Python code generator, capable of creating scripts from specifications.
Thread routine that returns when the count of the items in the queue is reached.
Given the following Python 3 function, write the documentation def target(self): while self.event.wait(): self.event.clear() while True: with self.lock: if not self.count: break self.count -= 1 ...
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a new connection to the given room.
Explain what the following Python 3 code does def create_connection(self, room, ws_url, agent, cookies): urlparts = urlsplit(ws_url) req = Request("GET", ws_url) cookies = get_cookie_header(cookies, req) if cookies: headers = dict(Cookie=cookies) else: he...
You are a Python code generator, capable of creating scripts from specifications.
Sends a message to the specified protocol.
Given the following Python 3 function, write the documentation def __send_message(self, proto, payload): # pylint: disable=no-self-use """Sends a message""" try: if not isinstance(payload, bytes): payload = payload.encode("utf-8") if not proto.connected: ...
As a Python code composer, you craft elegant and concise scripts.
Closes a connection to the specified protocol.
Given the following Python 3 function, write the documentation def close(self, proto): # pylint: disable=no-self-use """Closes a connection""" try: proto.sendClose() except Exception as ex: logger.exception("Failed to send close") proto.reraise(ex)
As a Python code translator, you convert algorithms and pseudocode into Python.
Process queue for these listeners. Only the items with type that matches.
Given the following Python 3 function, write the documentation def process(self): with self.lock, self.enlock: queue = copy(self.queue) self.queue.clear() callbacks = copy(self.callbacks) with self.lock: rm_cb = False for ki, vi in queue.item...
You are a Python code analyst, evaluating scripts for potential improvements.
def add(self, callback_type, callback): """Add a new listener""" with self.lock: self.callbacks[callback_type].append(callback)
How would you implement a function in Python 3 that adds a new listener
You are a Python code architect, reviewing and designing scalable and efficient code
def enqueue(self, item_type, item): """Queue a new data item, make item iterable""" with self.enlock: self.queue[item_type].append(item)
Can you create a Python 3 function that queues a new data item, make item iterable
As a Python code translator, you convert algorithms and pseudocode into Python.
def extract_slitlet2d(self, image_2k2k): """Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : numpy array Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2) Returns ------- slitlet2d : numpy arra...
Implement a Python 3 function for extracting slitlet 2d image from image with original EMIR dimensions.
As a python code expert, you are capable of creating scripts from specifications.
Locate the locations of unknown arc lines in a 2d slitlet image.
Make a summary of the following Python 3 code def locate_unknown_arc_lines(self, slitlet2d, times_sigma_threshold=15, minimum_threshold=None, delta_x_max=30, delta_y_min=30, ...
You are a Python code analyst, evaluating scripts for potential improvements.
def xy_spectrail_arc_intersections(self, slitlet2d=None): """Compute intersection points of spectrum trails with arc lines. The member list_arc_lines is updated with new keyword:keyval values for each arc line. Parameters ---------- slitlet2d : numpy array S...
Implement a Python 3 function for computing the intersection points of spectrum trails with arc lines.
As a python code expert, you are capable of creating scripts from specifications.
def estimate_tt_to_rectify(self, order, slitlet2d=None): """Estimate the polynomial transformation to rectify the image. Parameters ---------- order : int Order of the polynomial transformation. slitlet2d : numpy array Slitlet image to be displayed with t...
Can you create a Python 3 function that estimates the polynomial transformation to rectify the image.
As a Python code analyst, you investigate and solve complex coding mysteries
Rectify a 2d slitlet image using computed transformation.
Given the following Python 3 function, write the documentation def rectify(self, slitlet2d, resampling, transformation, inverse=False): if resampling not in [1, 2]: raise ValueError("Unexpected resampling value=" + str(resampling)) if transformation not in [1, 2]: raise ValueEr...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function takes a rectified image and returns the median spectrum and line peaks from the image.
Can you generate the documentation for the following Python 3 function def median_spectrum_from_rectified_image(self, slitlet2d_rect, sigma_gaussian_filtering=0, nwinwidth_initial=5, nw...
You are a Python code generator, capable of creating scripts from specifications.
def clip_slices(r, region, scale=1): '''Intersect slices with a region.''' t = [] for ch in r: a1 = intersection(ch[0], region[0], scale=scale) if a1 is None: continue a2 = intersection(ch[1], region[1], scale=scale) if a2 is None: continue t....
How would you code a function in Python 3 to intersect slices with a region.
As a Python code analyst, you investigate and solve complex coding mysteries
Set metadata in FITS headers.
Here you have a function in Python 3, explain what it does def set_base_headers(self, hdr): hdr = super(JoinDitheredImagesRecipe, self).set_base_headers(hdr) hdr['IMGOBBL'] = 0 hdr['OBSMODE'] = 'DITHERED_IMAGE' return hdr
You are a Python code architect, reviewing and designing scalable and efficient code
Load common defaults data structures.
Here you have a function in Python 3, explain what it does def _load_defaults(inventory_path=None, roles=None, extra_vars=None, tags=None, basedir=False): """Load common defaults data structures. For factorization purpose.""" extra_vars = extra_vars or {} tags = tags or [] loade...
You are a Python code architect, reviewing and designing scalable and efficient code
Run a play. Args: pattern_hosts (str): pattern to describe ansible hosts to target. see https://docs.ansible.com/ansible/latest/intro_patterns.html play_source (dict): ansible task inventory_path (str): inventory to use extra_vars (dict): extra_vars to use on_err...
Here you have a function in Python 3, explain what it does def run_play(play_source, inventory_path=None, roles=None, extra_vars=None, on_error_continue=False): """Run a play. Args: pattern_hosts (str): pattern to describe ansible hosts to target. see https://docs.ansible.com/a...
You are a Python code analyst, evaluating scripts for potential improvements.
def run_command(pattern_hosts, command, inventory_path=None, roles=None, extra_vars=None, on_error_continue=False): """Run a shell command on some remote hosts. Args: pattern_hosts (str): pattern to describe ansible hosts to target. see https://docs.ansible.c...
Can you create a Python 3 function that runs a command on some remote hosts.
You are a Python code architect, reviewing and designing scalable and efficient code
def run_ansible(playbooks, inventory_path=None, roles=None, extra_vars=None, tags=None, on_error_continue=False, basedir='.'): """Run Ansible. Args: playbooks (list): list of paths to the playbooks to run inventory_path (str): path to the hosts file (inventory) extra_var (dict):...
Write a Python 3 function that can run Ansible. Args: playbooks (list): list of paths to the playbooks to run inventory_path (str): path to the hosts file (inventory) extra_var (dict): extra vars to pass tags (list): list of tags to run on_error_continue(bool): Don't throw any exception in case a host is unreachable or...
As a python code expert, you are capable of creating scripts from specifications.
This function returns a list of hosts that are connected to the given networks.
Can you tell what is the following Python 3 function doing def discover_networks(roles, networks, fake_interfaces=None, fake_networks=None): """Checks the network interfaces on the nodes. This enables to auto-discover the mapping interface name <-> network role. Beware, this has a side ...
As a python code expert, you are capable of creating scripts from specifications.
Generate an inventory file in the ini format.
How would you explain what the following Python 3 function does def generate_inventory(roles, networks, inventory_path, check_networks=False, fake_interfaces=None, fake_networks=None): """Generate an inventory file in the ini format. The inventory is generated using the ``roles`` in the ...
You are a Python code architect, reviewing and designing scalable and efficient code
def emulate_network(network_constraints, roles=None, inventory_path=None, extra_vars=None): """Emulate network links. Read ``network_constraints`` and apply ``tc`` rules on all the nodes. Constraints are applied between groups of machines. Theses ...
How would you code a function in Python 3 to emulate network links. Read ``network_constraints`` and apply ``tc`` rules on all the nodes. Constraints are applied between groups of machines. Theses groups are described in the ``network_constraints`` variable and must be found in the inventory file. The newtwork constrai...
You are a Python code analyst, evaluating scripts for potential improvements.
def validate_network(roles=None, inventory_path=None, output_dir=None, extra_vars=None): """Validate the network parameters (latency, bandwidth ...) Performs flent, ping tests to validate the constraints set by :py:func:`emulate_network`. Repor...
Write a Python 3 function that can validate the network parameters.
As a python code expert, you are capable of creating scripts from specifications.
Reset the network constraints.
Can you generate a brief explanation for the following Python 3 code def reset_network(roles, extra_vars=None): logger.debug('Reset the constraints') if not extra_vars: extra_vars = {} tmpdir = os.path.join(os.getcwd(), TMP_DIRNAME) _check_tmpdir(tmpdir) utils_playbook = os.path.join(ANSI...
As a Python code analyst, you investigate and solve complex coding mysteries
Wait for all the machines to be ssh - reachable
How would you explain what the following Python 3 function does def wait_ssh(roles, retries=100, interval=30): utils_playbook = os.path.join(ANSIBLE_DIR, 'utils.yml') options = {'enos_action': 'ping'} for i in range(0, retries): try: run_ansible([utils_playbook], ...
As a Python code analyst, you investigate and solve complex coding mysteries
Expand group names. Args: grp (string): group names to expand Returns: list of groups Examples: * grp[1-3] will be expanded to [grp1, grp2, grp3] * grp1 will be expanded to [grp1]
Given the following Python 3 function, write the documentation def expand_groups(grp): p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P<end>\d+)\]") m = p.match(grp) if m is not None: s = int(m.group('start')) e = int(m.group('end')) n = m.group('name') return list(map(lambd...
You are a Python code architect, reviewing and designing scalable and efficient code
Expand the description given the group names and patterns.
Given the following Python 3 function, write the documentation def _expand_description(desc): srcs = expand_groups(desc['src']) dsts = expand_groups(desc['dst']) descs = [] for src in srcs: for dst in dsts: local_desc = desc.copy() local_desc['src'] = src loca...
As a Python code analyst, you investigate and solve complex coding mysteries
Generate default symetric grp constraints.
Explain what the following Python 3 code does def _generate_default_grp_constraints(roles, network_constraints): default_delay = network_constraints.get('default_delay') default_rate = network_constraints.get('default_rate') default_loss = network_constraints.get('default_loss', 0) except_groups = netwo...
You are a Python code analyst, evaluating scripts for potential improvements.
Generate the user specified constraints
Here you have a function in Python 3, explain what it does def _generate_actual_grp_constraints(network_constraints): if 'constraints' not in network_constraints: return [] constraints = network_constraints['constraints'] actual = [] for desc in constraints: descs = _expand_description(...
You are a Python code generator, capable of creating scripts from specifications.
Merge the constraints avoiding duplicates Change constraints in place.
Explain what the following Python 3 code does def _merge_constraints(constraints, overrides): for o in overrides: i = 0 while i < len(constraints): c = constraints[i] if _same(o, c): constraints[i].update(o) break i = i + 1
As a Python code composer, you craft elegant and concise scripts.
Generate constraints at the group level and deal with symetric constraints.
Explain what the following Python 3 code does def _build_grp_constraints(roles, network_constraints): # generate defaults constraints constraints = _generate_default_grp_constraints(roles, network_constraints) # Updating the constraints if necessary if...
You are a Python code architect, reviewing and designing scalable and efficient code
def _build_ip_constraints(roles, ips, constraints): """Generate the constraints at the ip/device level. Those constraints are those used by ansible to enforce tc/netem rules. """ local_ips = copy.deepcopy(ips) for constraint in constraints: gsrc = constraint['src'] gdst = constraint[...
Write a Python 3 function for building the constraints at the ip level.
You are a Python code generator, capable of creating scripts from specifications.
Decorate each network with the corresponding nic name.
Make a summary of the following Python 3 code def _map_device_on_host_networks(provider_nets, devices): networks = copy.deepcopy(provider_nets) for network in networks: for device in devices: network.setdefault('device', None) ip_set = IPSet([network['cidr']]) if 'ipv...
As a Python code composer, you craft elegant and concise scripts.
def f_daterange(freq, tz='UTC', *args, **kwargs): """ Use ``dateutil.rrule`` to create a range of dates. The frequency must be a string in the following list: YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY or SECONDLY. See `dateutil rrule`_ documentation for more detail. .. _dateutil rrule: ...
Can you write a function in Python 3 where it returns a list of dates in a frequency range.
You are a Python code analyst, evaluating scripts for potential improvements.
def f_energy(ac_power, times): """ Calculate the total energy accumulated from AC power at the end of each timestep between the given times. :param ac_power: AC Power [W] :param times: times :type times: np.datetime64[s] :return: energy [W*h] and energy times """ dt = np.diff(times)...
Can you implement a function in Python 3 that calculates the total energy accumulated from the end of each timestep between the given times.
You are a Python code architect, reviewing and designing scalable and efficient code
Group items in a timeseries by frequency.
Can you generate a brief explanation for the following Python 3 code def groupby_freq(items, times, freq, wkst='SU'): timeseries = zip(times, items) # timeseries map of items # create a key lambda to group timeseries by if freq.upper() == 'DAILY': def key(ts_): return ts_[0].day elif freq.upper...
You are a Python code generator, capable of creating scripts from specifications.
def f_rollup(items, times, freq): """ Use :func:`groupby_freq` to rollup items :param items: items in timeseries :param times: times corresponding to items :param freq: One of the ``dateutil.rrule`` frequency constants :type freq: str """ rollup = [np.sum(item for __, item in ts) ...
Write a Python 3 script for using :func:`groupby_freq` to rollup items :param items: items in timeseries :param times: times corresponding to items :param freq: One of the ``dateutil.rrule`` frequency constants :type freq: str
You are a Python code generator, capable of creating scripts from specifications.
Method to update extra metadata fields with dict obtained through fileinfo
Can you tell what is the following Python 3 function doing def fileupdate(self, data): self.name = data["name"] add = self.__additional add["filetype"] = "other" for filetype in ("book", "image", "video", "audio", "archive"): if filetype in data: add["filetyp...
As a Python code translator, you convert algorithms and pseudocode into Python.
def thumbnail(self): """Returns the thumbnail's url for this image, audio, or video file. Returns empty string if the file has no thumbnail""" if self.filetype not in ("video", "image", "audio"): raise RuntimeError("Only video, audio and image files can have thumbnails") thu...
Write a Python 3 function that can return the thumbnail s url for this image audio or video file.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the duration in seconds of this audio or video file
Can you generate a brief explanation for the following Python 3 code def duration(self): if self.filetype not in ("video", "audio"): raise RuntimeError("Only videos and audio have durations") return self.info.get("length") or self.info.get("duration")
As a python code expert, you are capable of creating scripts from specifications.
Remove this file from the room
Given the following Python 3 function, write the documentation def delete(self): self.room.check_owner() self.conn.make_call("deleteFiles", [self.fid])
As a Python code composer, you craft elegant and concise scripts.
Change the group of the running process
Here you have a function in Python 3, explain what it does def set_gid(self): if self.group: gid = getgrnam(self.group).gr_gid try: os.setgid(gid) except Exception: message = ("Unable to switch ownership to {0}:{1}. " + ...
As a Python code composer, you craft elegant and concise scripts.
def set_uid(self): """Change the user of the running process""" if self.user: uid = getpwnam(self.user).pw_uid try: os.setuid(uid) except Exception: message = ('Unable to switch ownership to {0}:{1}. ' + 'Did ...
Write a Python 3 function for changing the user of the running process
As a Python code analyst, you investigate and solve complex coding mysteries
Setup logging to syslog using the
Can you tell what is the following Python 3 function doing def setup_logging(self): self.logger = logging.getLogger() if os.path.exists('/dev/log'): handler = SysLogHandler('/dev/log') else: handler = SysLogHandler() self.logger.addHandler(handler)
As a Python code analyst, you investigate and solve complex coding mysteries
def daemonize(self): """ Do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: ...
Write a Python 3 script for doing the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
As a python code expert, you are capable of creating scripts from specifications.
def status(self): """Determine the status of the daemon""" my_name = os.path.basename(sys.argv[0]) if self._already_running(): message = "{0} (pid {1}) is running...\n".format(my_name, self.pid) sys.stdout.write(message) return 0 sys.stdout.write("{0}...
Create a Python 3 function for determining the status of the daemon
You are a Python code generator, capable of creating scripts from specifications.
def fetch_resources(uri, rel): """ Retrieves embeddable resource from given ``uri``. For now only local resources (images, fonts) are supported. :param str uri: path or url to image or font resource :returns: path to local resource file. :rtype: str :raises: :exc:`~easy_pdf.exceptions.Unsu...
Write a Python 3 function that can retrieve embeddable resource from given uri.
As a Python code translator, you convert algorithms and pseudocode into Python.
Converts html content into PDF document.
Explain what the following Python 3 code does def html_to_pdf(content, encoding="utf-8", link_callback=fetch_resources, **kwargs): """ Converts html ``content`` into PDF document. :param unicode content: html content :returns: PDF content :rtype: :class:`bytes` :raises: :exc:`~e...
You are a Python code architect, reviewing and designing scalable and efficient code
Creates a response object with content.
Explain what the following Python 3 code does def make_response(content, filename=None, content_type="application/pdf"): response = HttpResponse(content, content_type=content_type) if filename is not None: response["Content-Disposition"] = "attachment; %s" % encode_filename(filename) return response
You are a Python code architect, reviewing and designing scalable and efficient code
def render_to_pdf(template, context, using=None, request=None, encoding="utf-8", **kwargs): """ Create PDF document from Django html template. :param str template: Path to Django template :param dict context: Template context :param using: Optional Django template engine :param request: Django ...
Can you implement a function in Python 3 that renders a Django html template and return a PDF document.
As a Python code analyst, you investigate and solve complex coding mysteries
def render_to_pdf_response(request, template, context, using=None, filename=None, encoding="utf-8", **kwargs): """ Renders a PDF response using given ``request``, ``template`` and ``context``. If ``filename`` param is specified then the response ``Content-Disposition`` header...
Create a Python 3 function to render a PDF response using given request template and context.
As a Python code analyst, you investigate and solve complex coding mysteries
Renders PDF document and prepares response.
Can you tell what is the following Python 3 function doing def get_pdf_response(self, context, **response_kwargs): return render_to_pdf_response( request=self.request, template=self.get_template_names(), context=context, using=self.template_engine, fil...
As a Python code translator, you convert algorithms and pseudocode into Python.
def compile_patterns_in_dictionary(dictionary): """ Replace all strings in dictionary with compiled version of themselves and return dictionary. """ for key, value in dictionary.items(): if isinstance(value, str): dictionary[key] = re.compile(value) elif isinstance(value,...
Create a Python 3 function to replace all strings in dictionary with compiled version of themselves and return dictionary.
You are a Python code generator, capable of creating scripts from specifications.
Parse file and return list of source text.
How would you explain what the following Python 3 function does def filter(self, source_file, encoding): # noqa A001 with codecs.open(source_file, 'r', encoding=encoding) as f: text = f.read() return [filters.SourceText(self._filter(text), source_file, encoding, 'context')]
As a Python code composer, you craft elegant and concise scripts.
Filter the text for context delimiter.
Can you generate the documentation for the following Python 3 function def _filter(self, text): if self.line_endings: text = self.norm_nl(text) new_text = [] index = 0 last = 0 end = len(text) while index < end: m = self.escapes.match(text, pos=i...
You are a Python code generator, capable of creating scripts from specifications.
def create_starttls_connection( loop, protocol_factory, host=None, port=None, *, sock=None, ssl_context_factory=None, use_starttls=False, local_addr=None, **kwargs): """ Create a connection which can later be upgraded to use TLS. ...
How would you code a function in Python 3 to create a new connection which can later be upgraded to use TLS.
You are a Python code generator, capable of creating scripts from specifications.
Clean up all resources and call the protocol connection lost method.
Can you generate the documentation for the following Python 3 function def _call_connection_lost_and_clean_up(self, exc): self._state = _State.CLOSED try: self._protocol.connection_lost(exc) finally: self._rawsock.close() if self._tls_conn is not None: ...
As a Python code composer, you craft elegant and concise scripts.
def abort(self): """ Immediately close the stream, without sending remaining buffers or performing a proper shutdown. """ if self._state == _State.CLOSED: self._invalid_state("abort() called") return self._force_close(None)
Create a Python 3 function to abort the current session.
You are a Python code analyst, evaluating scripts for potential improvements.
def close(self): """ Close the stream. This performs a proper stream shutdown, except if the stream is currently performing a TLS handshake. In that case, calling :meth:`close` is equivalent to calling :meth:`abort`. Otherwise, the transport waits until all buffers are transmitt...
Can you implement a function in Python 3 that closes the current session.
You are a Python code architect, reviewing and designing scalable and efficient code
def starttls(self, ssl_context=None, post_handshake_callback=None): """ Start a TLS stream on top of the socket. This is an invalid operation if the stream is not in RAW_OPEN state. If `ssl_context` is set, it overrides the `ssl_context` passed to the constructo...
Create a Python 3 function for starting a TLS stream on top of the socket.
You are a Python code generator, capable of creating scripts from specifications.
def write(self, data): """ Write data to the transport. This is an invalid operation if the stream is not writable, that is, if it is closed. During TLS negotiation, the data is buffered. """ if not isinstance(data, (bytes, bytearray, memoryview)): raise TypeE...
Write a Python 3 script to write data to the transport.
As a Python code translator, you convert algorithms and pseudocode into Python.
given an array of objects de - normalized into fields
Can you tell what is the following Python 3 function doing def explode(prefix: str): def _app(i, e=None): if i is not None: return {k: v for (k, v) in iter_fields(i)}, None return i, e def iter_fields(event_field: Union[dict, list]): if type(event_field) is dict: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _has_xml_encode(self, content): """Check XML encoding.""" encode = None m = RE_XML_START.match(content) if m: if m.group(1): m2 = RE_XML_ENCODE.match(m.group(1)) if m2: enc = m2.group(2).decode('ascii') ...
Implement a Python 3 function for checking if the content contains XML encoding.
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if tag is an element we should break on.
Here you have a function in Python 3, explain what it does def is_break_tag(self, el): name = el.name return name in self.break_tags or name in self.user_break_tags
You are a Python code analyst, evaluating scripts for potential improvements.
def store_blocks(self, el, blocks, text, force_root): """Store the text as desired.""" if force_root or el.parent is None or self.is_break_tag(el): content = ''.join(text) if content: blocks.append((content, self.construct_selector(el))) text = [] ...
Implement a Python 3 function for storing the text as desired.
As a python code expert, you are capable of creating scripts from specifications.
Construct an selector for context.
Given the following Python 3 function, write the documentation def construct_selector(self, el, attr=''): selector = deque() ancestor = el while ancestor and ancestor.parent: if ancestor is not el: selector.appendleft(ancestor.name) else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Extract text from tags and attributes.
Here you have a function in Python 3, explain what it does def to_text(self, tree, force_root=False): self.extract_tag_metadata(tree) text = [] attributes = [] comments = [] blocks = [] if not (self.ignores.match(tree) if self.ignores else None): # The root...
As a Python code composer, you craft elegant and concise scripts.
def _filter(self, text, context, encoding): """Filter the source text.""" content = [] blocks, attributes, comments = self.to_text(bs4.BeautifulSoup(text, self.parser)) if self.comments: for c, desc in comments: content.append(filters.SourceText(c, context + ...
Implement a function in Python 3 to filter the source text.
As a Python code analyst, you investigate and solve complex coding mysteries
def sfilter(self, source): """Filter.""" return self._filter(source.text, source.context, source.encoding)
Implement a Python 3 function for filtering the source text.
As a python code expert, you are capable of creating scripts from specifications.
Decorator for declaring a lazy import.
Can you generate the documentation for the following Python 3 function def lazy_import(func): try: f = sys._getframe(1) except Exception: # pragma: no cover namespace = None else: namespace = f.f_locals return _LazyImport(func.__name__, func, namespace)
You are a Python code generator, capable of creating scripts from specifications.
def csv_to_map(fields, delimiter=','): """ Convert csv to dict :param delimiter: :param fields: :return: """ def _csv_to_list(csv_input): """ Util function to overcome the use of files by in-memory io buffer :param csv_input: :return: """ io...
Write a Python 3 script to convert csv to dict
As a Python code translator, you convert algorithms and pseudocode into Python.
def map_to_csv(fields, delimiter=","): """ Convert dict to csv :param fields: :return: """ def _list_to_csv(l): """ Util function to overcome the use of files by in-memory io buffer :param l: :return: """ io_file = io.StringIO() writer =...
Can you create a Python 3 function that converts dict to csv
As a Python code composer, you craft elegant and concise scripts.
def xarrayfunc(func): """Make a function compatible with xarray.DataArray. This function is intended to be used as a decorator like:: >>> @dc.xarrayfunc >>> def func(array): ... # do something ... return newarray >>> >>> result = func(array) Args: ...
Write a Python 3 function that can make a function compatible with xarray. DataArray.
As a Python code translator, you convert algorithms and pseudocode into Python.
def chunk(*argnames, concatfunc=None): """Make a function compatible with multicore chunk processing. This function is intended to be used as a decorator like:: >>> @dc.chunk('array') >>> def func(array): ... # do something ... return newarray >>> >>> re...
Create a Python 3 function for making a function compatible with multicore chunk processing.
You are a Python code analyst, evaluating scripts for potential improvements.
Format seconds in a more human readable way. It supports units down to nanoseconds.
Explain what the following Python 3 code does def format_sec(s): prefixes = ["", "m", "u", "n"] unit = 0 while s < 1 and unit + 1 < len(prefixes): s *= 1000 unit += 1 return "{:.1f} {}s".format(s, prefixes[unit])
You are a Python code generator, capable of creating scripts from specifications.