code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def update(self, observable, handlers): """Toolbar ReaderObserver callback that is notified when readers are added or removed.""" addedreaders, removedreaders = handlers for reader in addedreaders: item = self.Append(str(reader)) self.SetClientData(item, reader) ...
Toolbar ReaderObserver callback that is notified when readers are added or removed.
Below is the the instruction that describes the task: ### Input: Toolbar ReaderObserver callback that is notified when readers are added or removed. ### Response: def update(self, observable, handlers): """Toolbar ReaderObserver callback that is notified when readers are added or removed.""...
def _build_rhs(p, q, deriv): """The right hand side of the equation system matrix""" b = [0 for _ in range(p+q+1)] b[deriv] = math.factorial(deriv) return np.array(b)
The right hand side of the equation system matrix
Below is the the instruction that describes the task: ### Input: The right hand side of the equation system matrix ### Response: def _build_rhs(p, q, deriv): """The right hand side of the equation system matrix""" b = [0 for _ in range(p+q+1)] b[deriv] = math.factorial(deriv) return np.array(b)
def import_surf_mesh(file_name): """ Generates a NURBS surface object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS surface :rtype: NURBS.Surface """ raw_content = read_file(file_name) raw_content = raw_content.split("\n") content = [] ...
Generates a NURBS surface object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS surface :rtype: NURBS.Surface
Below is the the instruction that describes the task: ### Input: Generates a NURBS surface object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS surface :rtype: NURBS.Surface ### Response: def import_surf_mesh(file_name): """ Generates a NURBS surface...
def attitude_quaternion_encode(self, time_boot_ms, q1, q2, q3, q4, rollspeed, pitchspeed, yawspeed): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rot...
The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0). time_boot_ms : Timestamp (milliseconds since system ...
Below is the the instruction that describes the task: ### Input: The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0). ...
def save(self, inplace=True): """ Saves all modification to the marker on the server. :param inplace Apply edits on the current instance or get a new one. :return: Marker instance. """ modified_data = self._modified_data() if bool(modified_data): extra...
Saves all modification to the marker on the server. :param inplace Apply edits on the current instance or get a new one. :return: Marker instance.
Below is the the instruction that describes the task: ### Input: Saves all modification to the marker on the server. :param inplace Apply edits on the current instance or get a new one. :return: Marker instance. ### Response: def save(self, inplace=True): """ Saves all modification ...
def load_data(self, sess, inputs, state_inputs): """Bulk loads the specified inputs into device memory. The shape of the inputs must conform to the shapes of the input placeholders this optimizer was constructed with. The data is split equally across all the devices. If the data is not...
Bulk loads the specified inputs into device memory. The shape of the inputs must conform to the shapes of the input placeholders this optimizer was constructed with. The data is split equally across all the devices. If the data is not evenly divisible by the batch size, excess data wil...
Below is the the instruction that describes the task: ### Input: Bulk loads the specified inputs into device memory. The shape of the inputs must conform to the shapes of the input placeholders this optimizer was constructed with. The data is split equally across all the devices. If the da...
def update_email_marketing_campaign(self, email_marketing_campaign, name, email_content, from_email, from_name, reply_to_email, subject, text_content, address, ...
Update a Constant Contact email marketing campaign. Returns the updated EmailMarketingCampaign object.
Below is the the instruction that describes the task: ### Input: Update a Constant Contact email marketing campaign. Returns the updated EmailMarketingCampaign object. ### Response: def update_email_marketing_campaign(self, email_marketing_campaign, name, email_conte...
def get_process_params(xmldoc, program, param, require_unique_program = True): """ Return a list of the values stored in the process_params table for params named param for the program(s) named program. The values are returned as Python native types, not as the strings appearing in the XML document. If require_u...
Return a list of the values stored in the process_params table for params named param for the program(s) named program. The values are returned as Python native types, not as the strings appearing in the XML document. If require_unique_program is True (default), then the document must contain exactly one program ...
Below is the the instruction that describes the task: ### Input: Return a list of the values stored in the process_params table for params named param for the program(s) named program. The values are returned as Python native types, not as the strings appearing in the XML document. If require_unique_program is...
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which t...
r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which the data exists for. Called ...
Below is the the instruction that describes the task: ### Input: r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods...
def many_psds(k=2,fs=1.0, b0=1.0, N=1024): """ compute average of many PSDs """ psd=[] for j in range(k): print j x = noise.white(N=2*4096,b0=b0,fs=fs) f, tmp = noise.numpy_psd(x,fs) if j==0: psd = tmp else: psd = psd + tmp return f, psd/k
compute average of many PSDs
Below is the the instruction that describes the task: ### Input: compute average of many PSDs ### Response: def many_psds(k=2,fs=1.0, b0=1.0, N=1024): """ compute average of many PSDs """ psd=[] for j in range(k): print j x = noise.white(N=2*4096,b0=b0,fs=fs) f, tmp = noise.nump...
def ping(self, timeout=12): """ Send a keep-alive request for the endpoint. Args: timeout (int): maximum amount of time for the endpoint to stay active """ self.conn("POST", "{0}/users/ME/endpoints/{1}/active".format(self.conn.msgsHost, self.id), au...
Send a keep-alive request for the endpoint. Args: timeout (int): maximum amount of time for the endpoint to stay active
Below is the the instruction that describes the task: ### Input: Send a keep-alive request for the endpoint. Args: timeout (int): maximum amount of time for the endpoint to stay active ### Response: def ping(self, timeout=12): """ Send a keep-alive request for the endpoint. ...
def jarFlags(target, source, env, for_signature): """If we have a manifest, make sure that the 'm' flag is specified.""" jarflags = env.subst('$JARFLAGS', target=target, source=source) for src in source: contents = src.get_text_contents() if contents[:16] == "Manifest-Version": ...
If we have a manifest, make sure that the 'm' flag is specified.
Below is the the instruction that describes the task: ### Input: If we have a manifest, make sure that the 'm' flag is specified. ### Response: def jarFlags(target, source, env, for_signature): """If we have a manifest, make sure that the 'm' flag is specified.""" jarflags = env.subst('$JARFLAGS', ...
def blend_html_colour_to_white(html_colour, alpha): """ :param html_colour: Colour string like FF552B or #334455 :param alpha: Alpha value :return: Html colour alpha blended onto white """ html_colour = html_colour.upper() has_hash = False if html_colour[0] == '#': has_hash = Tru...
:param html_colour: Colour string like FF552B or #334455 :param alpha: Alpha value :return: Html colour alpha blended onto white
Below is the the instruction that describes the task: ### Input: :param html_colour: Colour string like FF552B or #334455 :param alpha: Alpha value :return: Html colour alpha blended onto white ### Response: def blend_html_colour_to_white(html_colour, alpha): """ :param html_colour: Colour string l...
def make_github_markdown_writer(opts): """ Creates a Writer object used for parsing and writing Markdown files with a GitHub style anchor transformation opts is a namespace object containing runtime options. It should generally include the following attributes: * 'open': a string correspondi...
Creates a Writer object used for parsing and writing Markdown files with a GitHub style anchor transformation opts is a namespace object containing runtime options. It should generally include the following attributes: * 'open': a string corresponding to the opening portion of the wrapper ...
Below is the the instruction that describes the task: ### Input: Creates a Writer object used for parsing and writing Markdown files with a GitHub style anchor transformation opts is a namespace object containing runtime options. It should generally include the following attributes: * 'open': a ...
def gen_chunks(self, gen): """Generates byte chunks of a given size. Takes a bytes generator and yields chunks of a maximum of ``chunk_size`` bytes. Parameters ---------- gen : generator The bytes generator that produces the bytes """ for dat...
Generates byte chunks of a given size. Takes a bytes generator and yields chunks of a maximum of ``chunk_size`` bytes. Parameters ---------- gen : generator The bytes generator that produces the bytes
Below is the the instruction that describes the task: ### Input: Generates byte chunks of a given size. Takes a bytes generator and yields chunks of a maximum of ``chunk_size`` bytes. Parameters ---------- gen : generator The bytes generator that produces the by...
def _load_market_scheme(self): ''' Load market yaml description ''' try: self.scheme = yaml.load(open(self.scheme_path, 'r')) except Exception, error: raise LoadMarketSchemeFailed(reason=error)
Load market yaml description
Below is the the instruction that describes the task: ### Input: Load market yaml description ### Response: def _load_market_scheme(self): ''' Load market yaml description ''' try: self.scheme = yaml.load(open(self.scheme_path, 'r')) except Exception, error: raise Lo...
def __capture(self, checkout_id, **kwargs): """Call documentation: `/checkout/capture <https://www.wepay.com/developer/reference/checkout#capture>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``...
Call documentation: `/checkout/capture <https://www.wepay.com/developer/reference/checkout#capture>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` p...
Below is the the instruction that describes the task: ### Input: Call documentation: `/checkout/capture <https://www.wepay.com/developer/reference/checkout#capture>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_to...
def make_list(var, num_terms=1): """ Make a variable a list if it is not already If variable is not a list it will make it a list of the correct length with all terms identical. """ if not isinstance(var, list): if isinstance(var, tuple): var = list(var) else: ...
Make a variable a list if it is not already If variable is not a list it will make it a list of the correct length with all terms identical.
Below is the the instruction that describes the task: ### Input: Make a variable a list if it is not already If variable is not a list it will make it a list of the correct length with all terms identical. ### Response: def make_list(var, num_terms=1): """ Make a variable a list if it is not already ...
def section_menu( context, show_section_root=True, show_multiple_levels=True, apply_active_classes=True, allow_repeating_parents=True, max_levels=settings.DEFAULT_SECTION_MENU_MAX_LEVELS, template='', sub_menu_template='', sub_menu_templates=None, use_specific=settings.DEFAULT_SECTION_MENU_USE_SPECI...
Render a section menu for the current section.
Below is the the instruction that describes the task: ### Input: Render a section menu for the current section. ### Response: def section_menu( context, show_section_root=True, show_multiple_levels=True, apply_active_classes=True, allow_repeating_parents=True, max_levels=settings.DEFAULT_SECTION_MENU_M...
def export_yaml(obj, file_name): """ Exports curves and surfaces in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input sha...
Exports curves and surfaces in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :para...
Below is the the instruction that describes the task: ### Input: Exports curves and surfaces in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>...
def p_single_statement_systemcall(self, p): 'single_statement : systemcall SEMICOLON' p[0] = SingleStatement(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
single_statement : systemcall SEMICOLON
Below is the the instruction that describes the task: ### Input: single_statement : systemcall SEMICOLON ### Response: def p_single_statement_systemcall(self, p): 'single_statement : systemcall SEMICOLON' p[0] = SingleStatement(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def _set_vlan_add(self, v, load=False): """ Setter method for vlan_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/vlan/vlan_add (container) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_add is considered as a private method. Back...
Setter method for vlan_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/vlan/vlan_add (container) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_add is considered as a private method. Backends looking to populate this variable should do...
Below is the the instruction that describes the task: ### Input: Setter method for vlan_add, mapped from YANG variable /routing_system/evpn_config/evpn/evpn_instance/vlan/vlan_add (container) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_add is considered as a private...
def collect_results(project, force=False): """collect_results.""" if not project.crawlable: return project now = datetime.datetime.now() if (now - project.updated_at).total_seconds() < 4 and (not force): return project result_paths = [] if os.path.isdir(project.path_name): ...
collect_results.
Below is the the instruction that describes the task: ### Input: collect_results. ### Response: def collect_results(project, force=False): """collect_results.""" if not project.crawlable: return project now = datetime.datetime.now() if (now - project.updated_at).total_seconds() < 4 and (n...
def ref(function, callback=None): """ Returns a weak reference to the given method or function. If the callback argument is not None, it is called as soon as the referenced function is garbage deleted. :type function: callable :param function: The function to reference. :type callback: ca...
Returns a weak reference to the given method or function. If the callback argument is not None, it is called as soon as the referenced function is garbage deleted. :type function: callable :param function: The function to reference. :type callback: callable :param callback: Called when the fu...
Below is the the instruction that describes the task: ### Input: Returns a weak reference to the given method or function. If the callback argument is not None, it is called as soon as the referenced function is garbage deleted. :type function: callable :param function: The function to reference. ...
def predict(self, data, output_margin=False, ntree_limit=0, pred_leaf=False): """ Predict with data. NOTE: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call...
Predict with data. NOTE: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call bst.copy() to make copies of model object and then call predict Parameters...
Below is the the instruction that describes the task: ### Input: Predict with data. NOTE: This function is not thread safe. For each booster object, predict can only be called from one thread. If you want to run prediction using multiple thread, call bst.copy() to make copies ...
def index(self): ''' Index all the keys added so far and make them searchable. ''' for i, hashtable in enumerate(self.hashtables): self.sorted_hashtables[i] = [H for H in hashtable.keys()] self.sorted_hashtables[i].sort()
Index all the keys added so far and make them searchable.
Below is the the instruction that describes the task: ### Input: Index all the keys added so far and make them searchable. ### Response: def index(self): ''' Index all the keys added so far and make them searchable. ''' for i, hashtable in enumerate(self.hashtables): sel...
def _get_task_from_task_dir(self, job_id, user_id, task_id, task_attempt): """Return a Task object with this task's info.""" # We need to be very careful about how we read and interpret the contents # of the task directory. The directory could be changing because a new # task is being created. The dire...
Return a Task object with this task's info.
Below is the the instruction that describes the task: ### Input: Return a Task object with this task's info. ### Response: def _get_task_from_task_dir(self, job_id, user_id, task_id, task_attempt): """Return a Task object with this task's info.""" # We need to be very careful about how we read and interpr...
def buses_of_vlvl(network, voltage_level): """ Get bus-ids of given voltage level(s). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA voltage_level: list Returns ------- list List containing bus-ids. """ mask = network.buses.v_n...
Get bus-ids of given voltage level(s). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA voltage_level: list Returns ------- list List containing bus-ids.
Below is the the instruction that describes the task: ### Input: Get bus-ids of given voltage level(s). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA voltage_level: list Returns ------- list List containing bus-ids. ### Response: def ...
def adjust_brightness_contrast(image, brightness=0., contrast=0.): """ Adjust the brightness and/or contrast of an image :param image: OpenCV BGR image :param contrast: Float, contrast adjustment with 0 meaning no change :param brightness: Float, brightness adjustment with 0 meaning no change "...
Adjust the brightness and/or contrast of an image :param image: OpenCV BGR image :param contrast: Float, contrast adjustment with 0 meaning no change :param brightness: Float, brightness adjustment with 0 meaning no change
Below is the the instruction that describes the task: ### Input: Adjust the brightness and/or contrast of an image :param image: OpenCV BGR image :param contrast: Float, contrast adjustment with 0 meaning no change :param brightness: Float, brightness adjustment with 0 meaning no change ### Response: ...
def get_package_status(owner, repo, identifier): """Get the status for a package in a repository.""" client = get_packages_api() with catch_raise_api_exception(): data, _, headers = client.packages_status_with_http_info( owner=owner, repo=repo, identifier=identifier ) ratel...
Get the status for a package in a repository.
Below is the the instruction that describes the task: ### Input: Get the status for a package in a repository. ### Response: def get_package_status(owner, repo, identifier): """Get the status for a package in a repository.""" client = get_packages_api() with catch_raise_api_exception(): data, ...
def __read_and_render_yaml_file(source, template, saltenv): ''' Read a yaml file and, if needed, renders that using the specifieds templating. Returns the python objects defined inside of the file. ''' sfn = __salt__['cp.cache_file'](so...
Read a yaml file and, if needed, renders that using the specifieds templating. Returns the python objects defined inside of the file.
Below is the the instruction that describes the task: ### Input: Read a yaml file and, if needed, renders that using the specifieds templating. Returns the python objects defined inside of the file. ### Response: def __read_and_render_yaml_file(source, template, ...
def _get_valid_endpoint(resp, name, entry_type): """ Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog """ catalog =...
Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog
Below is the the instruction that describes the task: ### Input: Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog ### Response: def _get_valid...
def signal_alias_exists(alias: str) -> bool: """ Checks if signal alias exists. :param alias: Signal alias. :return: """ if SignalDispatcher.signals.get(alias): return True return False
Checks if signal alias exists. :param alias: Signal alias. :return:
Below is the the instruction that describes the task: ### Input: Checks if signal alias exists. :param alias: Signal alias. :return: ### Response: def signal_alias_exists(alias: str) -> bool: """ Checks if signal alias exists. :param alias: Signal alias. :return: ...
def hdfpath_to_nifti1image(file_path, h5path): """Returns a nibabel Nifti1Image from a HDF5 group datasets Parameters ---------- file_path: string HDF5 file path h5path: HDF5 group path in file_path Returns ------- nibabel Nifti1Image """ with h5py.File(fil...
Returns a nibabel Nifti1Image from a HDF5 group datasets Parameters ---------- file_path: string HDF5 file path h5path: HDF5 group path in file_path Returns ------- nibabel Nifti1Image
Below is the the instruction that describes the task: ### Input: Returns a nibabel Nifti1Image from a HDF5 group datasets Parameters ---------- file_path: string HDF5 file path h5path: HDF5 group path in file_path Returns ------- nibabel Nifti1Image ### Response: ...
def main(inputstructs, inputpdbids): """Main function. Calls functions for processing, report generation and visualization.""" pdbid, pdbpath = None, None # #@todo For multiprocessing, implement better stacktracing for errors # Print title and version title = "* Protein-Ligand Interaction Profiler v...
Main function. Calls functions for processing, report generation and visualization.
Below is the the instruction that describes the task: ### Input: Main function. Calls functions for processing, report generation and visualization. ### Response: def main(inputstructs, inputpdbids): """Main function. Calls functions for processing, report generation and visualization.""" pdbid, pdbpath = ...
def get_jenkins_job_urls( rosdistro_name, jenkins_url, release_build_name, targets): """ Get the Jenkins job urls for each target. The placeholder {pkg} needs to be replaced with the ROS package name. :return: a dict indexed by targets containing a string """ urls = {} for target i...
Get the Jenkins job urls for each target. The placeholder {pkg} needs to be replaced with the ROS package name. :return: a dict indexed by targets containing a string
Below is the the instruction that describes the task: ### Input: Get the Jenkins job urls for each target. The placeholder {pkg} needs to be replaced with the ROS package name. :return: a dict indexed by targets containing a string ### Response: def get_jenkins_job_urls( rosdistro_name, jenkins_u...
def count_id(w0): """ 0 -> no terms idd 1 -> most term idd are shared in root morphem 2 -> most term idd are shared in flexing morphem 3 -> most term idd are shared root <-> flexing (crossed) :param w0: :param w1: :return: """ def f(w1): count = [set(w0.root).intersectio...
0 -> no terms idd 1 -> most term idd are shared in root morphem 2 -> most term idd are shared in flexing morphem 3 -> most term idd are shared root <-> flexing (crossed) :param w0: :param w1: :return:
Below is the the instruction that describes the task: ### Input: 0 -> no terms idd 1 -> most term idd are shared in root morphem 2 -> most term idd are shared in flexing morphem 3 -> most term idd are shared root <-> flexing (crossed) :param w0: :param w1: :return: ### Response: def count_i...
def voicing_measures(ref_voicing, est_voicing): """Compute the voicing recall and false alarm rates given two voicing indicator sequences, one as reference (truth) and the other as the estimate (prediction). The sequences must be of the same length. Examples -------- >>> ref_time, ref_freq = m...
Compute the voicing recall and false alarm rates given two voicing indicator sequences, one as reference (truth) and the other as the estimate (prediction). The sequences must be of the same length. Examples -------- >>> ref_time, ref_freq = mir_eval.io.load_time_series('ref.txt') >>> est_time...
Below is the the instruction that describes the task: ### Input: Compute the voicing recall and false alarm rates given two voicing indicator sequences, one as reference (truth) and the other as the estimate (prediction). The sequences must be of the same length. Examples -------- >>> ref_time...
def find_or_create_by_name(self, item_name, items_list, item_type): """ See if item with item_name exists in item_list. If not, create that item. Either way, return an item of type item_type. """ item = self.find_by_name(item_name, items_list) if not item: ...
See if item with item_name exists in item_list. If not, create that item. Either way, return an item of type item_type.
Below is the the instruction that describes the task: ### Input: See if item with item_name exists in item_list. If not, create that item. Either way, return an item of type item_type. ### Response: def find_or_create_by_name(self, item_name, items_list, item_type): """ See if item ...
def _readintbe(self, length, start): """Read bits and interpret as a big-endian signed int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readint(length, start)
Read bits and interpret as a big-endian signed int.
Below is the the instruction that describes the task: ### Input: Read bits and interpret as a big-endian signed int. ### Response: def _readintbe(self, length, start): """Read bits and interpret as a big-endian signed int.""" if length % 8: raise InterpretError("Big-endian integers must...
def create_nio(self, node, nio_settings): """ Creates a new NIO. :param node: Dynamips node instance :param nio_settings: information to create the NIO :returns: a NIO object """ nio = None if nio_settings["type"] == "nio_udp": lport = nio_s...
Creates a new NIO. :param node: Dynamips node instance :param nio_settings: information to create the NIO :returns: a NIO object
Below is the the instruction that describes the task: ### Input: Creates a new NIO. :param node: Dynamips node instance :param nio_settings: information to create the NIO :returns: a NIO object ### Response: def create_nio(self, node, nio_settings): """ Creates a new NIO. ...
def from_content(cls, content): """Parses a Tibia.com response into a House object. Parameters ---------- content: :class:`str` HTML content of the page. Returns ------- :class:`House` The house contained in the page, or None if the house...
Parses a Tibia.com response into a House object. Parameters ---------- content: :class:`str` HTML content of the page. Returns ------- :class:`House` The house contained in the page, or None if the house doesn't exist. Raises ---...
Below is the the instruction that describes the task: ### Input: Parses a Tibia.com response into a House object. Parameters ---------- content: :class:`str` HTML content of the page. Returns ------- :class:`House` The house contained in the ...
def path(self, target, args, kw): """Build a URL path fragment for a resource or route. Possible values for `target`: A string that does not start with a '.' and does not contain ':'. : Looks up the route of the same name on this mapper and returns it's path. A s...
Build a URL path fragment for a resource or route. Possible values for `target`: A string that does not start with a '.' and does not contain ':'. : Looks up the route of the same name on this mapper and returns it's path. A string of the form 'a:b', 'a:b:c', etc. ...
Below is the the instruction that describes the task: ### Input: Build a URL path fragment for a resource or route. Possible values for `target`: A string that does not start with a '.' and does not contain ':'. : Looks up the route of the same name on this mapper and returns it's ...
def __we_c(cls, calib, tc, temp, we_v): """ Compute weC from sensor temperature compensation of weV """ offset_v = calib.pid_elc_mv / 1000.0 response_v = we_v - offset_v # remove electronic zero response_c = tc.correct(temp, response_v) # correct the res...
Compute weC from sensor temperature compensation of weV
Below is the the instruction that describes the task: ### Input: Compute weC from sensor temperature compensation of weV ### Response: def __we_c(cls, calib, tc, temp, we_v): """ Compute weC from sensor temperature compensation of weV """ offset_v = calib.pid_elc_mv / 1000.0 ...
def middle(self): """ Returns the middle point of the bounding box :return: middle point :rtype: (float, float) """ return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2
Returns the middle point of the bounding box :return: middle point :rtype: (float, float)
Below is the the instruction that describes the task: ### Input: Returns the middle point of the bounding box :return: middle point :rtype: (float, float) ### Response: def middle(self): """ Returns the middle point of the bounding box :return: middle point :rtype: (float,...
def add_ip(self,oid,value,label=None): """Short helper to add an IP address value to the MIB subtree.""" self.add_oid_entry(oid,'IPADDRESS',value,label=label)
Short helper to add an IP address value to the MIB subtree.
Below is the the instruction that describes the task: ### Input: Short helper to add an IP address value to the MIB subtree. ### Response: def add_ip(self,oid,value,label=None): """Short helper to add an IP address value to the MIB subtree.""" self.add_oid_entry(oid,'IPADDRESS',value,label=label)
def __validate_and_fix_spark_args(spark_args): """ Prepares spark arguments. In the command-line script, they are passed as for example `-s master=local[4] deploy-mode=client verbose`, which would be passed to spark-submit as `--master local[4] --deploy-mode client --verbose` Parameters -------...
Prepares spark arguments. In the command-line script, they are passed as for example `-s master=local[4] deploy-mode=client verbose`, which would be passed to spark-submit as `--master local[4] --deploy-mode client --verbose` Parameters ---------- spark_args (List): List of spark arguments Ret...
Below is the the instruction that describes the task: ### Input: Prepares spark arguments. In the command-line script, they are passed as for example `-s master=local[4] deploy-mode=client verbose`, which would be passed to spark-submit as `--master local[4] --deploy-mode client --verbose` Parameters ...
def match_agent_id(self, agent_id, match): """Matches the agent identified by the given ``Id``. arg: agent_id (osid.id.Id): the Id of the ``Agent`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgument - ``agent_id`...
Matches the agent identified by the given ``Id``. arg: agent_id (osid.id.Id): the Id of the ``Agent`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgument - ``agent_id`` is ``null`` *compliance: mandatory -- This m...
Below is the the instruction that describes the task: ### Input: Matches the agent identified by the given ``Id``. arg: agent_id (osid.id.Id): the Id of the ``Agent`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgumen...
def checktype_seq(self, seq, kind, *, unique=False, **kargs): """Raise TypeError if seq is not a sequence of elements satisfying kind. Optionally require elements to be unique. As a special case, a string is considered to be an atomic value rather than a sequence of single-chara...
Raise TypeError if seq is not a sequence of elements satisfying kind. Optionally require elements to be unique. As a special case, a string is considered to be an atomic value rather than a sequence of single-character strings. (Thus, checktype_seq('foo', str) will fail.)
Below is the the instruction that describes the task: ### Input: Raise TypeError if seq is not a sequence of elements satisfying kind. Optionally require elements to be unique. As a special case, a string is considered to be an atomic value rather than a sequence of single-character...
def transform_data(from_client, from_project, from_logstore, from_time, to_time=None, to_client=None, to_project=None, to_logstore=None, shard_list=None, config=None, batch_size=None, compress=None, cg_name...
transform data from one logstore to another one (could be the same or in different region), the time is log received time on server side.
Below is the the instruction that describes the task: ### Input: transform data from one logstore to another one (could be the same or in different region), the time is log received time on server side. ### Response: def transform_data(from_client, from_project, from_logstore, from_time, to_time...
def find_video_by_id(self, video_id): """doc: http://open.youku.com/docs/doc?id=44 """ url = 'https://openapi.youku.com/v2/videos/show_basic.json' params = { 'client_id': self.client_id, 'video_id': video_id } r = requests.get(url, params=params) ...
doc: http://open.youku.com/docs/doc?id=44
Below is the the instruction that describes the task: ### Input: doc: http://open.youku.com/docs/doc?id=44 ### Response: def find_video_by_id(self, video_id): """doc: http://open.youku.com/docs/doc?id=44 """ url = 'https://openapi.youku.com/v2/videos/show_basic.json' params = { ...
def backward_committor(T, A, B): r"""Backward committor between given sets. The backward committor u(x) between sets A and B is the probability for the chain starting in x to have come from A last rather than from B. Parameters ---------- T : (M, M) ndarray Transition matrix A ...
r"""Backward committor between given sets. The backward committor u(x) between sets A and B is the probability for the chain starting in x to have come from A last rather than from B. Parameters ---------- T : (M, M) ndarray Transition matrix A : array_like List of integer ...
Below is the the instruction that describes the task: ### Input: r"""Backward committor between given sets. The backward committor u(x) between sets A and B is the probability for the chain starting in x to have come from A last rather than from B. Parameters ---------- T : (M, M) ndarray ...
def get_raw_access_token(self, request_token, request_token_secret, method='GET', **kwargs): ''' Returns a Requests' response over the :attr:`rauth.OAuth1Service.access_token_url`....
Returns a Requests' response over the :attr:`rauth.OAuth1Service.access_token_url`. Use this if your endpoint if you need the full `Response` object. :param request_token: The request token as returned by :meth:`get_request_token`. :type request_token: str :param re...
Below is the the instruction that describes the task: ### Input: Returns a Requests' response over the :attr:`rauth.OAuth1Service.access_token_url`. Use this if your endpoint if you need the full `Response` object. :param request_token: The request token as returned by :meth:`g...
def places_nearby(client, location=None, radius=None, keyword=None, language=None, min_price=None, max_price=None, name=None, open_now=False, rank_by=None, type=None, page_token=None): """ Performs nearby search for places. :param location: The latitude/longitude value f...
Performs nearby search for places. :param location: The latitude/longitude value for which you wish to obtain the closest, human-readable address. :type location: string, dict, list, or tuple :param radius: Distance in meters within which to bias results. :type radius: int :p...
Below is the the instruction that describes the task: ### Input: Performs nearby search for places. :param location: The latitude/longitude value for which you wish to obtain the closest, human-readable address. :type location: string, dict, list, or tuple :param radius: Distance ...
def upload(self, stop_at=None): """ Perform file upload. Performs continous upload of chunks of the file. The size uploaded at each cycle is the value of the attribute 'chunk_size'. :Args: - stop_at (Optional[int]): Determines at what offset value th...
Perform file upload. Performs continous upload of chunks of the file. The size uploaded at each cycle is the value of the attribute 'chunk_size'. :Args: - stop_at (Optional[int]): Determines at what offset value the upload should stop. If not specified this ...
Below is the the instruction that describes the task: ### Input: Perform file upload. Performs continous upload of chunks of the file. The size uploaded at each cycle is the value of the attribute 'chunk_size'. :Args: - stop_at (Optional[int]): Determines at wha...
def writeDB(filename, catalog, meta=None): """ Output an sqlite3 database containing one table for each source type Parameters ---------- filename : str Output filename catalog : list List of sources of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools....
Output an sqlite3 database containing one table for each source type Parameters ---------- filename : str Output filename catalog : list List of sources of type :class:`AegeanTools.models.OutputSource`, :class:`AegeanTools.models.SimpleSource`, or :class:`AegeanTools.models.Isl...
Below is the the instruction that describes the task: ### Input: Output an sqlite3 database containing one table for each source type Parameters ---------- filename : str Output filename catalog : list List of sources of type :class:`AegeanTools.models.OutputSource`, :class...
def refine_get_urls(original): """ serve static files (and media files also) in production the webserver should serve requested static files itself and never let requests to /static/* and /media/* get to the django application. """ def get_urls(): from django.conf.urls import url ...
serve static files (and media files also) in production the webserver should serve requested static files itself and never let requests to /static/* and /media/* get to the django application.
Below is the the instruction that describes the task: ### Input: serve static files (and media files also) in production the webserver should serve requested static files itself and never let requests to /static/* and /media/* get to the django application. ### Response: def refine_get_urls(original):...
def handle_new_tuple_set_2(self, hts2): """Called when new HeronTupleSet2 arrives Convert(Assemble) HeronTupleSet2(raw byte array) to HeronTupleSet See more at GitHub PR #1421 :param tuple_msg_set: HeronTupleSet2 type """ if self.my_pplan_helper is None or self.my_instance is None: L...
Called when new HeronTupleSet2 arrives Convert(Assemble) HeronTupleSet2(raw byte array) to HeronTupleSet See more at GitHub PR #1421 :param tuple_msg_set: HeronTupleSet2 type
Below is the the instruction that describes the task: ### Input: Called when new HeronTupleSet2 arrives Convert(Assemble) HeronTupleSet2(raw byte array) to HeronTupleSet See more at GitHub PR #1421 :param tuple_msg_set: HeronTupleSet2 type ### Response: def handle_new_tuple_set_2(self, hts2): ...
def set_inputhook(self, callback): """Set PyOS_InputHook to callback and return the previous one.""" # On platforms with 'readline' support, it's all too likely to # have a KeyboardInterrupt signal delivered *even before* an # initial ``try:`` clause in the callback can be executed, so ...
Set PyOS_InputHook to callback and return the previous one.
Below is the the instruction that describes the task: ### Input: Set PyOS_InputHook to callback and return the previous one. ### Response: def set_inputhook(self, callback): """Set PyOS_InputHook to callback and return the previous one.""" # On platforms with 'readline' support, it's all too likely...
def _load_builtins(self): """ Fill the Registry with the hard coded key bindings. """ pymux = self.pymux kb = KeyBindings() # Create filters. has_prefix = HasPrefix(pymux) waits_for_confirmation = WaitsForConfirmation(pymux) prompt_or_command_focu...
Fill the Registry with the hard coded key bindings.
Below is the the instruction that describes the task: ### Input: Fill the Registry with the hard coded key bindings. ### Response: def _load_builtins(self): """ Fill the Registry with the hard coded key bindings. """ pymux = self.pymux kb = KeyBindings() # Create fi...
def normalize_list_of_dicts(value, default_key, default_value=UNDEFINED): """ Converts given value to a list of dictionaries as follows: * ``[{...}]`` → ``[{...}]`` * ``{...}`` → ``[{...}]`` * ``'xyz'`` → ``[{default_key: 'xyz'}]`` * ``None`` → ``[{default_key: default_value}]`` (if spe...
Converts given value to a list of dictionaries as follows: * ``[{...}]`` → ``[{...}]`` * ``{...}`` → ``[{...}]`` * ``'xyz'`` → ``[{default_key: 'xyz'}]`` * ``None`` → ``[{default_key: default_value}]`` (if specified) * ``None`` → ``[]`` :param default_value: only Unicode, i....
Below is the the instruction that describes the task: ### Input: Converts given value to a list of dictionaries as follows: * ``[{...}]`` → ``[{...}]`` * ``{...}`` → ``[{...}]`` * ``'xyz'`` → ``[{default_key: 'xyz'}]`` * ``None`` → ``[{default_key: default_value}]`` (if specified) * ``N...
def mtz2tw(n,c,e,l): """mtz: model for the traveling salesman problem with time windows (based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints) Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) - e[i]: earliest date for visiting ...
mtz: model for the traveling salesman problem with time windows (based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints) Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) - e[i]: earliest date for visiting node i - l[i]: lates...
Below is the the instruction that describes the task: ### Input: mtz: model for the traveling salesman problem with time windows (based on Miller-Tucker-Zemlin's one-index potential formulation, stronger constraints) Parameters: - n: number of nodes - c[i,j]: cost for traversing arc (i,j) ...
def create_error(msg, cause=None): """Creates a ``GaxError`` or subclass. Attributes: msg (string): describes the error that occurred. cause (Exception, optional): the exception raised by a lower layer of the RPC stack (for example, gRPC) that caused this exception, or N...
Creates a ``GaxError`` or subclass. Attributes: msg (string): describes the error that occurred. cause (Exception, optional): the exception raised by a lower layer of the RPC stack (for example, gRPC) that caused this exception, or None if this exception originated in GAX. ...
Below is the the instruction that describes the task: ### Input: Creates a ``GaxError`` or subclass. Attributes: msg (string): describes the error that occurred. cause (Exception, optional): the exception raised by a lower layer of the RPC stack (for example, gRPC) that caused this ...
def bin2hex(fin, fout, offset=0): """Simple bin-to-hex convertor. @return 0 if all OK @param fin input bin file (filename or file-like object) @param fout output hex file (filename or file-like object) @param offset starting address offset for loading bin """ h = IntelHex()...
Simple bin-to-hex convertor. @return 0 if all OK @param fin input bin file (filename or file-like object) @param fout output hex file (filename or file-like object) @param offset starting address offset for loading bin
Below is the the instruction that describes the task: ### Input: Simple bin-to-hex convertor. @return 0 if all OK @param fin input bin file (filename or file-like object) @param fout output hex file (filename or file-like object) @param offset starting address offset for loading bi...
def track_progress(**context): """Print training progress. Called after each epoch.""" model = context["model"] train_X = context["train_X"] dev_X = context["dev_X"] dev_y = context["dev_y"] n_train = len(train_X) trainer = context["trainer"] def each_epoch(): global epoch_train...
Print training progress. Called after each epoch.
Below is the the instruction that describes the task: ### Input: Print training progress. Called after each epoch. ### Response: def track_progress(**context): """Print training progress. Called after each epoch.""" model = context["model"] train_X = context["train_X"] dev_X = context["dev_X"] ...
def annotate(title, format_type, message=None, data=None, metric=1.0): """ Annotate a test case with info that should be displayed in the reports. Parameters ---------- title : str A human-readable descriptive title of the test case. format_type : str A string that determines ho...
Annotate a test case with info that should be displayed in the reports. Parameters ---------- title : str A human-readable descriptive title of the test case. format_type : str A string that determines how the result data is formatted in the report. It is expected not to be None...
Below is the the instruction that describes the task: ### Input: Annotate a test case with info that should be displayed in the reports. Parameters ---------- title : str A human-readable descriptive title of the test case. format_type : str A string that determines how the result d...
def haversine(lon1, lat1, lon2, lat2, earth_radius=6357000): """Calculate the great circle distance between two points on earth in Kilometers on the earth (specified in decimal degrees) .. seealso:: :func:`distance_points` :param float lon1: longitude of first place (decimal degrees) :param float ...
Calculate the great circle distance between two points on earth in Kilometers on the earth (specified in decimal degrees) .. seealso:: :func:`distance_points` :param float lon1: longitude of first place (decimal degrees) :param float lat1: latitude of first place (decimal degrees) :param float lon...
Below is the the instruction that describes the task: ### Input: Calculate the great circle distance between two points on earth in Kilometers on the earth (specified in decimal degrees) .. seealso:: :func:`distance_points` :param float lon1: longitude of first place (decimal degrees) :param float...
def list_user_threads_view(request, targetUsername): ''' View of threads a user has created. ''' targetUser = get_object_or_404(User, username=targetUsername) targetProfile = get_object_or_404(UserProfile, user=targetUser) threads = Thread.objects.filter(owner=targetProfile) page_name = "{0}'s Threa...
View of threads a user has created.
Below is the the instruction that describes the task: ### Input: View of threads a user has created. ### Response: def list_user_threads_view(request, targetUsername): ''' View of threads a user has created. ''' targetUser = get_object_or_404(User, username=targetUsername) targetProfile = get_object_or...
def beam(problem, beam_size=100, iterations_limit=0, viewer=None): ''' Beam search. beam_size is the size of the beam. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Req...
Beam search. beam_size is the size of the beam. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: SearchProblem.actions, SearchProblem.result, SearchProblem.value, an...
Below is the the instruction that describes the task: ### Input: Beam search. beam_size is the size of the beam. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: Sea...
def get_epochs_given_midtimes_and_period( t_mid, period, err_t_mid=None, t0_fixed=None, t0_percentile=None, verbose=False ): '''This calculates the future epochs for a transit, given a period and a starting epoch The equation used is:: t_mid = period...
This calculates the future epochs for a transit, given a period and a starting epoch The equation used is:: t_mid = period*epoch + t0 Default behavior if no kwargs are used is to define `t0` as the median finite time of the passed `t_mid` array. Only one of `err_t_mid` or `t0_fixed` shou...
Below is the the instruction that describes the task: ### Input: This calculates the future epochs for a transit, given a period and a starting epoch The equation used is:: t_mid = period*epoch + t0 Default behavior if no kwargs are used is to define `t0` as the median finite time of the ...
def build_html(path_jinja2, template_name, path_outfile, template_kwargs=None): '''Helper function for building an html from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex...
Helper function for building an html from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex template :param path_outfile: the full path to the desired final output file ...
Below is the the instruction that describes the task: ### Input: Helper function for building an html from a latex jinja2 template :param path_jinja2: the root directory for latex jinja2 templates :param template_name: the relative path, to path_jinja2, to the desired jinja2 Latex template :par...
def run(command, raw_output=False): """Run a command using subprocess. :param command: command line to be run :type command: str :param raw_output: does not attempt to convert the output as unicode :type raw_output: bool :return: error code, output (``stdout``) and error (``stderr``) :rtype...
Run a command using subprocess. :param command: command line to be run :type command: str :param raw_output: does not attempt to convert the output as unicode :type raw_output: bool :return: error code, output (``stdout``) and error (``stderr``) :rtype: tuple
Below is the the instruction that describes the task: ### Input: Run a command using subprocess. :param command: command line to be run :type command: str :param raw_output: does not attempt to convert the output as unicode :type raw_output: bool :return: error code, output (``stdout``) and err...
def _cont_norm_running_quantile_regions(wl, fluxes, ivars, q, delta_lambda, ranges, verbose=True): """ Perform continuum normalization using running quantile, for spectrum that comes in chunks """ print("contnorm.py: continuum norm using running quantile") pri...
Perform continuum normalization using running quantile, for spectrum that comes in chunks
Below is the the instruction that describes the task: ### Input: Perform continuum normalization using running quantile, for spectrum that comes in chunks ### Response: def _cont_norm_running_quantile_regions(wl, fluxes, ivars, q, delta_lambda, ranges, verbose=True): ...
def convert_nexus_to_format(dataset_as_nexus, dataset_format): """ Converts nexus format to Phylip and Fasta using Biopython tools. :param dataset_as_nexus: :param dataset_format: :return: """ fake_handle = StringIO(dataset_as_nexus) nexus_al = AlignIO.parse(fake_handle, 'nexus') tm...
Converts nexus format to Phylip and Fasta using Biopython tools. :param dataset_as_nexus: :param dataset_format: :return:
Below is the the instruction that describes the task: ### Input: Converts nexus format to Phylip and Fasta using Biopython tools. :param dataset_as_nexus: :param dataset_format: :return: ### Response: def convert_nexus_to_format(dataset_as_nexus, dataset_format): """ Converts nexus format to P...
def p_statement_draw_attr(p): """ statement : DRAW attr_list expr COMMA expr """ p[0] = make_sentence('DRAW', make_typecast(TYPE.integer, p[3], p.lineno(4)), make_typecast(TYPE.integer, p[5], p.lineno(4)), p[2])
statement : DRAW attr_list expr COMMA expr
Below is the the instruction that describes the task: ### Input: statement : DRAW attr_list expr COMMA expr ### Response: def p_statement_draw_attr(p): """ statement : DRAW attr_list expr COMMA expr """ p[0] = make_sentence('DRAW', make_typecast(TYPE.integer, p[3], p.lineno(4))...
def content_edge_check(self, url): """Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server.""" prefixes = ["http://", "https://"] for prefix in prefixes: if url.startswith(prefix): url = url[len(prefix):] break content = self._fetch("/content/edge_check/%s" %...
Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server.
Below is the the instruction that describes the task: ### Input: Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server. ### Response: def content_edge_check(self, url): """Retrieve headers and MD5 hash of the content for a particular url from each Fastly edge server.""" ...
def _compute_key(self, id, nbytes): "id is 'A' - 'F' for the various keys used by ssh" m = Message() m.add_mpint(self.K) m.add_bytes(self.H) m.add_byte(id) m.add_bytes(self.session_id) out = sofar = SHA.new(str(m)).digest() while len(out) < nbytes: ...
id is 'A' - 'F' for the various keys used by ssh
Below is the the instruction that describes the task: ### Input: id is 'A' - 'F' for the various keys used by ssh ### Response: def _compute_key(self, id, nbytes): "id is 'A' - 'F' for the various keys used by ssh" m = Message() m.add_mpint(self.K) m.add_bytes(self.H) m.add_...
def make_datastore_query(self, cursor=None): """Returns a datastore.Query that generates all namespaces in the range. Args: cursor: start cursor for the query. Returns: A datastore.Query instance that generates db.Keys for each namespace in the NamespaceRange. """ filters = {} ...
Returns a datastore.Query that generates all namespaces in the range. Args: cursor: start cursor for the query. Returns: A datastore.Query instance that generates db.Keys for each namespace in the NamespaceRange.
Below is the the instruction that describes the task: ### Input: Returns a datastore.Query that generates all namespaces in the range. Args: cursor: start cursor for the query. Returns: A datastore.Query instance that generates db.Keys for each namespace in the NamespaceRange. ### Respon...
def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (self._observed_errors - 1)) return min(self.BACKOFF_MAX, backoff_value)
Formula for computing the current backoff :rtype: float
Below is the the instruction that describes the task: ### Input: Formula for computing the current backoff :rtype: float ### Response: def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ if self._observed_errors <= 1: ret...
def plot(self, numPoints=100): """ Specific plotting method for cylinders. """ fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # generate cylinder x = np.linspace(- self.radius, self.radius, numPoints) z = np.linspace(- self.height / 2., self.height / 2., numPoints) Xc...
Specific plotting method for cylinders.
Below is the the instruction that describes the task: ### Input: Specific plotting method for cylinders. ### Response: def plot(self, numPoints=100): """ Specific plotting method for cylinders. """ fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # generate cylinder x = np...
def run(self): """ this is the actual execution of the instrument thread: continuously read values from the probes """ eta = self.settings['noise_strength'] gamma = 2 * np.pi * self.settings['noise_bandwidth'] dt = 1. / self.settings['update frequency'] control =...
this is the actual execution of the instrument thread: continuously read values from the probes
Below is the the instruction that describes the task: ### Input: this is the actual execution of the instrument thread: continuously read values from the probes ### Response: def run(self): """ this is the actual execution of the instrument thread: continuously read values from the probes "...
def get_wigner(z, freq, sample_freq, histbins=200, show_plot=False): """ Calculates an approximation to the wigner quasi-probability distribution by splitting the z position array into slices of the length of one period of the motion. This slice is then associated with phase from -180 to 180 degrees...
Calculates an approximation to the wigner quasi-probability distribution by splitting the z position array into slices of the length of one period of the motion. This slice is then associated with phase from -180 to 180 degrees. These slices are then histogramed in order to get a distribution of counts ...
Below is the the instruction that describes the task: ### Input: Calculates an approximation to the wigner quasi-probability distribution by splitting the z position array into slices of the length of one period of the motion. This slice is then associated with phase from -180 to 180 degrees. These slic...
def set_event(self, ref, tk_event, callback): """ Sets a callback for this widget against a ref (reference) for a tk_event, setting the callback to None will remove it. """ # has an EventCallback been created for this tk event if tk_event not in self._event_callbacks: ...
Sets a callback for this widget against a ref (reference) for a tk_event, setting the callback to None will remove it.
Below is the the instruction that describes the task: ### Input: Sets a callback for this widget against a ref (reference) for a tk_event, setting the callback to None will remove it. ### Response: def set_event(self, ref, tk_event, callback): """ Sets a callback for this widget against a r...
def exists(self, path): """ Does provided path exist on S3? """ (bucket, key) = self._path_to_bucket_and_key(path) # root always exists if self._is_root(key): return True # file if self._exists(bucket, key): return True i...
Does provided path exist on S3?
Below is the the instruction that describes the task: ### Input: Does provided path exist on S3? ### Response: def exists(self, path): """ Does provided path exist on S3? """ (bucket, key) = self._path_to_bucket_and_key(path) # root always exists if self._is_root(ke...
def read_root_generation_progress(self): """Read the configuration and process of the current root generation attempt. Supported methods: GET: /sys/generate-root/attempt. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict """ ...
Read the configuration and process of the current root generation attempt. Supported methods: GET: /sys/generate-root/attempt. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict
Below is the the instruction that describes the task: ### Input: Read the configuration and process of the current root generation attempt. Supported methods: GET: /sys/generate-root/attempt. Produces: 200 application/json :return: The JSON response of the request. :rtype: dict...
def get_limits(self, limit_sum=None): """ Gets the current limit data if it is different from the data indicated by limit_sum. The db argument is used for hydrating the limit objects. Raises a NoChangeException if the limit_sum represents no change, otherwise returns a tuple ...
Gets the current limit data if it is different from the data indicated by limit_sum. The db argument is used for hydrating the limit objects. Raises a NoChangeException if the limit_sum represents no change, otherwise returns a tuple consisting of the current limit_sum and a list of Li...
Below is the the instruction that describes the task: ### Input: Gets the current limit data if it is different from the data indicated by limit_sum. The db argument is used for hydrating the limit objects. Raises a NoChangeException if the limit_sum represents no change, otherwise returns...
def ping(self): """Attempts to ping the server using current credentials, and responds with the path of the currently authenticated device""" return self.handleresult(self.r.get(self.url, params={"q": "this"})).text
Attempts to ping the server using current credentials, and responds with the path of the currently authenticated device
Below is the the instruction that describes the task: ### Input: Attempts to ping the server using current credentials, and responds with the path of the currently authenticated device ### Response: def ping(self): """Attempts to ping the server using current credentials, and responds with the path...
def get_config(self, name, default=_MISSING): """Get a configuration setting from this DeviceAdapter. See :meth:`AbstractDeviceAdapter.get_config`. """ val = self._config.get(name, default) if val is _MISSING: raise ArgumentError("DeviceAdapter config {} did not exi...
Get a configuration setting from this DeviceAdapter. See :meth:`AbstractDeviceAdapter.get_config`.
Below is the the instruction that describes the task: ### Input: Get a configuration setting from this DeviceAdapter. See :meth:`AbstractDeviceAdapter.get_config`. ### Response: def get_config(self, name, default=_MISSING): """Get a configuration setting from this DeviceAdapter. See :meth...
def simulate_w(self, index: int, half_turns: float, axis_half_turns: float): """Simulate a single qubit rotation gate about a X + b Y. The gate simulated is U = exp(-i pi/2 W half_turns) where W = cos(pi axis_half_turns) X + sin(pi ax...
Simulate a single qubit rotation gate about a X + b Y. The gate simulated is U = exp(-i pi/2 W half_turns) where W = cos(pi axis_half_turns) X + sin(pi axis_half_turns) Y Args: index: The qubit to act on. half_turns: The amount of the overall rotation, see the formula ...
Below is the the instruction that describes the task: ### Input: Simulate a single qubit rotation gate about a X + b Y. The gate simulated is U = exp(-i pi/2 W half_turns) where W = cos(pi axis_half_turns) X + sin(pi axis_half_turns) Y Args: index: The qubit to act on. ...
def _scope_vars(scope, trainable_only=False): """ Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were...
Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- v...
Below is the the instruction that describes the task: ### Input: Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variable...
def getFileHandle(self, dataFile, openMethod): """ Returns handle associated to the filename. If the file is already opened, update its priority in the cache and return its handle. Otherwise, open the file using openMethod, store it in the cache and return the corresponding handl...
Returns handle associated to the filename. If the file is already opened, update its priority in the cache and return its handle. Otherwise, open the file using openMethod, store it in the cache and return the corresponding handle.
Below is the the instruction that describes the task: ### Input: Returns handle associated to the filename. If the file is already opened, update its priority in the cache and return its handle. Otherwise, open the file using openMethod, store it in the cache and return the corresponding han...
def uniq(args): """ %prog uniq fastqfile Retain only first instance of duplicate reads. Duplicate is defined as having the same read name. """ p = OptionParser(uniq.__doc__) p.set_outfile() opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) ...
%prog uniq fastqfile Retain only first instance of duplicate reads. Duplicate is defined as having the same read name.
Below is the the instruction that describes the task: ### Input: %prog uniq fastqfile Retain only first instance of duplicate reads. Duplicate is defined as having the same read name. ### Response: def uniq(args): """ %prog uniq fastqfile Retain only first instance of duplicate reads. Duplica...
def expr2dimacscnf(ex): """Convert an expression into an equivalent DIMACS CNF.""" litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
Convert an expression into an equivalent DIMACS CNF.
Below is the the instruction that describes the task: ### Input: Convert an expression into an equivalent DIMACS CNF. ### Response: def expr2dimacscnf(ex): """Convert an expression into an equivalent DIMACS CNF.""" litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
def kl_setup(num_eig,sr,struct,prefixes, factors_file="kl_factors.dat",islog=True, basis_file=None, tpl_dir="."): """setup a karhuenen-Loeve based parameterization for a given geostatistical structure. Parameters ---------- num_eig : int number of basis vectors to ...
setup a karhuenen-Loeve based parameterization for a given geostatistical structure. Parameters ---------- num_eig : int number of basis vectors to retain in the reduced basis sr : flopy.reference.SpatialReference struct : str or pyemu.geostats.Geostruct geostatistical structur...
Below is the the instruction that describes the task: ### Input: setup a karhuenen-Loeve based parameterization for a given geostatistical structure. Parameters ---------- num_eig : int number of basis vectors to retain in the reduced basis sr : flopy.reference.SpatialReference str...
def get_review_sh(self, revision, item): """ Add sorting hat enrichment fields for the author of the revision """ identity = self.get_sh_identity(revision) update = parser.parse(item[self.get_field_date()]) erevision = self.get_item_sh_fields(identity, update) return erevision
Add sorting hat enrichment fields for the author of the revision
Below is the the instruction that describes the task: ### Input: Add sorting hat enrichment fields for the author of the revision ### Response: def get_review_sh(self, revision, item): """ Add sorting hat enrichment fields for the author of the revision """ identity = self.get_sh_identity(revision...
def adam_minimax(grad_both, init_params_max, init_params_min, callback=None, num_iters=100, step_size_max=0.001, step_size_min=0.001, b1=0.9, b2=0.999, eps=10**-8): """Adam modified to do minimiax optimization, for instance to help with training generative adversarial networks.""" x_max, unflatten...
Adam modified to do minimiax optimization, for instance to help with training generative adversarial networks.
Below is the the instruction that describes the task: ### Input: Adam modified to do minimiax optimization, for instance to help with training generative adversarial networks. ### Response: def adam_minimax(grad_both, init_params_max, init_params_min, callback=None, num_iters=100, step_size_max=0.001,...
def _get_supported_py_config(tops, extended_cfg): ''' Based on the Salt SSH configuration, create a YAML configuration for the supported Python interpreter versions. This is then written into the thin.tgz archive and then verified by salt.client.ssh.ssh_py_shim.get_executable() Note: Minimum defaul...
Based on the Salt SSH configuration, create a YAML configuration for the supported Python interpreter versions. This is then written into the thin.tgz archive and then verified by salt.client.ssh.ssh_py_shim.get_executable() Note: Minimum default of 2.x versions is 2.7 and 3.x is 3.0, unless specified in n...
Below is the the instruction that describes the task: ### Input: Based on the Salt SSH configuration, create a YAML configuration for the supported Python interpreter versions. This is then written into the thin.tgz archive and then verified by salt.client.ssh.ssh_py_shim.get_executable() Note: Minimum...
def _run_bunny(args): """Run CWL with rabix bunny. """ main_file, json_file, project_name = _get_main_and_json(args.directory) work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "bunny_work")) flags = ["-b", work_dir] log_file = os.path.join(work_dir, "%s-bunny.log" % project_name) if o...
Run CWL with rabix bunny.
Below is the the instruction that describes the task: ### Input: Run CWL with rabix bunny. ### Response: def _run_bunny(args): """Run CWL with rabix bunny. """ main_file, json_file, project_name = _get_main_and_json(args.directory) work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "bunny_work...
def cidr_netmask(cidr): ''' Get the netmask address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20 ''' ips = netaddr.IPNetwork(cidr) return six.text_type(ips.netmask)
Get the netmask address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20
Below is the the instruction that describes the task: ### Input: Get the netmask address associated with a CIDR address. CLI example:: salt myminion netaddress.cidr_netmask 192.168.0.0/20 ### Response: def cidr_netmask(cidr): ''' Get the netmask address associated with a CIDR address. CL...
def clustdealer(pairdealer, optim): """ return optim clusters given iterators, and whether it got all or not""" ccnt = 0 chunk = [] while ccnt < optim: ## try refreshing taker, else quit try: taker = itertools.takewhile(lambda x: x[0] != "//\n", pairdealer) oneclu...
return optim clusters given iterators, and whether it got all or not
Below is the the instruction that describes the task: ### Input: return optim clusters given iterators, and whether it got all or not ### Response: def clustdealer(pairdealer, optim): """ return optim clusters given iterators, and whether it got all or not""" ccnt = 0 chunk = [] while ccnt < optim:...