repo
stringlengths
7
55
path
stringlengths
4
223
url
stringlengths
87
315
code
stringlengths
75
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
avg_line_len
float64
7.91
980
blockstack/blockstack-core
blockstack/lib/nameset/db.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/lib/nameset/db.py#L2458-L2474
def namedb_get_num_names( cur, current_block, include_expired=False ): """ Get the number of names that exist at the current block """ unexpired_query = "" unexpired_args = () if not include_expired: # count all names, including expired ones unexpired_query, unexpired_args = namedb_select_where_unexpired_names( current_block ) unexpired_query = 'WHERE {}'.format(unexpired_query) query = "SELECT COUNT(name_records.name) FROM name_records JOIN namespaces ON name_records.namespace_id = namespaces.namespace_id " + unexpired_query + ";" args = unexpired_args num_rows = namedb_select_count_rows( cur, query, args, count_column='COUNT(name_records.name)' ) return num_rows
[ "def", "namedb_get_num_names", "(", "cur", ",", "current_block", ",", "include_expired", "=", "False", ")", ":", "unexpired_query", "=", "\"\"", "unexpired_args", "=", "(", ")", "if", "not", "include_expired", ":", "# count all names, including expired ones", "unexpir...
Get the number of names that exist at the current block
[ "Get", "the", "number", "of", "names", "that", "exist", "at", "the", "current", "block" ]
python
train
42.529412
SBRG/ssbio
ssbio/protein/structure/properties/residues.py
https://github.com/SBRG/ssbio/blob/e9449e64ffc1a1f5ad07e5849aa12a650095f8a2/ssbio/protein/structure/properties/residues.py#L391-L421
def hse_output(pdb_file, file_type): """ The solvent exposure of an amino acid residue is important for analyzing, understanding and predicting aspects of protein structure and function [73]. A residue's solvent exposure can be classified as four categories: exposed, partly exposed, buried and deeply buried residues. Hamelryck et al. [73] established a new 2D measure that provides a different view of solvent exposure, i.e. half-sphere exposure (HSE). By conceptually dividing the sphere of a residue into two halves- HSE-up and HSE-down, HSE provides a more detailed description of an amino acid residue's spatial neighborhood. HSE is calculated by the hsexpo module implemented in the BioPython package [74] from a PDB file. http://onlinelibrary.wiley.com/doi/10.1002/prot.20379/abstract Args: pdb_file: Returns: """ # Get the first model my_structure = StructureIO(pdb_file) model = my_structure.first_model # Calculate HSEalpha exp_ca = HSExposureCA(model) # Calculate HSEbeta exp_cb = HSExposureCB(model) # Calculate classical coordination number exp_fs = ExposureCN(model) return
[ "def", "hse_output", "(", "pdb_file", ",", "file_type", ")", ":", "# Get the first model", "my_structure", "=", "StructureIO", "(", "pdb_file", ")", "model", "=", "my_structure", ".", "first_model", "# Calculate HSEalpha", "exp_ca", "=", "HSExposureCA", "(", "model"...
The solvent exposure of an amino acid residue is important for analyzing, understanding and predicting aspects of protein structure and function [73]. A residue's solvent exposure can be classified as four categories: exposed, partly exposed, buried and deeply buried residues. Hamelryck et al. [73] established a new 2D measure that provides a different view of solvent exposure, i.e. half-sphere exposure (HSE). By conceptually dividing the sphere of a residue into two halves- HSE-up and HSE-down, HSE provides a more detailed description of an amino acid residue's spatial neighborhood. HSE is calculated by the hsexpo module implemented in the BioPython package [74] from a PDB file. http://onlinelibrary.wiley.com/doi/10.1002/prot.20379/abstract Args: pdb_file: Returns:
[ "The", "solvent", "exposure", "of", "an", "amino", "acid", "residue", "is", "important", "for", "analyzing", "understanding", "and", "predicting", "aspects", "of", "protein", "structure", "and", "function", "[", "73", "]", ".", "A", "residue", "s", "solvent", ...
python
train
37.580645
senaite/senaite.core
bika/lims/browser/widgets/serviceswidget.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/widgets/serviceswidget.py#L205-L210
def process_form(self, instance, field, form, empty_marker=None, emptyReturnsMarker=False, validating=True): """Return UIDs of the selected services """ service_uids = form.get("uids", []) return service_uids, {}
[ "def", "process_form", "(", "self", ",", "instance", ",", "field", ",", "form", ",", "empty_marker", "=", "None", ",", "emptyReturnsMarker", "=", "False", ",", "validating", "=", "True", ")", ":", "service_uids", "=", "form", ".", "get", "(", "\"uids\"", ...
Return UIDs of the selected services
[ "Return", "UIDs", "of", "the", "selected", "services" ]
python
train
43.333333
mryellow/maze_explorer
mazeexp/engine/score.py
https://github.com/mryellow/maze_explorer/blob/ab8a25ccd05105d2fe57e0213d690cfc07e45827/mazeexp/engine/score.py#L66-L75
def update(self, dt): """ Responsabilities: Updates game engine each tick Copies new stats into labels """ for key, value in self.labels.iteritems(): str_val = str(int(self.stats[key])) self.msgs[key][0].element.text = self.labels[key] + str_val self.msgs[key][1].element.text = self.labels[key] + str_val
[ "def", "update", "(", "self", ",", "dt", ")", ":", "for", "key", ",", "value", "in", "self", ".", "labels", ".", "iteritems", "(", ")", ":", "str_val", "=", "str", "(", "int", "(", "self", ".", "stats", "[", "key", "]", ")", ")", "self", ".", ...
Responsabilities: Updates game engine each tick Copies new stats into labels
[ "Responsabilities", ":", "Updates", "game", "engine", "each", "tick", "Copies", "new", "stats", "into", "labels" ]
python
train
38.8
epfl-lts2/pygsp
pygsp/graphs/graph.py
https://github.com/epfl-lts2/pygsp/blob/8ce5bde39206129287375af24fdbcd7edddca8c5/pygsp/graphs/graph.py#L798-L811
def lmax(self): r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`. """ if self._lmax is None: self.logger.warning('The largest eigenvalue G.lmax is not ' 'available, we need to estimate it. ' 'Explicitly call G.estimate_lmax() or ' 'G.compute_fourier_basis() ' 'once beforehand to suppress the warning.') self.estimate_lmax() return self._lmax
[ "def", "lmax", "(", "self", ")", ":", "if", "self", ".", "_lmax", "is", "None", ":", "self", ".", "logger", ".", "warning", "(", "'The largest eigenvalue G.lmax is not '", "'available, we need to estimate it. '", "'Explicitly call G.estimate_lmax() or '", "'G.compute_four...
r"""Largest eigenvalue of the graph Laplacian. Can be exactly computed by :func:`compute_fourier_basis` or approximated by :func:`estimate_lmax`.
[ "r", "Largest", "eigenvalue", "of", "the", "graph", "Laplacian", "." ]
python
train
44.714286
productml/blurr
blurr/core/store.py
https://github.com/productml/blurr/blob/1b688b2c4a9bbbb2139c58bf0682ddc05a6c24fa/blurr/core/store.py#L79-L89
def _get_range_dimension_key(self, base_key: Key, start_time: datetime, end_time: datetime, count: int = 0) -> List[Tuple[Key, Any]]: """ Returns the list of items from the store based on the given time range or count. This is used when the key being used is a DIMENSION key. """ raise NotImplementedError()
[ "def", "_get_range_dimension_key", "(", "self", ",", "base_key", ":", "Key", ",", "start_time", ":", "datetime", ",", "end_time", ":", "datetime", ",", "count", ":", "int", "=", "0", ")", "->", "List", "[", "Tuple", "[", "Key", ",", "Any", "]", "]", ...
Returns the list of items from the store based on the given time range or count. This is used when the key being used is a DIMENSION key.
[ "Returns", "the", "list", "of", "items", "from", "the", "store", "based", "on", "the", "given", "time", "range", "or", "count", "." ]
python
train
42.727273
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/well_known_types.py#L310-L313
def ToMicroseconds(self): """Converts a Duration to microseconds.""" micros = _RoundTowardZero(self.nanos, _NANOS_PER_MICROSECOND) return self.seconds * _MICROS_PER_SECOND + micros
[ "def", "ToMicroseconds", "(", "self", ")", ":", "micros", "=", "_RoundTowardZero", "(", "self", ".", "nanos", ",", "_NANOS_PER_MICROSECOND", ")", "return", "self", ".", "seconds", "*", "_MICROS_PER_SECOND", "+", "micros" ]
Converts a Duration to microseconds.
[ "Converts", "a", "Duration", "to", "microseconds", "." ]
python
train
47.25
disqus/nydus
nydus/contrib/ketama.py
https://github.com/disqus/nydus/blob/9b505840da47a34f758a830c3992fa5dcb7bb7ad/nydus/contrib/ketama.py#L95-L107
def remove_node(self, node): """ Removes node from circle and rebuild it. """ try: self._nodes.remove(node) del self._weights[node] except (KeyError, ValueError): pass self._hashring = dict() self._sorted_keys = [] self._build_circle()
[ "def", "remove_node", "(", "self", ",", "node", ")", ":", "try", ":", "self", ".", "_nodes", ".", "remove", "(", "node", ")", "del", "self", ".", "_weights", "[", "node", "]", "except", "(", "KeyError", ",", "ValueError", ")", ":", "pass", "self", ...
Removes node from circle and rebuild it.
[ "Removes", "node", "from", "circle", "and", "rebuild", "it", "." ]
python
train
25.230769
edeposit/marcxml2mods
src/marcxml2mods/xslt_transformer.py
https://github.com/edeposit/marcxml2mods/blob/7b44157e859b4d2a372f79598ddbf77e43d39812/src/marcxml2mods/xslt_transformer.py#L104-L127
def _read_marcxml(xml): """ Read MARC XML or OAI file, convert, add namespace and return XML in required format with all necessities. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. Returns: obj: Required XML parsed with ``lxml.etree``. """ # read file, if `xml` is valid file path marc_xml = _read_content_or_path(xml) # process input file - convert it from possible OAI to MARC XML and add # required XML namespaces marc_xml = _oai_to_xml(marc_xml) marc_xml = _add_namespace(marc_xml) file_obj = StringIO.StringIO(marc_xml) return ET.parse(file_obj)
[ "def", "_read_marcxml", "(", "xml", ")", ":", "# read file, if `xml` is valid file path", "marc_xml", "=", "_read_content_or_path", "(", "xml", ")", "# process input file - convert it from possible OAI to MARC XML and add", "# required XML namespaces", "marc_xml", "=", "_oai_to_xml...
Read MARC XML or OAI file, convert, add namespace and return XML in required format with all necessities. Args: xml (str): Filename or XML string. Don't use ``\\n`` in case of filename. Returns: obj: Required XML parsed with ``lxml.etree``.
[ "Read", "MARC", "XML", "or", "OAI", "file", "convert", "add", "namespace", "and", "return", "XML", "in", "required", "format", "with", "all", "necessities", "." ]
python
train
27.375
ska-sa/kittens
Kittens/utils.py
https://github.com/ska-sa/kittens/blob/92058e065ddffa5d00a44749145a6f917e0f31dc/Kittens/utils.py#L398-L404
def weakref_proxy(obj): """returns either a weakref.proxy for the object, or if object is already a proxy, returns itself.""" if type(obj) in weakref.ProxyTypes: return obj else: return weakref.proxy(obj)
[ "def", "weakref_proxy", "(", "obj", ")", ":", "if", "type", "(", "obj", ")", "in", "weakref", ".", "ProxyTypes", ":", "return", "obj", "else", ":", "return", "weakref", ".", "proxy", "(", "obj", ")" ]
returns either a weakref.proxy for the object, or if object is already a proxy, returns itself.
[ "returns", "either", "a", "weakref", ".", "proxy", "for", "the", "object", "or", "if", "object", "is", "already", "a", "proxy", "returns", "itself", "." ]
python
train
32.857143
juju-solutions/jujuresources
jujuresources/cli.py
https://github.com/juju-solutions/jujuresources/blob/7d2c5f50981784cc4b5cde216b930f6d59c951a4/jujuresources/cli.py#L107-L118
def fetch(opts): """ Create a local mirror of one or more resources. """ resources = _load(opts.resources, opts.output_dir) if opts.all: opts.resource_names = ALL reporthook = None if opts.quiet else lambda name: print('Fetching {}...'.format(name)) if opts.verbose: backend.VERBOSE = True _fetch(resources, opts.resource_names, opts.mirror_url, opts.force, reporthook) return verify(opts)
[ "def", "fetch", "(", "opts", ")", ":", "resources", "=", "_load", "(", "opts", ".", "resources", ",", "opts", ".", "output_dir", ")", "if", "opts", ".", "all", ":", "opts", ".", "resource_names", "=", "ALL", "reporthook", "=", "None", "if", "opts", "...
Create a local mirror of one or more resources.
[ "Create", "a", "local", "mirror", "of", "one", "or", "more", "resources", "." ]
python
train
35.833333
pauleveritt/kaybee
kaybee/plugins/events.py
https://github.com/pauleveritt/kaybee/blob/a00a718aaaa23b2d12db30dfacb6b2b6ec84459c/kaybee/plugins/events.py#L106-L112
def call_purge_doc(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docname: str): """ On env-purge-doc, do callbacks """ for callback in EventAction.get_callbacks(kb_app, SphinxEvent.EPD): callback(kb_app, sphinx_app, sphinx_env, docname)
[ "def", "call_purge_doc", "(", "cls", ",", "kb_app", ",", "sphinx_app", ":", "Sphinx", ",", "sphinx_env", ":", "BuildEnvironment", ",", "docname", ":", "str", ")", ":", "for", "callback", "in", "EventAction", ".", "get_callbacks", "(", "kb_app", ",", "SphinxE...
On env-purge-doc, do callbacks
[ "On", "env", "-", "purge", "-", "doc", "do", "callbacks" ]
python
train
46
saltstack/salt
salt/modules/apcups.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apcups.py#L86-L102
def status_charge(): ''' Return battery charge CLI Example: .. code-block:: bash salt '*' apcups.status_charge ''' data = status() if 'BCHARGE' in data: charge = data['BCHARGE'].split() if charge[1].lower() == 'percent': return float(charge[0]) return {'Error': 'Load not available.'}
[ "def", "status_charge", "(", ")", ":", "data", "=", "status", "(", ")", "if", "'BCHARGE'", "in", "data", ":", "charge", "=", "data", "[", "'BCHARGE'", "]", ".", "split", "(", ")", "if", "charge", "[", "1", "]", ".", "lower", "(", ")", "==", "'per...
Return battery charge CLI Example: .. code-block:: bash salt '*' apcups.status_charge
[ "Return", "battery", "charge" ]
python
train
20
jgillick/LendingClub
lendingclub/filters.py
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L197-L207
def __normalize_grades(self): """ Adjust the grades list. If a grade has been set, set All to false """ if 'grades' in self and self['grades']['All'] is True: for grade in self['grades']: if grade != 'All' and self['grades'][grade] is True: self['grades']['All'] = False break
[ "def", "__normalize_grades", "(", "self", ")", ":", "if", "'grades'", "in", "self", "and", "self", "[", "'grades'", "]", "[", "'All'", "]", "is", "True", ":", "for", "grade", "in", "self", "[", "'grades'", "]", ":", "if", "grade", "!=", "'All'", "and...
Adjust the grades list. If a grade has been set, set All to false
[ "Adjust", "the", "grades", "list", ".", "If", "a", "grade", "has", "been", "set", "set", "All", "to", "false" ]
python
train
34.090909
PySimpleGUI/PySimpleGUI
PySimpleGUIWeb/PySimpleGUIWeb.py
https://github.com/PySimpleGUI/PySimpleGUI/blob/08184197f5bd4580ab5e5aca28bdda30f87b86fc/PySimpleGUIWeb/PySimpleGUIWeb.py#L6596-L6647
def PopupGetFolder(message, default_path='', no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None, icon=DEFAULT_WINDOW_ICON, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None): """ Display popup with text entry field and browse button. Browse for folder :param message: :param default_path: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon: :param font: :param no_titlebar: :param grab_anywhere: :param keep_on_top: :param location: :return: Contents of text field. None if closed using X or cancelled """ global _my_windows if no_window: if _my_windows.NumOpenWindows: root = tk.Toplevel() else: root = tk.Tk() try: root.attributes('-alpha', 0) # hide window while building it. makes for smoother 'paint' except: pass folder_name = tk.filedialog.askdirectory() # show the 'get folder' dialog box root.destroy() return folder_name layout = [[Text(message, auto_size_text=True, text_color=text_color, background_color=background_color)], [InputText(default_text=default_path, size=size), FolderBrowse(initial_folder=initial_folder)], [Button('Ok', size=(5, 1), bind_return_key=True), Button('Cancel', size=(5, 1))]] window = Window(title=message, icon=icon, auto_size_text=True, button_color=button_color, background_color=background_color, font=font, no_titlebar=no_titlebar, grab_anywhere=grab_anywhere, keep_on_top=keep_on_top, location=location) (button, input_values) = window.LayoutAndRead(layout) window.Close() if button != 'Ok': return None else: path = input_values[0] return path
[ "def", "PopupGetFolder", "(", "message", ",", "default_path", "=", "''", ",", "no_window", "=", "False", ",", "size", "=", "(", "None", ",", "None", ")", ",", "button_color", "=", "None", ",", "background_color", "=", "None", ",", "text_color", "=", "Non...
Display popup with text entry field and browse button. Browse for folder :param message: :param default_path: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon: :param font: :param no_titlebar: :param grab_anywhere: :param keep_on_top: :param location: :return: Contents of text field. None if closed using X or cancelled
[ "Display", "popup", "with", "text", "entry", "field", "and", "browse", "button", ".", "Browse", "for", "folder", ":", "param", "message", ":", ":", "param", "default_path", ":", ":", "param", "no_window", ":", ":", "param", "size", ":", ":", "param", "bu...
python
train
37.730769
alfredodeza/remoto
remoto/backends/__init__.py
https://github.com/alfredodeza/remoto/blob/b7625e571a4b6c83f9589a1e9ad07354e42bf0d3/remoto/backends/__init__.py#L277-L292
def needs_ssh(hostname, _socket=None): """ Obtains remote hostname of the socket and cuts off the domain part of its FQDN. """ if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']: return False _socket = _socket or socket fqdn = _socket.getfqdn() if hostname == fqdn: return False local_hostname = _socket.gethostname() local_short_hostname = local_hostname.split('.')[0] if local_hostname == hostname or local_short_hostname == hostname: return False return True
[ "def", "needs_ssh", "(", "hostname", ",", "_socket", "=", "None", ")", ":", "if", "hostname", ".", "lower", "(", ")", "in", "[", "'localhost'", ",", "'127.0.0.1'", ",", "'127.0.1.1'", "]", ":", "return", "False", "_socket", "=", "_socket", "or", "socket"...
Obtains remote hostname of the socket and cuts off the domain part of its FQDN.
[ "Obtains", "remote", "hostname", "of", "the", "socket", "and", "cuts", "off", "the", "domain", "part", "of", "its", "FQDN", "." ]
python
train
33.125
Becksteinlab/GromacsWrapper
gromacs/fileformats/convert.py
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/fileformats/convert.py#L178-L189
def _convert_fancy(self, field): """Convert to a list (sep != None) and convert list elements.""" if self.sep is False: x = self._convert_singlet(field) else: x = tuple([self._convert_singlet(s) for s in field.split(self.sep)]) if len(x) == 0: x = '' elif len(x) == 1: x = x[0] #print "%r --> %r" % (field, x) return x
[ "def", "_convert_fancy", "(", "self", ",", "field", ")", ":", "if", "self", ".", "sep", "is", "False", ":", "x", "=", "self", ".", "_convert_singlet", "(", "field", ")", "else", ":", "x", "=", "tuple", "(", "[", "self", ".", "_convert_singlet", "(", ...
Convert to a list (sep != None) and convert list elements.
[ "Convert", "to", "a", "list", "(", "sep", "!", "=", "None", ")", "and", "convert", "list", "elements", "." ]
python
valid
35.583333
OpenAssets/openassets
openassets/protocol.py
https://github.com/OpenAssets/openassets/blob/e8eb5b80b9703c80980cb275dd85f17d50e39c60/openassets/protocol.py#L444-L467
def parse_script(output_script): """ Parses an output and returns the payload if the output matches the right pattern for a marker output, or None otherwise. :param CScript output_script: The output script to be parsed. :return: The marker output payload if the output fits the pattern, None otherwise. :rtype: bytes """ script_iterator = output_script.raw_iter() try: first_opcode, _, _ = next(script_iterator, (None, None, None)) _, data, _ = next(script_iterator, (None, None, None)) remainder = next(script_iterator, None) except bitcoin.core.script.CScriptTruncatedPushDataError: return None except bitcoin.core.script.CScriptInvalidError: return None if first_opcode == bitcoin.core.script.OP_RETURN and data is not None and remainder is None: return data else: return None
[ "def", "parse_script", "(", "output_script", ")", ":", "script_iterator", "=", "output_script", ".", "raw_iter", "(", ")", "try", ":", "first_opcode", ",", "_", ",", "_", "=", "next", "(", "script_iterator", ",", "(", "None", ",", "None", ",", "None", ")...
Parses an output and returns the payload if the output matches the right pattern for a marker output, or None otherwise. :param CScript output_script: The output script to be parsed. :return: The marker output payload if the output fits the pattern, None otherwise. :rtype: bytes
[ "Parses", "an", "output", "and", "returns", "the", "payload", "if", "the", "output", "matches", "the", "right", "pattern", "for", "a", "marker", "output", "or", "None", "otherwise", "." ]
python
train
39.458333
tBaxter/tango-comments
build/lib/tango_comments/forms.py
https://github.com/tBaxter/tango-comments/blob/1fd335c6fc9e81bba158e42e1483f1a149622ab4/build/lib/tango_comments/forms.py#L110-L126
def get_comment_object(self): """ Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``). """ if not self.is_valid(): raise ValueError("get_comment_object may only be called on valid forms") CommentModel = self.get_comment_model() new = CommentModel(**self.get_comment_create_data()) new = self.check_for_duplicate_comment(new) return new
[ "def", "get_comment_object", "(", "self", ")", ":", "if", "not", "self", ".", "is_valid", "(", ")", ":", "raise", "ValueError", "(", "\"get_comment_object may only be called on valid forms\"", ")", "CommentModel", "=", "self", ".", "get_comment_model", "(", ")", "...
Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError if not. Does not set any of the fields that would come from a Request object (i.e. ``user`` or ``ip_address``).
[ "Return", "a", "new", "(", "unsaved", ")", "comment", "object", "based", "on", "the", "information", "in", "this", "form", ".", "Assumes", "that", "the", "form", "is", "already", "validated", "and", "will", "throw", "a", "ValueError", "if", "not", "." ]
python
train
37.470588
swharden/SWHLab
swhlab/core.py
https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/core.py#L445-L449
def output_touch(self): """ensure the ./swhlab/ folder exists.""" if not os.path.exists(self.outFolder): self.log.debug("creating %s",self.outFolder) os.mkdir(self.outFolder)
[ "def", "output_touch", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "outFolder", ")", ":", "self", ".", "log", ".", "debug", "(", "\"creating %s\"", ",", "self", ".", "outFolder", ")", "os", ".", "mkdir", ...
ensure the ./swhlab/ folder exists.
[ "ensure", "the", ".", "/", "swhlab", "/", "folder", "exists", "." ]
python
valid
42
inveniosoftware/invenio-pidstore
invenio_pidstore/alembic/999c62899c20_create_pidstore_tables.py
https://github.com/inveniosoftware/invenio-pidstore/blob/8bf35f4e62d5dcaf1a2cfe5803245ba5220a9b78/invenio_pidstore/alembic/999c62899c20_create_pidstore_tables.py#L22-L72
def upgrade(): """Upgrade database.""" op.create_table( 'pidstore_pid', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column('id', sa.Integer(), nullable=False), sa.Column('pid_type', sa.String(length=6), nullable=False), sa.Column('pid_value', sa.String(length=255), nullable=False), sa.Column('pid_provider', sa.String(length=8), nullable=True), sa.Column('status', sa.CHAR(1), nullable=False), sa.Column('object_type', sa.String(length=3), nullable=True), sa.Column( 'object_uuid', sqlalchemy_utils.types.uuid.UUIDType(), nullable=True ), sa.PrimaryKeyConstraint('id') ) op.create_index( 'idx_object', 'pidstore_pid', ['object_type', 'object_uuid'], unique=False ) op.create_index('idx_status', 'pidstore_pid', ['status'], unique=False) op.create_index( 'uidx_type_pid', 'pidstore_pid', ['pid_type', 'pid_value'], unique=True ) op.create_table( 'pidstore_recid', sa.Column('recid', sa.BigInteger(), nullable=False), sa.PrimaryKeyConstraint('recid') ) op.create_table( 'pidstore_redirect', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column( 'id', sqlalchemy_utils.types.uuid.UUIDType(), nullable=False ), sa.Column('pid_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint( ['pid_id'], [u'pidstore_pid.id'], onupdate='CASCADE', ondelete='RESTRICT' ), sa.PrimaryKeyConstraint('id') )
[ "def", "upgrade", "(", ")", ":", "op", ".", "create_table", "(", "'pidstore_pid'", ",", "sa", ".", "Column", "(", "'created'", ",", "sa", ".", "DateTime", "(", ")", ",", "nullable", "=", "False", ")", ",", "sa", ".", "Column", "(", "'updated'", ",", ...
Upgrade database.
[ "Upgrade", "database", "." ]
python
train
34.54902
tammoippen/geohash-hilbert
geohash_hilbert/_hilbert.py
https://github.com/tammoippen/geohash-hilbert/blob/b74f0fc1bff0234d8ff367e4129c3324676b0b36/geohash_hilbert/_hilbert.py#L205-L230
def _xy2hash(x, y, dim): """Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in dim x dim coord system y: int y value of point [0, dim) in dim x dim coord system dim: int Number of coding points each x, y value can take. Corresponds to 2^level of the hilbert curve. Returns: int: hashcode ∈ [0, dim**2) """ d = 0 lvl = dim >> 1 while (lvl > 0): rx = int((x & lvl) > 0) ry = int((y & lvl) > 0) d += lvl * lvl * ((3 * rx) ^ ry) x, y = _rotate(lvl, x, y, rx, ry) lvl >>= 1 return d
[ "def", "_xy2hash", "(", "x", ",", "y", ",", "dim", ")", ":", "d", "=", "0", "lvl", "=", "dim", ">>", "1", "while", "(", "lvl", ">", "0", ")", ":", "rx", "=", "int", "(", "(", "x", "&", "lvl", ")", ">", "0", ")", "ry", "=", "int", "(", ...
Convert (x, y) to hashcode. Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 Pure python implementation. Parameters: x: int x value of point [0, dim) in dim x dim coord system y: int y value of point [0, dim) in dim x dim coord system dim: int Number of coding points each x, y value can take. Corresponds to 2^level of the hilbert curve. Returns: int: hashcode ∈ [0, dim**2)
[ "Convert", "(", "x", "y", ")", "to", "hashcode", "." ]
python
train
29.923077
pysal/spglm
spglm/base.py
https://github.com/pysal/spglm/blob/1339898adcb7e1638f1da83d57aa37392525f018/spglm/base.py#L258-L338
def cov_params(self, r_matrix=None, column=None, scale=None, cov_p=None, other=None): """ Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. Parameters ---------- r_matrix : array-like Can be 1d, or 2d. Can be used alone or with other. column : array-like, optional Must be used on its own. Can be 0d or 1d see below. scale : float, optional Can be specified or not. Default is None, which means that the scale argument is taken from the model. other : array-like, optional Can be used when r_matrix is specified. Returns ------- cov : ndarray covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. Notes ----- (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model ``(scale)*(X.T X)^(-1)`` If contrast is specified it pre and post-multiplies as follows ``(scale) * r_matrix (X.T X)^(-1) r_matrix.T`` If contrast and other are specified returns ``(scale) * r_matrix (X.T X)^(-1) other.T`` If column is specified returns ``(scale) * (X.T X)^(-1)[column,column]`` if column is 0d OR ``(scale) * (X.T X)^(-1)[column][:,column]`` if column is 1d """ if (hasattr(self, 'mle_settings') and self.mle_settings['optimizer'] in ['l1', 'l1_cvxopt_cp']): dot_fun = nan_dot else: dot_fun = np.dot if (cov_p is None and self.normalized_cov_params is None and not hasattr(self, 'cov_params_default')): raise ValueError('need covariance of parameters for computing ' '(unnormalized) covariances') if column is not None and (r_matrix is not None or other is not None): raise ValueError('Column should be specified without other ' 'arguments.') if other is not None and r_matrix is None: raise ValueError('other can only be specified with r_matrix') if cov_p is None: if hasattr(self, 'cov_params_default'): cov_p = self.cov_params_default else: if scale is None: scale = self.scale cov_p = self.normalized_cov_params * scale if column is not None: column = np.asarray(column) if column.shape == (): return cov_p[column, column] else: # return cov_p[column][:, column] return cov_p[column[:, None], column] elif r_matrix is not None: r_matrix = np.asarray(r_matrix) if r_matrix.shape == (): raise ValueError("r_matrix should be 1d or 2d") if other is None: other = r_matrix else: other = np.asarray(other) tmp = dot_fun(r_matrix, dot_fun(cov_p, np.transpose(other))) return tmp else: # if r_matrix is None and column is None: return cov_p
[ "def", "cov_params", "(", "self", ",", "r_matrix", "=", "None", ",", "column", "=", "None", ",", "scale", "=", "None", ",", "cov_p", "=", "None", ",", "other", "=", "None", ")", ":", "if", "(", "hasattr", "(", "self", ",", "'mle_settings'", ")", "a...
Returns the variance/covariance matrix. The variance/covariance matrix can be of a linear contrast of the estimates of params or all params multiplied by scale which will usually be an estimate of sigma^2. Scale is assumed to be a scalar. Parameters ---------- r_matrix : array-like Can be 1d, or 2d. Can be used alone or with other. column : array-like, optional Must be used on its own. Can be 0d or 1d see below. scale : float, optional Can be specified or not. Default is None, which means that the scale argument is taken from the model. other : array-like, optional Can be used when r_matrix is specified. Returns ------- cov : ndarray covariance matrix of the parameter estimates or of linear combination of parameter estimates. See Notes. Notes ----- (The below are assumed to be in matrix notation.) If no argument is specified returns the covariance matrix of a model ``(scale)*(X.T X)^(-1)`` If contrast is specified it pre and post-multiplies as follows ``(scale) * r_matrix (X.T X)^(-1) r_matrix.T`` If contrast and other are specified returns ``(scale) * r_matrix (X.T X)^(-1) other.T`` If column is specified returns ``(scale) * (X.T X)^(-1)[column,column]`` if column is 0d OR ``(scale) * (X.T X)^(-1)[column][:,column]`` if column is 1d
[ "Returns", "the", "variance", "/", "covariance", "matrix", ".", "The", "variance", "/", "covariance", "matrix", "can", "be", "of", "a", "linear", "contrast", "of", "the", "estimates", "of", "params", "or", "all", "params", "multiplied", "by", "scale", "which...
python
train
42.17284
delph-in/pydelphin
delphin/mrs/__init__.py
https://github.com/delph-in/pydelphin/blob/7bd2cd63ab7cf74803e1d6547b9ebc014b382abd/delphin/mrs/__init__.py#L53-L95
def convert(txt, src_fmt, tgt_fmt, single=True, **kwargs): """ Convert a textual representation of \*MRS from one the src_fmt representation to the tgt_fmt representation. By default, only read and convert a single \*MRS object (e.g. for `mrx` this starts at <mrs> and not <mrs-list>), but changing the `mode` argument to `corpus` (alternatively: `list`) reads and converts multiple \*MRSs. Args: txt: A string of semantic data. src_fmt: The original representation format of txt. tgt_fmt: The representation format to convert to. single: If True, assume txt represents a single \*MRS, otherwise read it as a corpus (or list) of \*MRSs. kwargs: Any other keyword arguments to pass to the serializer of the target format. See Notes. Returns: A string in the target format. Notes: src_fmt and tgt_fmt may be one of the following: | format | description | | --------- | ---------------------------- | | simplemrs | The popular SimpleMRS format | | mrx | The XML format of MRS | | dmrx | The XML format of DMRS | Additional keyword arguments for the serializer may include: | option | description | | ------------ | ----------------------------------- | | pretty_print | print with newlines and indentation | | color | print with syntax highlighting | """ from importlib import import_module reader = import_module('{}.{}'.format('delphin.mrs', src_fmt.lower())) writer = import_module('{}.{}'.format('delphin.mrs', tgt_fmt.lower())) return writer.dumps( reader.loads(txt, single=single), single=single, **kwargs )
[ "def", "convert", "(", "txt", ",", "src_fmt", ",", "tgt_fmt", ",", "single", "=", "True", ",", "*", "*", "kwargs", ")", ":", "from", "importlib", "import", "import_module", "reader", "=", "import_module", "(", "'{}.{}'", ".", "format", "(", "'delphin.mrs'"...
Convert a textual representation of \*MRS from one the src_fmt representation to the tgt_fmt representation. By default, only read and convert a single \*MRS object (e.g. for `mrx` this starts at <mrs> and not <mrs-list>), but changing the `mode` argument to `corpus` (alternatively: `list`) reads and converts multiple \*MRSs. Args: txt: A string of semantic data. src_fmt: The original representation format of txt. tgt_fmt: The representation format to convert to. single: If True, assume txt represents a single \*MRS, otherwise read it as a corpus (or list) of \*MRSs. kwargs: Any other keyword arguments to pass to the serializer of the target format. See Notes. Returns: A string in the target format. Notes: src_fmt and tgt_fmt may be one of the following: | format | description | | --------- | ---------------------------- | | simplemrs | The popular SimpleMRS format | | mrx | The XML format of MRS | | dmrx | The XML format of DMRS | Additional keyword arguments for the serializer may include: | option | description | | ------------ | ----------------------------------- | | pretty_print | print with newlines and indentation | | color | print with syntax highlighting |
[ "Convert", "a", "textual", "representation", "of", "\\", "*", "MRS", "from", "one", "the", "src_fmt", "representation", "to", "the", "tgt_fmt", "representation", ".", "By", "default", "only", "read", "and", "convert", "a", "single", "\\", "*", "MRS", "object...
python
train
42
sdispater/orator
orator/schema/builder.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/schema/builder.py#L62-L78
def table(self, table): """ Modify a table on the schema. :param table: The table """ try: blueprint = self._create_blueprint(table) yield blueprint except Exception as e: raise try: self._build(blueprint) except Exception: raise
[ "def", "table", "(", "self", ",", "table", ")", ":", "try", ":", "blueprint", "=", "self", ".", "_create_blueprint", "(", "table", ")", "yield", "blueprint", "except", "Exception", "as", "e", ":", "raise", "try", ":", "self", ".", "_build", "(", "bluep...
Modify a table on the schema. :param table: The table
[ "Modify", "a", "table", "on", "the", "schema", "." ]
python
train
20
bspaans/python-mingus
mingus/extra/tunings.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tunings.py#L274-L281
def frets_to_NoteContainer(self, fingering): """Convert a list such as returned by find_fret to a NoteContainer.""" res = [] for (string, fret) in enumerate(fingering): if fret is not None: res.append(self.get_Note(string, fret)) return NoteContainer(res)
[ "def", "frets_to_NoteContainer", "(", "self", ",", "fingering", ")", ":", "res", "=", "[", "]", "for", "(", "string", ",", "fret", ")", "in", "enumerate", "(", "fingering", ")", ":", "if", "fret", "is", "not", "None", ":", "res", ".", "append", "(", ...
Convert a list such as returned by find_fret to a NoteContainer.
[ "Convert", "a", "list", "such", "as", "returned", "by", "find_fret", "to", "a", "NoteContainer", "." ]
python
train
38.625
CS207-Final-Project-Group-10/cs207-FinalProject
fluxions/elementary_functions.py
https://github.com/CS207-Final-Project-Group-10/cs207-FinalProject/blob/842e9c2d3ca1490cef18c086dfde81856d8d3a82/fluxions/elementary_functions.py#L362-L368
def _deriv_logaddexp2(x1, x2): """The derivative of f(x, y) = log2(2^x + 2^y)""" y1 = np.exp2(x1) y2 = np.exp2(x2) df_dx1 = y1 / (y1 + y2) df_dx2 = y2 / (y1 + y2) return np.vstack([df_dx1, df_dx2]).T
[ "def", "_deriv_logaddexp2", "(", "x1", ",", "x2", ")", ":", "y1", "=", "np", ".", "exp2", "(", "x1", ")", "y2", "=", "np", ".", "exp2", "(", "x2", ")", "df_dx1", "=", "y1", "/", "(", "y1", "+", "y2", ")", "df_dx2", "=", "y2", "/", "(", "y1"...
The derivative of f(x, y) = log2(2^x + 2^y)
[ "The", "derivative", "of", "f", "(", "x", "y", ")", "=", "log2", "(", "2^x", "+", "2^y", ")" ]
python
train
31
apache/incubator-superset
superset/models/core.py
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L305-L322
def get_viz(self, force=False): """Creates :py:class:viz.BaseViz object from the url_params_multidict. :return: object of the 'viz_type' type that is taken from the url_params_multidict or self.params. :rtype: :py:class:viz.BaseViz """ slice_params = json.loads(self.params) slice_params['slice_id'] = self.id slice_params['json'] = 'false' slice_params['slice_name'] = self.slice_name slice_params['viz_type'] = self.viz_type if self.viz_type else 'table' return viz_types[slice_params.get('viz_type')]( self.datasource, form_data=slice_params, force=force, )
[ "def", "get_viz", "(", "self", ",", "force", "=", "False", ")", ":", "slice_params", "=", "json", ".", "loads", "(", "self", ".", "params", ")", "slice_params", "[", "'slice_id'", "]", "=", "self", ".", "id", "slice_params", "[", "'json'", "]", "=", ...
Creates :py:class:viz.BaseViz object from the url_params_multidict. :return: object of the 'viz_type' type that is taken from the url_params_multidict or self.params. :rtype: :py:class:viz.BaseViz
[ "Creates", ":", "py", ":", "class", ":", "viz", ".", "BaseViz", "object", "from", "the", "url_params_multidict", "." ]
python
train
37.833333
jart/fabulous
fabulous/text.py
https://github.com/jart/fabulous/blob/19903cf0a980b82f5928c3bec1f28b6bdd3785bd/fabulous/text.py#L180-L208
def get_font_files(): """Returns a list of all font files we could find Returned as a list of dir/files tuples:: get_font_files() -> {'FontName': '/abs/FontName.ttf', ...] For example:: >>> fonts = get_font_files() >>> 'NotoSans-Bold' in fonts True >>> fonts['NotoSans-Bold'].endswith('/NotoSans-Bold.ttf') True """ roots = [ '/usr/share/fonts/truetype', # where ubuntu puts fonts '/usr/share/fonts', # where fedora puts fonts os.path.expanduser('~/.fonts'), # custom user fonts os.path.abspath(os.path.join(os.path.dirname(__file__), 'fonts')), ] result = {} for root in roots: for path, dirs, names in os.walk(root): for name in names: if name.endswith(('.ttf', '.otf')): result[name[:-4]] = os.path.join(path, name) return result
[ "def", "get_font_files", "(", ")", ":", "roots", "=", "[", "'/usr/share/fonts/truetype'", ",", "# where ubuntu puts fonts", "'/usr/share/fonts'", ",", "# where fedora puts fonts", "os", ".", "path", ".", "expanduser", "(", "'~/.fonts'", ")", ",", "# custom user fonts", ...
Returns a list of all font files we could find Returned as a list of dir/files tuples:: get_font_files() -> {'FontName': '/abs/FontName.ttf', ...] For example:: >>> fonts = get_font_files() >>> 'NotoSans-Bold' in fonts True >>> fonts['NotoSans-Bold'].endswith('/NotoSans-Bold.ttf') True
[ "Returns", "a", "list", "of", "all", "font", "files", "we", "could", "find" ]
python
train
31
chrisrink10/basilisp
src/basilisp/lang/compiler/optimizer.py
https://github.com/chrisrink10/basilisp/blob/3d82670ee218ec64eb066289c82766d14d18cc92/src/basilisp/lang/compiler/optimizer.py#L47-L60
def visit_FunctionDef(self, node: ast.FunctionDef) -> Optional[ast.AST]: """Eliminate dead code from function bodies.""" new_node = self.generic_visit(node) assert isinstance(new_node, ast.FunctionDef) return ast.copy_location( ast.FunctionDef( name=new_node.name, args=new_node.args, body=_filter_dead_code(new_node.body), decorator_list=new_node.decorator_list, returns=new_node.returns, ), new_node, )
[ "def", "visit_FunctionDef", "(", "self", ",", "node", ":", "ast", ".", "FunctionDef", ")", "->", "Optional", "[", "ast", ".", "AST", "]", ":", "new_node", "=", "self", ".", "generic_visit", "(", "node", ")", "assert", "isinstance", "(", "new_node", ",", ...
Eliminate dead code from function bodies.
[ "Eliminate", "dead", "code", "from", "function", "bodies", "." ]
python
test
39.071429
TissueMAPS/TmDeploy
tmdeploy/log.py
https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/tmdeploy/log.py#L68-L92
def configure_logging(level=logging.DEBUG): '''Configures the root logger for command line applications. A stream handler will be added to the logger that directs messages to the standard error stream. By default, *no* messages will be filtered out: set a higher level on derived/child loggers to achieve filtering. Warning ------- Logging should only be configured once at the main entry point of the application! ''' fmt = '%(asctime)s | %(levelname)-8s | %(name)-40s | %(message)s' datefmt = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(fmt=fmt, datefmt=datefmt) logger = logging.getLogger() # returns the root logger stderr_handler = logging.StreamHandler(stream=sys.stderr) stderr_handler.name = 'err' stderr_handler.setLevel(level) stderr_handler.setFormatter(formatter) logger.addHandler(stderr_handler)
[ "def", "configure_logging", "(", "level", "=", "logging", ".", "DEBUG", ")", ":", "fmt", "=", "'%(asctime)s | %(levelname)-8s | %(name)-40s | %(message)s'", "datefmt", "=", "'%Y-%m-%d %H:%M:%S'", "formatter", "=", "logging", ".", "Formatter", "(", "fmt", "=", "fmt", ...
Configures the root logger for command line applications. A stream handler will be added to the logger that directs messages to the standard error stream. By default, *no* messages will be filtered out: set a higher level on derived/child loggers to achieve filtering. Warning ------- Logging should only be configured once at the main entry point of the application!
[ "Configures", "the", "root", "logger", "for", "command", "line", "applications", "." ]
python
train
34.92
Zsailer/kubeconf
kubeconf/kubeconf.py
https://github.com/Zsailer/kubeconf/blob/b4e81001b5d2fb8d461056f25eb8b03307d57a6b/kubeconf/kubeconf.py#L267-L272
def remove_user(self, name): """Remove a user from kubeconfig. """ user = self.get_user(name) users = self.get_users() users.remove(user)
[ "def", "remove_user", "(", "self", ",", "name", ")", ":", "user", "=", "self", ".", "get_user", "(", "name", ")", "users", "=", "self", ".", "get_users", "(", ")", "users", ".", "remove", "(", "user", ")" ]
Remove a user from kubeconfig.
[ "Remove", "a", "user", "from", "kubeconfig", "." ]
python
train
28.666667
caioariede/docker-run-build
docker_rb/utils.py
https://github.com/caioariede/docker-run-build/blob/76ca4802018a63d6778374ebdba082d6750816b2/docker_rb/utils.py#L13-L19
def get_old_options(cli, image): """ Returns Dockerfile values for CMD and Entrypoint """ return { 'cmd': dockerapi.inspect_config(cli, image, 'Cmd'), 'entrypoint': dockerapi.inspect_config(cli, image, 'Entrypoint'), }
[ "def", "get_old_options", "(", "cli", ",", "image", ")", ":", "return", "{", "'cmd'", ":", "dockerapi", ".", "inspect_config", "(", "cli", ",", "image", ",", "'Cmd'", ")", ",", "'entrypoint'", ":", "dockerapi", ".", "inspect_config", "(", "cli", ",", "im...
Returns Dockerfile values for CMD and Entrypoint
[ "Returns", "Dockerfile", "values", "for", "CMD", "and", "Entrypoint" ]
python
train
34.857143
cbclab/MOT
mot/sample/base.py
https://github.com/cbclab/MOT/blob/fb3243b65025705842e82704705c00902f9a35af/mot/sample/base.py#L205-L253
def _get_kernel_data(self, nmr_samples, thinning, return_output): """Get the kernel data we will input to the MCMC sampler. This sets the items: * data: the pointer to the user provided data * method_data: the data specific to the MCMC method * nmr_iterations: the number of iterations to sample * iteration_offset: the current sample index, that is, the offset to the given number of iterations * rng_state: the random number generator state * current_chain_position: the current position of the sampled chain * current_log_likelihood: the log likelihood of the current position on the chain * current_log_prior: the log prior of the current position on the chain Additionally, if ``return_output`` is True, we add to that the arrays: * samples: for the samples * log_likelihoods: for storing the log likelihoods * log_priors: for storing the priors Args: nmr_samples (int): the number of samples we will draw thinning (int): the thinning factor we want to use return_output (boolean): if the kernel should return output Returns: dict[str: mot.lib.utils.KernelData]: the kernel input data """ kernel_data = { 'data': self._data, 'method_data': self._get_mcmc_method_kernel_data(), 'nmr_iterations': Scalar(nmr_samples * thinning, ctype='ulong'), 'iteration_offset': Scalar(self._sampling_index, ctype='ulong'), 'rng_state': Array(self._rng_state, 'uint', mode='rw', ensure_zero_copy=True), 'current_chain_position': Array(self._current_chain_position, 'mot_float_type', mode='rw', ensure_zero_copy=True), 'current_log_likelihood': Array(self._current_log_likelihood, 'mot_float_type', mode='rw', ensure_zero_copy=True), 'current_log_prior': Array(self._current_log_prior, 'mot_float_type', mode='rw', ensure_zero_copy=True), } if return_output: kernel_data.update({ 'samples': Zeros((self._nmr_problems, self._nmr_params, nmr_samples), ctype='mot_float_type'), 'log_likelihoods': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'), 'log_priors': Zeros((self._nmr_problems, nmr_samples), ctype='mot_float_type'), }) return kernel_data
[ "def", "_get_kernel_data", "(", "self", ",", "nmr_samples", ",", "thinning", ",", "return_output", ")", ":", "kernel_data", "=", "{", "'data'", ":", "self", ".", "_data", ",", "'method_data'", ":", "self", ".", "_get_mcmc_method_kernel_data", "(", ")", ",", ...
Get the kernel data we will input to the MCMC sampler. This sets the items: * data: the pointer to the user provided data * method_data: the data specific to the MCMC method * nmr_iterations: the number of iterations to sample * iteration_offset: the current sample index, that is, the offset to the given number of iterations * rng_state: the random number generator state * current_chain_position: the current position of the sampled chain * current_log_likelihood: the log likelihood of the current position on the chain * current_log_prior: the log prior of the current position on the chain Additionally, if ``return_output`` is True, we add to that the arrays: * samples: for the samples * log_likelihoods: for storing the log likelihoods * log_priors: for storing the priors Args: nmr_samples (int): the number of samples we will draw thinning (int): the thinning factor we want to use return_output (boolean): if the kernel should return output Returns: dict[str: mot.lib.utils.KernelData]: the kernel input data
[ "Get", "the", "kernel", "data", "we", "will", "input", "to", "the", "MCMC", "sampler", "." ]
python
train
51.387755
pricingassistant/mrq
mrq/job.py
https://github.com/pricingassistant/mrq/blob/d0a5a34de9cba38afa94fb7c9e17f9b570b79a50/mrq/job.py#L663-L668
def queue_raw_jobs(queue, params_list, **kwargs): """ Queue some jobs on a raw queue """ from .queue import Queue queue_obj = Queue(queue) queue_obj.enqueue_raw_jobs(params_list, **kwargs)
[ "def", "queue_raw_jobs", "(", "queue", ",", "params_list", ",", "*", "*", "kwargs", ")", ":", "from", ".", "queue", "import", "Queue", "queue_obj", "=", "Queue", "(", "queue", ")", "queue_obj", ".", "enqueue_raw_jobs", "(", "params_list", ",", "*", "*", ...
Queue some jobs on a raw queue
[ "Queue", "some", "jobs", "on", "a", "raw", "queue" ]
python
train
33.333333
soldag/python-pwmled
pwmled/transitions/transition_manager.py
https://github.com/soldag/python-pwmled/blob/09cde36ecc0153fa81dc2a1b9bb07d1c0e418c8c/pwmled/transitions/transition_manager.py#L29-L40
def _transition_loop(self): """Execute all queued transitions step by step.""" while self._transitions: start = time.time() for transition in self._transitions: transition.step() if transition.finished: self._transitions.remove(transition) time_delta = time.time() - start sleep_time = max(0, self.MIN_STEP_TIME - time_delta) time.sleep(sleep_time)
[ "def", "_transition_loop", "(", "self", ")", ":", "while", "self", ".", "_transitions", ":", "start", "=", "time", ".", "time", "(", ")", "for", "transition", "in", "self", ".", "_transitions", ":", "transition", ".", "step", "(", ")", "if", "transition"...
Execute all queued transitions step by step.
[ "Execute", "all", "queued", "transitions", "step", "by", "step", "." ]
python
train
38.833333
vinci1it2000/schedula
schedula/dispatcher.py
https://github.com/vinci1it2000/schedula/blob/addb9fd685be81544b796c51383ac00a31543ce9/schedula/dispatcher.py#L1437-L1485
def blue(self, memo=None): """ Constructs a BlueDispatcher out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A BlueDispatcher of the current object. :rtype: schedula.utils.blue.BlueDispatcher """ memo = {} if memo is None else memo if self in memo: return memo[self] from .utils.dsp import map_list from .utils.blue import BlueDispatcher, _parent_blue memo[self] = blue = BlueDispatcher( executor=self.executor, name=self.name, raises=self.raises, description=self.__doc__ ) dfl = self.default_values key_map_data = ['data_id', {'value': 'default_value'}] pred, succ = self.dmap.pred, self.dmap.succ def _set_weight(n, r, d): d = {i: j['weight'] for i, j in d.items() if 'weight' in j} if d: r[n] = d for k, v in sorted(self.nodes.items(), key=lambda x: x[1]['index']): v = v.copy() t = v.pop('type') del v['index'] if t == 'data': method = 'add_data' combine_dicts(map_list(key_map_data, k, dfl.get(k, {})), base=v) elif t in ('function', 'dispatcher'): method = 'add_%s' % t if t == 'dispatcher': t = 'dsp' v['%s_id' % t] = k del v['wait_inputs'] _set_weight('inp_weight', v, pred[k]) _set_weight('out_weight', v, succ[k]) if 'function' in v: v[t] = _parent_blue(v.pop('function'), memo) blue.deferred.append((method, v)) return blue
[ "def", "blue", "(", "self", ",", "memo", "=", "None", ")", ":", "memo", "=", "{", "}", "if", "memo", "is", "None", "else", "memo", "if", "self", "in", "memo", ":", "return", "memo", "[", "self", "]", "from", ".", "utils", ".", "dsp", "import", ...
Constructs a BlueDispatcher out of the current object. :param memo: A dictionary to cache Blueprints. :type memo: dict[T,schedula.utils.blue.Blueprint] :return: A BlueDispatcher of the current object. :rtype: schedula.utils.blue.BlueDispatcher
[ "Constructs", "a", "BlueDispatcher", "out", "of", "the", "current", "object", "." ]
python
train
36.367347
RudolfCardinal/pythonlib
cardinal_pythonlib/subproc.py
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/subproc.py#L301-L454
def mimic_user_input( args: List[str], source_challenge_response: List[Tuple[SubprocSource, str, Union[str, SubprocCommand]]], line_terminators: List[str] = None, print_stdout: bool = False, print_stderr: bool = False, print_stdin: bool = False, stdin_encoding: str = None, stdout_encoding: str = None, suppress_decoding_errors: bool = True, sleep_time_s: float = 0.1) -> None: r""" Run an external command. Pretend to be a human by sending text to the subcommand (responses) when the external command sends us triggers (challenges). This is a bit nasty. Args: args: command-line arguments source_challenge_response: list of tuples of the format ``(challsrc, challenge, response)``; see below line_terminators: valid line terminators print_stdout: print_stderr: print_stdin: stdin_encoding: stdout_encoding: suppress_decoding_errors: trap any ``UnicodeDecodeError``? sleep_time_s: The ``(challsrc, challenge, response)`` tuples have this meaning: - ``challsrc``: where is the challenge coming from? Must be one of the objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`; - ``challenge``: text of challenge - ``response``: text of response (send to the subcommand's ``stdin``). Example (modified from :class:`CorruptedZipReader`): .. code-block:: python from cardinal_pythonlib.subproc import * SOURCE_FILENAME = "corrupt.zip" TMP_DIR = "/tmp" OUTPUT_FILENAME = "rescued.zip" cmdargs = [ "zip", # Linux zip tool "-FF", # or "--fixfix": "fix very broken things" SOURCE_FILENAME, # input file "--temp-path", TMP_DIR, # temporary storage path "--out", OUTPUT_FILENAME # output file ] # We would like to be able to say "y" automatically to # "Is this a single-disk archive? (y/n):" # The source code (api.c, zip.c, zipfile.c), from # ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q" # should do this (internally "-q" sets "noisy = 0") - but in # practice it doesn't work. This is a critical switch. # Therefore we will do something very ugly, and send raw text via # stdin. ZIP_PROMPTS_RESPONSES = [ (SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"), (SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"), (SOURCE_STDERR, "zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) " "&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && " "prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) " "== 0)' failed.", TERMINATE_SUBPROCESS), ] ZIP_STDOUT_TERMINATORS = ["\n", "): "] mimic_user_input(cmdargs, source_challenge_response=ZIP_PROMPTS_RESPONSES, line_terminators=ZIP_STDOUT_TERMINATORS, print_stdout=show_zip_output, print_stdin=show_zip_output) """ # noqa line_terminators = line_terminators or ["\n"] # type: List[str] stdin_encoding = stdin_encoding or sys.getdefaultencoding() stdout_encoding = stdout_encoding or sys.getdefaultencoding() # Launch the command p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=0) # Launch the asynchronous readers of stdout and stderr stdout_queue = Queue() # noinspection PyTypeChecker stdout_reader = AsynchronousFileReader( fd=p.stdout, queue=stdout_queue, encoding=stdout_encoding, line_terminators=line_terminators, cmdargs=args, suppress_decoding_errors=suppress_decoding_errors ) stdout_reader.start() stderr_queue = Queue() # noinspection PyTypeChecker stderr_reader = AsynchronousFileReader( fd=p.stderr, queue=stderr_queue, encoding=stdout_encoding, # same as stdout line_terminators=line_terminators, cmdargs=args, suppress_decoding_errors=suppress_decoding_errors ) stderr_reader.start() while not stdout_reader.eof() or not stderr_reader.eof(): lines_with_source = [] # type: List[Tuple[SubprocSource, str]] while not stdout_queue.empty(): lines_with_source.append((SOURCE_STDOUT, stdout_queue.get())) while not stderr_queue.empty(): lines_with_source.append((SOURCE_STDERR, stderr_queue.get())) for src, line in lines_with_source: if src is SOURCE_STDOUT and print_stdout: print(line, end="") # terminator already in line if src is SOURCE_STDERR and print_stderr: print(line, end="") # terminator already in line for challsrc, challenge, response in source_challenge_response: # log.critical("challsrc={!r}", challsrc) # log.critical("challenge={!r}", challenge) # log.critical("line={!r}", line) # log.critical("response={!r}", response) if challsrc != src: continue if challenge in line: if response is TERMINATE_SUBPROCESS: log.warning("Terminating subprocess {!r} because input " "{!r} received", args, challenge) p.kill() return else: p.stdin.write(response.encode(stdin_encoding)) p.stdin.flush() if print_stdin: print(response, end="") # Sleep a bit before asking the readers again. sleep(sleep_time_s) stdout_reader.join() stderr_reader.join() p.stdout.close() p.stderr.close()
[ "def", "mimic_user_input", "(", "args", ":", "List", "[", "str", "]", ",", "source_challenge_response", ":", "List", "[", "Tuple", "[", "SubprocSource", ",", "str", ",", "Union", "[", "str", ",", "SubprocCommand", "]", "]", "]", ",", "line_terminators", ":...
r""" Run an external command. Pretend to be a human by sending text to the subcommand (responses) when the external command sends us triggers (challenges). This is a bit nasty. Args: args: command-line arguments source_challenge_response: list of tuples of the format ``(challsrc, challenge, response)``; see below line_terminators: valid line terminators print_stdout: print_stderr: print_stdin: stdin_encoding: stdout_encoding: suppress_decoding_errors: trap any ``UnicodeDecodeError``? sleep_time_s: The ``(challsrc, challenge, response)`` tuples have this meaning: - ``challsrc``: where is the challenge coming from? Must be one of the objects :data:`SOURCE_STDOUT` or :data:`SOURCE_STDERR`; - ``challenge``: text of challenge - ``response``: text of response (send to the subcommand's ``stdin``). Example (modified from :class:`CorruptedZipReader`): .. code-block:: python from cardinal_pythonlib.subproc import * SOURCE_FILENAME = "corrupt.zip" TMP_DIR = "/tmp" OUTPUT_FILENAME = "rescued.zip" cmdargs = [ "zip", # Linux zip tool "-FF", # or "--fixfix": "fix very broken things" SOURCE_FILENAME, # input file "--temp-path", TMP_DIR, # temporary storage path "--out", OUTPUT_FILENAME # output file ] # We would like to be able to say "y" automatically to # "Is this a single-disk archive? (y/n):" # The source code (api.c, zip.c, zipfile.c), from # ftp://ftp.info-zip.org/pub/infozip/src/ , suggests that "-q" # should do this (internally "-q" sets "noisy = 0") - but in # practice it doesn't work. This is a critical switch. # Therefore we will do something very ugly, and send raw text via # stdin. ZIP_PROMPTS_RESPONSES = [ (SOURCE_STDOUT, "Is this a single-disk archive? (y/n): ", "y\n"), (SOURCE_STDOUT, " or ENTER (try reading this split again): ", "q\n"), (SOURCE_STDERR, "zip: malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) " "&& old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && " "prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) " "== 0)' failed.", TERMINATE_SUBPROCESS), ] ZIP_STDOUT_TERMINATORS = ["\n", "): "] mimic_user_input(cmdargs, source_challenge_response=ZIP_PROMPTS_RESPONSES, line_terminators=ZIP_STDOUT_TERMINATORS, print_stdout=show_zip_output, print_stdin=show_zip_output)
[ "r", "Run", "an", "external", "command", ".", "Pretend", "to", "be", "a", "human", "by", "sending", "text", "to", "the", "subcommand", "(", "responses", ")", "when", "the", "external", "command", "sends", "us", "triggers", "(", "challenges", ")", ".", "T...
python
train
39.311688
proycon/python-timbl
timbl.py
https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L293-L311
def leaveoneout(self): """Train & Test using leave one out""" traintestfile = self.fileprefix + '.train' options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out" if sys.version < '3': self.api = timblapi.TimblAPI(b(options), b"") else: self.api = timblapi.TimblAPI(options, "") if self.debug: print("Enabling debug for timblapi",file=stderr) self.api.enableDebug() print("Calling Timbl API : " + options,file=stderr) if sys.version < '3': self.api.learn(b(traintestfile)) self.api.test(b(traintestfile), b(self.fileprefix + '.out'),b'') else: self.api.learn(u(traintestfile)) self.api.test(u(traintestfile), u(self.fileprefix + '.out'),'') return self.api.getAccuracy()
[ "def", "leaveoneout", "(", "self", ")", ":", "traintestfile", "=", "self", ".", "fileprefix", "+", "'.train'", "options", "=", "\"-F \"", "+", "self", ".", "format", "+", "\" \"", "+", "self", ".", "timbloptions", "+", "\" -t leave_one_out\"", "if", "sys", ...
Train & Test using leave one out
[ "Train", "&", "Test", "using", "leave", "one", "out" ]
python
train
44.684211
salimane/rediscluster-py
rediscluster/cluster_client.py
https://github.com/salimane/rediscluster-py/blob/4fe4d928cd6fe3e7564f7362e3996898bda5a285/rediscluster/cluster_client.py#L299-L302
def object(self, infotype, key): "Return the encoding, idletime, or refcount about the key" redisent = self.redises[self._getnodenamefor(key) + '_slave'] return getattr(redisent, 'object')(infotype, key)
[ "def", "object", "(", "self", ",", "infotype", ",", "key", ")", ":", "redisent", "=", "self", ".", "redises", "[", "self", ".", "_getnodenamefor", "(", "key", ")", "+", "'_slave'", "]", "return", "getattr", "(", "redisent", ",", "'object'", ")", "(", ...
Return the encoding, idletime, or refcount about the key
[ "Return", "the", "encoding", "idletime", "or", "refcount", "about", "the", "key" ]
python
valid
56
learningequality/ricecooker
ricecooker/managers/progress.py
https://github.com/learningequality/ricecooker/blob/2f0385282500cb77ef2894646c6f9ce11bd7a853/ricecooker/managers/progress.py#L198-L204
def set_uploaded(self, files_uploaded): """ set_uploaded: records progress after uploading files Args: files_uploaded ([str]): list of files that have been successfully uploaded Returns: None """ self.files_uploaded = files_uploaded self.__record_progress(Status.UPLOAD_CHANNEL)
[ "def", "set_uploaded", "(", "self", ",", "files_uploaded", ")", ":", "self", ".", "files_uploaded", "=", "files_uploaded", "self", ".", "__record_progress", "(", "Status", ".", "UPLOAD_CHANNEL", ")" ]
set_uploaded: records progress after uploading files Args: files_uploaded ([str]): list of files that have been successfully uploaded Returns: None
[ "set_uploaded", ":", "records", "progress", "after", "uploading", "files", "Args", ":", "files_uploaded", "(", "[", "str", "]", ")", ":", "list", "of", "files", "that", "have", "been", "successfully", "uploaded", "Returns", ":", "None" ]
python
train
46.857143
echinopsii/net.echinopsii.ariane.community.cli.python3
ariane_clip3/mapping.py
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/mapping.py#L378-L390
def json_2_cluster(json_obj): """ transform json from Ariane server to local object :param json_obj: json from Ariane Server :return: transformed cluster """ LOGGER.debug("Cluster.json_2_cluster") return Cluster( cid=json_obj['clusterID'], name=json_obj['clusterName'], containers_id=json_obj['clusterContainersID'], ignore_sync=True )
[ "def", "json_2_cluster", "(", "json_obj", ")", ":", "LOGGER", ".", "debug", "(", "\"Cluster.json_2_cluster\"", ")", "return", "Cluster", "(", "cid", "=", "json_obj", "[", "'clusterID'", "]", ",", "name", "=", "json_obj", "[", "'clusterName'", "]", ",", "cont...
transform json from Ariane server to local object :param json_obj: json from Ariane Server :return: transformed cluster
[ "transform", "json", "from", "Ariane", "server", "to", "local", "object", ":", "param", "json_obj", ":", "json", "from", "Ariane", "Server", ":", "return", ":", "transformed", "cluster" ]
python
train
33.461538
portfors-lab/sparkle
sparkle/gui/stim/qauto_parameter_model.py
https://github.com/portfors-lab/sparkle/blob/5fad1cf2bec58ec6b15d91da20f6236a74826110/sparkle/gui/stim/qauto_parameter_model.py#L135-L142
def checkValidCell(self, index): """Asks the model if the value at *index* is valid See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>` """ col = index.column() row = index.row() return self.model.isFieldValid(row, self._headers[index.column()])
[ "def", "checkValidCell", "(", "self", ",", "index", ")", ":", "col", "=", "index", ".", "column", "(", ")", "row", "=", "index", ".", "row", "(", ")", "return", "self", ".", "model", ".", "isFieldValid", "(", "row", ",", "self", ".", "_headers", "[...
Asks the model if the value at *index* is valid See :meth:`isFieldValid<sparkle.stim.auto_parameter_model.AutoParameterModel.isFieldValid>`
[ "Asks", "the", "model", "if", "the", "value", "at", "*", "index", "*", "is", "valid" ]
python
train
40.875
Becksteinlab/GromacsWrapper
gromacs/tools.py
https://github.com/Becksteinlab/GromacsWrapper/blob/d4f9a8cb6f48292732cf7c7e4ef4a6d2ccbc51b9/gromacs/tools.py#L244-L276
def load_v4_tools(): """ Load Gromacs 4.x tools automatically using some heuristic. Tries to load tools (1) in configured tool groups (2) and fails back to automatic detection from ``GMXBIN`` (3) then to a prefilled list. Also load any extra tool configured in ``~/.gromacswrapper.cfg`` :return: dict mapping tool names to GromacsCommand classes """ logger.debug("Loading v4 tools...") names = config.get_tool_names() if len(names) == 0 and 'GMXBIN' in os.environ: names = find_executables(os.environ['GMXBIN']) if len(names) == 0 or len(names) > len(V4TOOLS) * 4: names = list(V4TOOLS) names.extend(config.get_extra_tool_names()) tools = {} for name in names: fancy = make_valid_identifier(name) tools[fancy] = tool_factory(fancy, name, None) if not tools: errmsg = "Failed to load v4 tools" logger.debug(errmsg) raise GromacsToolLoadingError(errmsg) logger.debug("Loaded {0} v4 tools successfully!".format(len(tools))) return tools
[ "def", "load_v4_tools", "(", ")", ":", "logger", ".", "debug", "(", "\"Loading v4 tools...\"", ")", "names", "=", "config", ".", "get_tool_names", "(", ")", "if", "len", "(", "names", ")", "==", "0", "and", "'GMXBIN'", "in", "os", ".", "environ", ":", ...
Load Gromacs 4.x tools automatically using some heuristic. Tries to load tools (1) in configured tool groups (2) and fails back to automatic detection from ``GMXBIN`` (3) then to a prefilled list. Also load any extra tool configured in ``~/.gromacswrapper.cfg`` :return: dict mapping tool names to GromacsCommand classes
[ "Load", "Gromacs", "4", ".", "x", "tools", "automatically", "using", "some", "heuristic", "." ]
python
valid
31.242424
CEA-COSMIC/ModOpt
modopt/base/wrappers.py
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/base/wrappers.py#L19-L55
def add_args_kwargs(func): """Add Args and Kwargs This wrapper adds support for additional arguments and keyword arguments to any callable function Parameters ---------- func : function Callable function Returns ------- function wrapper """ @wraps(func) def wrapper(*args, **kwargs): props = argspec(func) # if 'args' not in props: if isinstance(props[1], type(None)): args = args[:len(props[0])] if ((not isinstance(props[2], type(None))) or (not isinstance(props[3], type(None)))): return func(*args, **kwargs) else: return func(*args) return wrapper
[ "def", "add_args_kwargs", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "props", "=", "argspec", "(", "func", ")", "# if 'args' not in props:", "if", "isinstance", "(", "pr...
Add Args and Kwargs This wrapper adds support for additional arguments and keyword arguments to any callable function Parameters ---------- func : function Callable function Returns ------- function wrapper
[ "Add", "Args", "and", "Kwargs" ]
python
train
18.405405
yunojuno/elasticsearch-django
elasticsearch_django/management/commands/__init__.py
https://github.com/yunojuno/elasticsearch-django/blob/e8d98d32bcd77f1bedb8f1a22b6523ca44ffd489/elasticsearch_django/management/commands/__init__.py#L39-L49
def handle(self, *args, **options): """Run do_index_command on each specified index and log the output.""" for index in options.pop("indexes"): data = {} try: data = self.do_index_command(index, **options) except TransportError as ex: logger.warning("ElasticSearch threw an error: %s", ex) data = {"index": index, "status": ex.status_code, "reason": ex.error} finally: logger.info(data)
[ "def", "handle", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "for", "index", "in", "options", ".", "pop", "(", "\"indexes\"", ")", ":", "data", "=", "{", "}", "try", ":", "data", "=", "self", ".", "do_index_command", "(", "...
Run do_index_command on each specified index and log the output.
[ "Run", "do_index_command", "on", "each", "specified", "index", "and", "log", "the", "output", "." ]
python
train
45.818182
singularityhub/singularity-python
singularity/views/trees.py
https://github.com/singularityhub/singularity-python/blob/498c3433724b332f7493fec632d8daf479f47b82/singularity/views/trees.py#L250-L284
def make_interactive_tree(matrix=None,labels=None): '''make interactive tree will return complete html for an interactive tree :param title: a title for the plot, if not defined, will be left out. ''' from scipy.cluster.hierarchy import ( dendrogram, linkage, to_tree ) d3 = None from scipy.cluster.hierarchy import cophenet from scipy.spatial.distance import pdist if isinstance(matrix,pandas.DataFrame): Z = linkage(matrix, 'ward') # clusters T = to_tree(Z, rd=False) if labels == None: labels = matrix.index.tolist() lookup = dict(zip(range(len(labels)), labels)) # Create a dendrogram object without plotting dend = dendrogram(Z,no_plot=True, orientation="right", leaf_rotation=90., # rotates the x axis labels leaf_font_size=8., # font size for the x axis labels labels=labels) d3 = dict(children=[], name="root") add_node(T, d3) label_tree(d3["children"][0],lookup) else: bot.warning('Please provide data as pandas Data Frame.') return d3
[ "def", "make_interactive_tree", "(", "matrix", "=", "None", ",", "labels", "=", "None", ")", ":", "from", "scipy", ".", "cluster", ".", "hierarchy", "import", "(", "dendrogram", ",", "linkage", ",", "to_tree", ")", "d3", "=", "None", "from", "scipy", "."...
make interactive tree will return complete html for an interactive tree :param title: a title for the plot, if not defined, will be left out.
[ "make", "interactive", "tree", "will", "return", "complete", "html", "for", "an", "interactive", "tree", ":", "param", "title", ":", "a", "title", "for", "the", "plot", "if", "not", "defined", "will", "be", "left", "out", "." ]
python
train
33.314286
OLC-Bioinformatics/sipprverse
cgecore/utility.py
https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/cgecore/utility.py#L223-L318
def seqs_from_file(filename, exit_on_err=False, return_qual=False): """Extract sequences from a file Name: seqs_from_file Author(s): Martin C F Thomsen Date: 18 Jul 2013 Description: Iterator which extract sequence data from the input file Args: filename: string which contain a path to the input file Supported Formats: fasta, fastq USAGE: >>> import os, sys >>> # Create fasta test file >>> file_content = ('>head1 desc1\nthis_is_seq_1\n>head2 desc2\n' 'this_is_seq_2\n>head3 desc3\nthis_is_seq_3\n') >>> with open_('test.fsa', 'w') as f: f.write(file_content) >>> # Parse and print the fasta file >>> for seq, name, desc in SeqsFromFile('test.fsa'): ... print ">%s %s\n%s"%(name, desc, seq) ... >head1 desc1 this_is_seq_1 >head2 desc2 this_is_seq_2 >head3 desc3 this_is_seq_3 """ # VALIDATE INPUT if not isinstance(filename, str): msg = 'Filename has to be a string.' if exit_on_err: sys.stderr.write('Error: %s\n'%msg) sys.exit(1) else: raise IOError(msg) if not os.path.exists(filename): msg = 'File "%s" does not exist.'%filename if exit_on_err: sys.stderr.write('Error: %s\n'%msg) sys.exit(1) else: raise IOError(msg) # EXTRACT DATA with open_(filename,"rt") as f: query_seq_segments = [] seq, name, desc, qual = '', '', '', '' add_segment = query_seq_segments.append for l in f: if len(l.strip()) == 0: continue #sys.stderr.write("%s\n"%line) fields=l.strip().split() if l.startswith(">"): # FASTA HEADER FOUND if query_seq_segments != []: # YIELD SEQUENCE AND RESET seq = ''.join(query_seq_segments) yield (seq, name, desc) seq, name, desc = '', '', '' del query_seq_segments[:] name = fields[0][1:] desc = ' '.join(fields[1:]) elif l.startswith("@"): # FASTQ HEADER FOUND name = fields[0][1:] desc = ' '.join(fields[1:]) try: # EXTRACT FASTQ SEQUENCE seq = next(f).strip().split()[0] # SKIP SECOND HEADER LINE AND QUALITY SCORES l = next(f) qual = next(f).strip() # Qualities except: break else: # YIELD SEQUENCE AND RESET if return_qual: yield (seq, qual, name, desc) else: yield (seq, name, desc) seq, name, desc, qual = '', '', '', '' elif len(fields[0])>0: # EXTRACT FASTA SEQUENCE add_segment(fields[0]) # CHECK FOR LAST FASTA SEQUENCE if query_seq_segments != []: # YIELD SEQUENCE seq = ''.join(query_seq_segments) yield (seq, name, desc)
[ "def", "seqs_from_file", "(", "filename", ",", "exit_on_err", "=", "False", ",", "return_qual", "=", "False", ")", ":", "# VALIDATE INPUT", "if", "not", "isinstance", "(", "filename", ",", "str", ")", ":", "msg", "=", "'Filename has to be a string.'", "if", "e...
Extract sequences from a file Name: seqs_from_file Author(s): Martin C F Thomsen Date: 18 Jul 2013 Description: Iterator which extract sequence data from the input file Args: filename: string which contain a path to the input file Supported Formats: fasta, fastq USAGE: >>> import os, sys >>> # Create fasta test file >>> file_content = ('>head1 desc1\nthis_is_seq_1\n>head2 desc2\n' 'this_is_seq_2\n>head3 desc3\nthis_is_seq_3\n') >>> with open_('test.fsa', 'w') as f: f.write(file_content) >>> # Parse and print the fasta file >>> for seq, name, desc in SeqsFromFile('test.fsa'): ... print ">%s %s\n%s"%(name, desc, seq) ... >head1 desc1 this_is_seq_1 >head2 desc2 this_is_seq_2 >head3 desc3 this_is_seq_3
[ "Extract", "sequences", "from", "a", "file", "Name", ":", "seqs_from_file", "Author", "(", "s", ")", ":", "Martin", "C", "F", "Thomsen", "Date", ":", "18", "Jul", "2013", "Description", ":", "Iterator", "which", "extract", "sequence", "data", "from", "the"...
python
train
30.614583
getsentry/rb
rb/cluster.py
https://github.com/getsentry/rb/blob/569d1d13311f6c04bae537fc17e75da430e4ec45/rb/cluster.py#L285-L295
def all(self, timeout=None, max_concurrency=64, auto_batch=True): """Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb() """ return self.fanout('all', timeout=timeout, max_concurrency=max_concurrency, auto_batch=auto_batch)
[ "def", "all", "(", "self", ",", "timeout", "=", "None", ",", "max_concurrency", "=", "64", ",", "auto_batch", "=", "True", ")", ":", "return", "self", ".", "fanout", "(", "'all'", ",", "timeout", "=", "timeout", ",", "max_concurrency", "=", "max_concurre...
Fanout to all hosts. Works otherwise exactly like :meth:`fanout`. Example:: with cluster.all() as client: client.flushdb()
[ "Fanout", "to", "all", "hosts", ".", "Works", "otherwise", "exactly", "like", ":", "meth", ":", "fanout", "." ]
python
train
36.454545
mback2k/python-appengine-auth
social_appengine_auth/backends.py
https://github.com/mback2k/python-appengine-auth/blob/dd27a0c53c7bebe147f7a6e3606c67ec673ac4d6/social_appengine_auth/backends.py#L42-L48
def user_data(self, access_token, *args, **kwargs): """Load user data from OAuth Profile Google App Engine App""" url = GOOGLE_APPENGINE_PROFILE_V1 auth = self.oauth_auth(access_token) return self.get_json(url, auth=auth, params=auth )
[ "def", "user_data", "(", "self", ",", "access_token", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "url", "=", "GOOGLE_APPENGINE_PROFILE_V1", "auth", "=", "self", ".", "oauth_auth", "(", "access_token", ")", "return", "self", ".", "get_json", "(", ...
Load user data from OAuth Profile Google App Engine App
[ "Load", "user", "data", "from", "OAuth", "Profile", "Google", "App", "Engine", "App" ]
python
train
40.142857
cloudera/cm_api
nagios/cm_nagios.py
https://github.com/cloudera/cm_api/blob/5d2512375bd94684b4da36df9e0d9177865ffcbb/nagios/cm_nagios.py#L283-L291
def submit_status_external_cmd(cmd_file, status_file): ''' Submits the status lines in the status_file to Nagios' external cmd file. ''' try: with open(cmd_file, 'a') as cmd_file: cmd_file.write(status_file.read()) except IOError: exit("Fatal error: Unable to write to Nagios external command file '%s'.\n" "Make sure that the file exists and is writable." % (cmd_file,))
[ "def", "submit_status_external_cmd", "(", "cmd_file", ",", "status_file", ")", ":", "try", ":", "with", "open", "(", "cmd_file", ",", "'a'", ")", "as", "cmd_file", ":", "cmd_file", ".", "write", "(", "status_file", ".", "read", "(", ")", ")", "except", "...
Submits the status lines in the status_file to Nagios' external cmd file.
[ "Submits", "the", "status", "lines", "in", "the", "status_file", "to", "Nagios", "external", "cmd", "file", "." ]
python
train
43.777778
nickmckay/LiPD-utilities
Python/lipd/__init__.py
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L734-L753
def getMetadata(L): """ Get metadata from a LiPD data in memory | Example | m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict L: One LiPD record :return dict d: LiPD record (metadata only) """ _l = {} try: # Create a copy. Do not affect the original data. _l = copy.deepcopy(L) # Remove values fields _l = rm_values_fields(_l) except Exception as e: # Input likely not formatted correctly, though other problems can occur. print("Error: Unable to get data. Please check that input is LiPD data: {}".format(e)) return _l
[ "def", "getMetadata", "(", "L", ")", ":", "_l", "=", "{", "}", "try", ":", "# Create a copy. Do not affect the original data.", "_l", "=", "copy", ".", "deepcopy", "(", "L", ")", "# Remove values fields", "_l", "=", "rm_values_fields", "(", "_l", ")", "except"...
Get metadata from a LiPD data in memory | Example | m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"]) :param dict L: One LiPD record :return dict d: LiPD record (metadata only)
[ "Get", "metadata", "from", "a", "LiPD", "data", "in", "memory" ]
python
train
30.85
artisanofcode/python-broadway
broadway/app.py
https://github.com/artisanofcode/python-broadway/blob/a051ca5a922ecb38a541df59e8740e2a047d9a4a/broadway/app.py#L128-L146
def add_extension(self, extension): """ Specify a broadway extension to initialise .. code-block:: python factory = Factory() factory.add_extension('broadway_sqlalchemy') :param extension: import path to extension :type extension: str """ instance = werkzeug.utils.import_string(extension) if hasattr(instance, 'register'): instance.register(self) self._extensions.append(instance)
[ "def", "add_extension", "(", "self", ",", "extension", ")", ":", "instance", "=", "werkzeug", ".", "utils", ".", "import_string", "(", "extension", ")", "if", "hasattr", "(", "instance", ",", "'register'", ")", ":", "instance", ".", "register", "(", "self"...
Specify a broadway extension to initialise .. code-block:: python factory = Factory() factory.add_extension('broadway_sqlalchemy') :param extension: import path to extension :type extension: str
[ "Specify", "a", "broadway", "extension", "to", "initialise" ]
python
train
25.105263
open-homeautomation/miflora
miflora/miflora_poller.py
https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/miflora/miflora_poller.py#L57-L87
def fill_cache(self): """Fill the cache with new data from the sensor.""" _LOGGER.debug('Filling cache with new sensor data.') try: firmware_version = self.firmware_version() except BluetoothBackendException: # If a sensor doesn't work, wait 5 minutes before retrying self._last_read = datetime.now() - self._cache_timeout + \ timedelta(seconds=300) raise with self._bt_interface.connect(self._mac) as connection: if firmware_version >= "2.6.6": # for the newer models a magic number must be written before we can read the current data try: connection.write_handle(_HANDLE_WRITE_MODE_CHANGE, _DATA_MODE_CHANGE) # pylint: disable=no-member # If a sensor doesn't work, wait 5 minutes before retrying except BluetoothBackendException: self._last_read = datetime.now() - self._cache_timeout + \ timedelta(seconds=300) return self._cache = connection.read_handle(_HANDLE_READ_SENSOR_DATA) # pylint: disable=no-member _LOGGER.debug('Received result for handle %s: %s', _HANDLE_READ_SENSOR_DATA, self._format_bytes(self._cache)) self._check_data() if self.cache_available(): self._last_read = datetime.now() else: # If a sensor doesn't work, wait 5 minutes before retrying self._last_read = datetime.now() - self._cache_timeout + \ timedelta(seconds=300)
[ "def", "fill_cache", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "'Filling cache with new sensor data.'", ")", "try", ":", "firmware_version", "=", "self", ".", "firmware_version", "(", ")", "except", "BluetoothBackendException", ":", "# If a sensor doesn't w...
Fill the cache with new data from the sensor.
[ "Fill", "the", "cache", "with", "new", "data", "from", "the", "sensor", "." ]
python
train
53
rainwoodman/kdcount
kdcount/sphere.py
https://github.com/rainwoodman/kdcount/blob/483548f6d27a4f245cd5d98880b5f4edd6cc8dc1/kdcount/sphere.py#L65-L153
def bootstrap(nside, rand, nbar, *data): """ This function will bootstrap data based on the sky coverage of rand. It is different from bootstrap in the traditional sense, but for correlation functions it gives the correct answer with less computation. nbar : number density of rand, used to estimate the effective area of a pixel nside : number of healpix pixels per side to use *data : a list of data -- will be binned on the same regions. small regions (incomplete pixels) are combined such that the total area is about the same (a healpix pixel) in each returned boot strap sample Yields: area, random, *data rand and *data are in (RA, DEC) Example: >>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2): >>> # Do stuff >>> pass """ def split(data, indices, axis): """ This function splits array. It fixes the bug in numpy that zero length array are improperly handled. In the future this will be fixed. """ s = [] s.append(slice(0, indices[0])) for i in range(len(indices) - 1): s.append(slice(indices[i], indices[i+1])) s.append(slice(indices[-1], None)) rt = [] for ss in s: ind = [slice(None, None, None) for i in range(len(data.shape))] ind[axis] = ss ind = tuple(ind) rt.append(data[ind]) return rt def hpsplit(nside, data): # data is (RA, DEC) RA, DEC = data pix = radec2pix(nside, RA, DEC) n = numpy.bincount(pix) a = numpy.argsort(pix) data = numpy.array(data)[:, a] rt = split(data, n.cumsum(), axis=-1) return rt # mean area of sky. Abar = 41252.96 / nside2npix(nside) rand = hpsplit(nside, rand) if len(data) > 0: data = [list(i) for i in zip(*[hpsplit(nside, d1) for d1 in data])] else: data = [[] for i in range(len(rand))] heap = [] j = 0 for r, d in zip(rand, data): if len(r[0]) == 0: continue a = 1.0 * len(r[0]) / nbar j = j + 1 if len(heap) == 0: heapq.heappush(heap, (a, j, r, d)) else: a0, j0, r0, d0 = heapq.heappop(heap) if a0 + a < Abar: a0 += a d0 = [ numpy.concatenate((d0[i], d[i]), axis=-1) for i in range(len(d)) ] r0 = numpy.concatenate((r0, r), axis=-1) else: heapq.heappush(heap, (a, j, r, d)) heapq.heappush(heap, (a0, j0, r0, d0)) for i in range(len(heap)): area, j, r, d = heapq.heappop(heap) rt = [area, r] + d yield rt
[ "def", "bootstrap", "(", "nside", ",", "rand", ",", "nbar", ",", "*", "data", ")", ":", "def", "split", "(", "data", ",", "indices", ",", "axis", ")", ":", "\"\"\" This function splits array. It fixes the bug\n in numpy that zero length array are improperly h...
This function will bootstrap data based on the sky coverage of rand. It is different from bootstrap in the traditional sense, but for correlation functions it gives the correct answer with less computation. nbar : number density of rand, used to estimate the effective area of a pixel nside : number of healpix pixels per side to use *data : a list of data -- will be binned on the same regions. small regions (incomplete pixels) are combined such that the total area is about the same (a healpix pixel) in each returned boot strap sample Yields: area, random, *data rand and *data are in (RA, DEC) Example: >>> for area, ran, data1, data2 in bootstrap(4, ran, 100., data1, data2): >>> # Do stuff >>> pass
[ "This", "function", "will", "bootstrap", "data", "based", "on", "the", "sky", "coverage", "of", "rand", ".", "It", "is", "different", "from", "bootstrap", "in", "the", "traditional", "sense", "but", "for", "correlation", "functions", "it", "gives", "the", "c...
python
train
30.955056
google/grr
grr/server/grr_response_server/databases/mem_cronjobs.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/databases/mem_cronjobs.py#L165-L173
def DeleteOldCronJobRuns(self, cutoff_timestamp): """Deletes cron job runs for a given job id.""" deleted = 0 for run in list(itervalues(self.cronjob_runs)): if run.timestamp < cutoff_timestamp: del self.cronjob_runs[(run.cron_job_id, run.run_id)] deleted += 1 return deleted
[ "def", "DeleteOldCronJobRuns", "(", "self", ",", "cutoff_timestamp", ")", ":", "deleted", "=", "0", "for", "run", "in", "list", "(", "itervalues", "(", "self", ".", "cronjob_runs", ")", ")", ":", "if", "run", ".", "timestamp", "<", "cutoff_timestamp", ":",...
Deletes cron job runs for a given job id.
[ "Deletes", "cron", "job", "runs", "for", "a", "given", "job", "id", "." ]
python
train
34
quiltdata/quilt
compiler/quilt/tools/store.py
https://github.com/quiltdata/quilt/blob/651853e7e89a8af86e0ff26167e752efa5878c12/compiler/quilt/tools/store.py#L493-L499
def get_file(self, hash_list): """ Returns the path of the file - but verifies that the hash is actually present. """ assert len(hash_list) == 1 self._check_hashes(hash_list) return self.object_path(hash_list[0])
[ "def", "get_file", "(", "self", ",", "hash_list", ")", ":", "assert", "len", "(", "hash_list", ")", "==", "1", "self", ".", "_check_hashes", "(", "hash_list", ")", "return", "self", ".", "object_path", "(", "hash_list", "[", "0", "]", ")" ]
Returns the path of the file - but verifies that the hash is actually present.
[ "Returns", "the", "path", "of", "the", "file", "-", "but", "verifies", "that", "the", "hash", "is", "actually", "present", "." ]
python
train
36.285714
goerz/clusterjob
clusterjob/backends/lsf.py
https://github.com/goerz/clusterjob/blob/361760d1a6dd3cbde49c5c2158a3acd0c314a749/clusterjob/backends/lsf.py#L92-L106
def get_status(self, response, finished=False): """Given the stdout from the command returned by :meth:`cmd_status`, return one of the status code defined in :mod:`clusterjob.status`""" status_pos = 0 for line in response.split("\n"): if line.startswith('JOBID'): try: status_pos = line.find('STAT') except ValueError: return None else: status = line[status_pos:].split()[0] if status in self.status_mapping: return self.status_mapping[status] return None
[ "def", "get_status", "(", "self", ",", "response", ",", "finished", "=", "False", ")", ":", "status_pos", "=", "0", "for", "line", "in", "response", ".", "split", "(", "\"\\n\"", ")", ":", "if", "line", ".", "startswith", "(", "'JOBID'", ")", ":", "t...
Given the stdout from the command returned by :meth:`cmd_status`, return one of the status code defined in :mod:`clusterjob.status`
[ "Given", "the", "stdout", "from", "the", "command", "returned", "by", ":", "meth", ":", "cmd_status", "return", "one", "of", "the", "status", "code", "defined", "in", ":", "mod", ":", "clusterjob", ".", "status" ]
python
train
41.933333
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L7973-L8078
def read_tags(fh, byteorder, offsetsize, tagnames, customtags=None, maxifds=None): """Read tags from chain of IFDs and return as list of dicts. The file handle position must be at a valid IFD header. """ if offsetsize == 4: offsetformat = byteorder+'I' tagnosize = 2 tagnoformat = byteorder+'H' tagsize = 12 tagformat1 = byteorder+'HH' tagformat2 = byteorder+'I4s' elif offsetsize == 8: offsetformat = byteorder+'Q' tagnosize = 8 tagnoformat = byteorder+'Q' tagsize = 20 tagformat1 = byteorder+'HH' tagformat2 = byteorder+'Q8s' else: raise ValueError('invalid offset size') if customtags is None: customtags = {} if maxifds is None: maxifds = 2**32 result = [] unpack = struct.unpack offset = fh.tell() while len(result) < maxifds: # loop over IFDs try: tagno = unpack(tagnoformat, fh.read(tagnosize))[0] if tagno > 4096: raise TiffFileError('suspicious number of tags') except Exception: log.warning('read_tags: corrupted tag list at offset %i', offset) break tags = {} data = fh.read(tagsize * tagno) pos = fh.tell() index = 0 for _ in range(tagno): code, type_ = unpack(tagformat1, data[index:index+4]) count, value = unpack(tagformat2, data[index+4:index+tagsize]) index += tagsize name = tagnames.get(code, str(code)) try: dtype = TIFF.DATA_FORMATS[type_] except KeyError: raise TiffFileError('unknown tag data type %i' % type_) fmt = '%s%i%s' % (byteorder, count * int(dtype[0]), dtype[1]) size = struct.calcsize(fmt) if size > offsetsize or code in customtags: offset = unpack(offsetformat, value)[0] if offset < 8 or offset > fh.size - size: raise TiffFileError('invalid tag value offset %i' % offset) fh.seek(offset) if code in customtags: readfunc = customtags[code][1] value = readfunc(fh, byteorder, dtype, count, offsetsize) elif type_ == 7 or (count > 1 and dtype[-1] == 'B'): value = read_bytes(fh, byteorder, dtype, count, offsetsize) elif code in tagnames or dtype[-1] == 's': value = unpack(fmt, fh.read(size)) else: value = read_numpy(fh, byteorder, dtype, count, offsetsize) elif dtype[-1] == 'B' or type_ == 7: value = value[:size] else: value = unpack(fmt, value[:size]) if code not in customtags and code not in TIFF.TAG_TUPLE: if len(value) == 1: value = value[0] if type_ != 7 and dtype[-1] == 's' and isinstance(value, bytes): # TIFF ASCII fields can contain multiple strings, # each terminated with a NUL try: value = bytes2str(stripascii(value).strip()) except UnicodeDecodeError: log.warning( 'read_tags: coercing invalid ASCII to bytes (tag %i)', code) tags[name] = value result.append(tags) # read offset to next page fh.seek(pos) offset = unpack(offsetformat, fh.read(offsetsize))[0] if offset == 0: break if offset >= fh.size: log.warning('read_tags: invalid page offset (%i)', offset) break fh.seek(offset) if result and maxifds == 1: result = result[0] return result
[ "def", "read_tags", "(", "fh", ",", "byteorder", ",", "offsetsize", ",", "tagnames", ",", "customtags", "=", "None", ",", "maxifds", "=", "None", ")", ":", "if", "offsetsize", "==", "4", ":", "offsetformat", "=", "byteorder", "+", "'I'", "tagnosize", "="...
Read tags from chain of IFDs and return as list of dicts. The file handle position must be at a valid IFD header.
[ "Read", "tags", "from", "chain", "of", "IFDs", "and", "return", "as", "list", "of", "dicts", "." ]
python
train
35.641509
allenai/allennlp
allennlp/data/dataset_readers/coreference_resolution/conll.py
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset_readers/coreference_resolution/conll.py#L18-L47
def canonicalize_clusters(clusters: DefaultDict[int, List[Tuple[int, int]]]) -> List[List[Tuple[int, int]]]: """ The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters containing the identical spans. """ merged_clusters: List[Set[Tuple[int, int]]] = [] for cluster in clusters.values(): cluster_with_overlapping_mention = None for mention in cluster: # Look at clusters we have already processed to # see if they contain a mention in the current # cluster for comparison. for cluster2 in merged_clusters: if mention in cluster2: # first cluster in merged clusters # which contains this mention. cluster_with_overlapping_mention = cluster2 break # Already encountered overlap - no need to keep looking. if cluster_with_overlapping_mention is not None: break if cluster_with_overlapping_mention is not None: # Merge cluster we are currently processing into # the cluster in the processed list. cluster_with_overlapping_mention.update(cluster) else: merged_clusters.append(set(cluster)) return [list(c) for c in merged_clusters]
[ "def", "canonicalize_clusters", "(", "clusters", ":", "DefaultDict", "[", "int", ",", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", "]", ")", "->", "List", "[", "List", "[", "Tuple", "[", "int", ",", "int", "]", "]", "]", ":", "merged_clu...
The CONLL 2012 data includes 2 annotated spans which are identical, but have different ids. This checks all clusters for spans which are identical, and if it finds any, merges the clusters containing the identical spans.
[ "The", "CONLL", "2012", "data", "includes", "2", "annotated", "spans", "which", "are", "identical", "but", "have", "different", "ids", ".", "This", "checks", "all", "clusters", "for", "spans", "which", "are", "identical", "and", "if", "it", "finds", "any", ...
python
train
47.666667
dagster-io/dagster
python_modules/dagster/dagster/core/types/field.py
https://github.com/dagster-io/dagster/blob/4119f8c773089de64831b1dfb9e168e353d401dc/python_modules/dagster/dagster/core/types/field.py#L34-L66
def Field( dagster_type, default_value=FIELD_NO_DEFAULT_PROVIDED, is_optional=INFER_OPTIONAL_COMPOSITE_FIELD, is_secret=False, description=None, ): ''' The schema for configuration data that describes the type, optionality, defaults, and description. Args: dagster_type (DagsterType): A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})` default_value (Any): A default value to use that respects the schema provided via dagster_type is_optional (bool): Whether the presence of this field is optional despcription (str): ''' config_type = resolve_to_config_type(dagster_type) if not config_type: raise DagsterInvalidDefinitionError( ( 'Attempted to pass {value_repr} to a Field that expects a valid ' 'dagster type usable in config (e.g. Dict, NamedDict, Int, String et al).' ).format(value_repr=repr(dagster_type)) ) return FieldImpl( config_type=resolve_to_config_type(dagster_type), default_value=default_value, is_optional=is_optional, is_secret=is_secret, description=description, )
[ "def", "Field", "(", "dagster_type", ",", "default_value", "=", "FIELD_NO_DEFAULT_PROVIDED", ",", "is_optional", "=", "INFER_OPTIONAL_COMPOSITE_FIELD", ",", "is_secret", "=", "False", ",", "description", "=", "None", ",", ")", ":", "config_type", "=", "resolve_to_co...
The schema for configuration data that describes the type, optionality, defaults, and description. Args: dagster_type (DagsterType): A ``DagsterType`` describing the schema of this field, ie `Dict({'example': Field(String)})` default_value (Any): A default value to use that respects the schema provided via dagster_type is_optional (bool): Whether the presence of this field is optional despcription (str):
[ "The", "schema", "for", "configuration", "data", "that", "describes", "the", "type", "optionality", "defaults", "and", "description", "." ]
python
test
36.818182
mikicz/arca
arca/utils.py
https://github.com/mikicz/arca/blob/e67fdc00be473ecf8ec16d024e1a3f2c47ca882c/arca/utils.py#L96-L139
def get(self, *keys: str, default: Any = NOT_SET) -> Any: """ Returns values from the settings in the order of keys, the first value encountered is used. Example: >>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2}) >>> settings.get("one") 1 >>> settings.get("one", "two") 1 >>> settings.get("two", "one") 2 >>> settings.get("three", "one") 1 >>> settings.get("three", default=3) 3 >>> settings.get("three") Traceback (most recent call last): ... KeyError: :param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key that has a value is returned. :param default: If none of the ``options`` aren't set, return this value. :return: A value from the settings or the default. :raise ValueError: If no keys are provided. :raise KeyError: If none of the keys are set and no default is provided. """ if not len(keys): raise ValueError("At least one key must be provided.") for option in keys: key = f"{self.PREFIX}_{option.upper()}" if key in self._data: return self._data[key] if default is NOT_SET: raise KeyError("None of the following key is present in settings and no default is set: {}".format( ", ".join(keys) )) return default
[ "def", "get", "(", "self", ",", "*", "keys", ":", "str", ",", "default", ":", "Any", "=", "NOT_SET", ")", "->", "Any", ":", "if", "not", "len", "(", "keys", ")", ":", "raise", "ValueError", "(", "\"At least one key must be provided.\"", ")", "for", "op...
Returns values from the settings in the order of keys, the first value encountered is used. Example: >>> settings = Settings({"ARCA_ONE": 1, "ARCA_TWO": 2}) >>> settings.get("one") 1 >>> settings.get("one", "two") 1 >>> settings.get("two", "one") 2 >>> settings.get("three", "one") 1 >>> settings.get("three", default=3) 3 >>> settings.get("three") Traceback (most recent call last): ... KeyError: :param keys: One or more keys to get from settings. If multiple keys are provided, the value of the first key that has a value is returned. :param default: If none of the ``options`` aren't set, return this value. :return: A value from the settings or the default. :raise ValueError: If no keys are provided. :raise KeyError: If none of the keys are set and no default is provided.
[ "Returns", "values", "from", "the", "settings", "in", "the", "order", "of", "keys", "the", "first", "value", "encountered", "is", "used", "." ]
python
train
33.295455
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L2293-L2353
def index(self, val, start=None, stop=None): """ Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice indices. """ _len = self._len if not _len: raise ValueError('{0!r} is not in list'.format(val)) if start is None: start = 0 if start < 0: start += _len if start < 0: start = 0 if stop is None: stop = _len if stop < 0: stop += _len if stop > _len: stop = _len if stop <= start: raise ValueError('{0!r} is not in list'.format(val)) _maxes = self._maxes key = self._key(val) pos = bisect_left(_maxes, key) if pos == len(_maxes): raise ValueError('{0!r} is not in list'.format(val)) stop -= 1 _lists = self._lists _keys = self._keys idx = bisect_left(_keys[pos], key) len_keys = len(_keys) len_sublist = len(_keys[pos]) while True: if _keys[pos][idx] != key: raise ValueError('{0!r} is not in list'.format(val)) if _lists[pos][idx] == val: loc = self._loc(pos, idx) if start <= loc <= stop: return loc elif loc > stop: break idx += 1 if idx == len_sublist: pos += 1 if pos == len_keys: raise ValueError('{0!r} is not in list'.format(val)) len_sublist = len(_keys[pos]) idx = 0 raise ValueError('{0!r} is not in list'.format(val))
[ "def", "index", "(", "self", ",", "val", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "_len", "=", "self", ".", "_len", "if", "not", "_len", ":", "raise", "ValueError", "(", "'{0!r} is not in list'", ".", "format", "(", "val", ")", ...
Return the smallest *k* such that L[k] == val and i <= k < j`. Raises ValueError if *val* is not present. *stop* defaults to the end of the list. *start* defaults to the beginning. Negative indices are supported, as for slice indices.
[ "Return", "the", "smallest", "*", "k", "*", "such", "that", "L", "[", "k", "]", "==", "val", "and", "i", "<", "=", "k", "<", "j", ".", "Raises", "ValueError", "if", "*", "val", "*", "is", "not", "present", ".", "*", "stop", "*", "defaults", "to...
python
train
29.688525
theolind/pymysensors
mysensors/__init__.py
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/__init__.py#L433-L437
def handle_line(self, line): """Handle incoming string data one line at a time.""" if not self.gateway.can_log: _LOGGER.debug('Receiving %s', line) self.gateway.add_job(self.gateway.logic, line)
[ "def", "handle_line", "(", "self", ",", "line", ")", ":", "if", "not", "self", ".", "gateway", ".", "can_log", ":", "_LOGGER", ".", "debug", "(", "'Receiving %s'", ",", "line", ")", "self", ".", "gateway", ".", "add_job", "(", "self", ".", "gateway", ...
Handle incoming string data one line at a time.
[ "Handle", "incoming", "string", "data", "one", "line", "at", "a", "time", "." ]
python
train
45.2
python-bonobo/bonobo
bonobo/util/api.py
https://github.com/python-bonobo/bonobo/blob/70c8e62c4a88576976e5b52e58d380d6e3227ab4/bonobo/util/api.py#L9-L26
def register(self, x, graph=False): """Register a function as being part of an API, then returns the original function.""" if graph: # This function must comply to the "graph" API interface, meaning it can bahave like bonobo.run. from inspect import signature parameters = list(signature(x).parameters) required_parameters = {"plugins", "services", "strategy"} assert ( len(parameters) > 0 and parameters[0] == "graph" ), 'First parameter of a graph api function must be "graph".' assert ( required_parameters.intersection(parameters) == required_parameters ), "Graph api functions must define the following parameters: " + ", ".join(sorted(required_parameters)) self.__all__.append(get_name(x)) return x
[ "def", "register", "(", "self", ",", "x", ",", "graph", "=", "False", ")", ":", "if", "graph", ":", "# This function must comply to the \"graph\" API interface, meaning it can bahave like bonobo.run.", "from", "inspect", "import", "signature", "parameters", "=", "list", ...
Register a function as being part of an API, then returns the original function.
[ "Register", "a", "function", "as", "being", "part", "of", "an", "API", "then", "returns", "the", "original", "function", "." ]
python
train
47.222222
sjkingo/virtualenv-api
virtualenvapi/manage.py
https://github.com/sjkingo/virtualenv-api/blob/146a181e540ae2ae89c2542497dea0cedbc78839/virtualenvapi/manage.py#L160-L164
def _write_to_log(self, s, truncate=False): """Writes the given output to the log file, appending unless `truncate` is True.""" # if truncate is True, set write mode to truncate with open(self._logfile, 'w' if truncate else 'a') as fp: fp.writelines((to_text(s) if six.PY2 else to_text(s), ))
[ "def", "_write_to_log", "(", "self", ",", "s", ",", "truncate", "=", "False", ")", ":", "# if truncate is True, set write mode to truncate", "with", "open", "(", "self", ".", "_logfile", ",", "'w'", "if", "truncate", "else", "'a'", ")", "as", "fp", ":", "fp"...
Writes the given output to the log file, appending unless `truncate` is True.
[ "Writes", "the", "given", "output", "to", "the", "log", "file", "appending", "unless", "truncate", "is", "True", "." ]
python
train
64.8
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_imputer.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_imputer.py#L21-L76
def convert(model, input_features, output_features): """Convert a DictVectorizer model to the protobuf spec. Parameters ---------- model: DictVectorizer A fitted DictVectorizer model. input_features: str Name of the input column. output_features: str Name of the output column. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model """ if not(_HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') # Set the interface params. spec = _Model_pb2.Model() spec.specificationVersion = SPECIFICATION_VERSION assert len(input_features) == 1 assert isinstance(input_features[0][1], datatypes.Array) # feature name in and out are the same here spec = set_transform_interface_params(spec, input_features, output_features) # Test the scikit-learn model _sklearn_util.check_expected_type(model, Imputer) _sklearn_util.check_fitted(model, lambda m: hasattr(m, 'statistics_')) if model.axis != 0: raise ValueError("Imputation is only supported along axis = 0.") # The imputer in our framework only works on single columns, so # we need to translate that over. The easiest way to do that is to # put it in a nested pipeline with a feature extractor and a tr_spec = spec.imputer for v in model.statistics_: tr_spec.imputedDoubleArray.vector.append(v) try: tr_spec.replaceDoubleValue = float(model.missing_values) except ValueError: raise ValueError("Only scalar values or NAN as missing_values " "in _imputer are supported.") return _MLModel(spec)
[ "def", "convert", "(", "model", ",", "input_features", ",", "output_features", ")", ":", "if", "not", "(", "_HAS_SKLEARN", ")", ":", "raise", "RuntimeError", "(", "'scikit-learn not found. scikit-learn conversion API is disabled.'", ")", "# Set the interface params.", "sp...
Convert a DictVectorizer model to the protobuf spec. Parameters ---------- model: DictVectorizer A fitted DictVectorizer model. input_features: str Name of the input column. output_features: str Name of the output column. Returns ------- model_spec: An object of type Model_pb. Protobuf representation of the model
[ "Convert", "a", "DictVectorizer", "model", "to", "the", "protobuf", "spec", "." ]
python
train
30.107143
kivy/buildozer
buildozer/__init__.py
https://github.com/kivy/buildozer/blob/586152c6ce2b6cde4d5a081d9711f9cb037a901c/buildozer/__init__.py#L173-L198
def prepare_for_build(self): '''Prepare the build. ''' assert(self.target is not None) if hasattr(self.target, '_build_prepared'): return self.info('Preparing build') self.info('Check requirements for {0}'.format(self.targetname)) self.target.check_requirements() self.info('Install platform') self.target.install_platform() self.info('Check application requirements') self.check_application_requirements() self.info('Check garden requirements') self.check_garden_requirements() self.info('Compile platform') self.target.compile_platform() # flag to prevent multiple build self.target._build_prepared = True
[ "def", "prepare_for_build", "(", "self", ")", ":", "assert", "(", "self", ".", "target", "is", "not", "None", ")", "if", "hasattr", "(", "self", ".", "target", ",", "'_build_prepared'", ")", ":", "return", "self", ".", "info", "(", "'Preparing build'", "...
Prepare the build.
[ "Prepare", "the", "build", "." ]
python
train
28.346154
modin-project/modin
modin/engines/base/frame/partition_manager.py
https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/engines/base/frame/partition_manager.py#L277-L313
def map_across_full_axis(self, axis, map_func): """Applies `map_func` to every partition. Note: This method should be used in the case that `map_func` relies on some global information about the axis. Args: axis: The axis to perform the map across (0 - index, 1 - columns). map_func: The function to apply. Returns: A new BaseFrameManager object, the type of object that called this. """ # Since we are already splitting the DataFrame back up after an # operation, we will just use this time to compute the number of # partitions as best we can right now. num_splits = self._compute_num_partitions() preprocessed_map_func = self.preprocess_func(map_func) partitions = self.column_partitions if not axis else self.row_partitions # For mapping across the entire axis, we don't maintain partitioning because we # may want to line to partitioning up with another BlockPartitions object. Since # we don't need to maintain the partitioning, this gives us the opportunity to # load-balance the data as well. result_blocks = np.array( [ part.apply(preprocessed_map_func, num_splits=num_splits) for part in partitions ] ) # If we are mapping over columns, they are returned to use the same as # rows, so we need to transpose the returned 2D numpy array to return # the structure to the correct order. return ( self.__constructor__(result_blocks.T) if not axis else self.__constructor__(result_blocks) )
[ "def", "map_across_full_axis", "(", "self", ",", "axis", ",", "map_func", ")", ":", "# Since we are already splitting the DataFrame back up after an", "# operation, we will just use this time to compute the number of", "# partitions as best we can right now.", "num_splits", "=", "self"...
Applies `map_func` to every partition. Note: This method should be used in the case that `map_func` relies on some global information about the axis. Args: axis: The axis to perform the map across (0 - index, 1 - columns). map_func: The function to apply. Returns: A new BaseFrameManager object, the type of object that called this.
[ "Applies", "map_func", "to", "every", "partition", "." ]
python
train
45.297297
RJT1990/pyflux
pyflux/families/exponential.py
https://github.com/RJT1990/pyflux/blob/297f2afc2095acd97c12e827dd500e8ea5da0c0f/pyflux/families/exponential.py#L195-L219
def markov_blanket(y, mean, scale, shape, skewness): """ Markov blanket for the Exponential distribution Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float scale parameter for the Exponential distribution shape : float tail thickness parameter for the Exponential distribution skewness : float skewness parameter for the Exponential distribution Returns ---------- - Markov blanket of the Exponential family """ return ss.expon.logpdf(x=y, scale=1/mean)
[ "def", "markov_blanket", "(", "y", ",", "mean", ",", "scale", ",", "shape", ",", "skewness", ")", ":", "return", "ss", ".", "expon", ".", "logpdf", "(", "x", "=", "y", ",", "scale", "=", "1", "/", "mean", ")" ]
Markov blanket for the Exponential distribution Parameters ---------- y : np.ndarray univariate time series mean : np.ndarray array of location parameters for the Exponential distribution scale : float scale parameter for the Exponential distribution shape : float tail thickness parameter for the Exponential distribution skewness : float skewness parameter for the Exponential distribution Returns ---------- - Markov blanket of the Exponential family
[ "Markov", "blanket", "for", "the", "Exponential", "distribution" ]
python
train
28.08
blockstack/blockstack-core
blockstack/blockstackd.py
https://github.com/blockstack/blockstack-core/blob/1dcfdd39b152d29ce13e736a6a1a0981401a0505/blockstack/blockstackd.py#L2970-L2987
def check_recovery(working_dir): """ Do we need to recover on start-up? """ recovery_start_block, recovery_end_block = get_recovery_range(working_dir) if recovery_start_block is not None and recovery_end_block is not None: local_current_block = virtualchain_hooks.get_last_block(working_dir) if local_current_block <= recovery_end_block: return True # otherwise, we're outside the recovery range and we can clear it log.debug('Chain state is at block {}, and is outside the recovery window {}-{}'.format(local_current_block, recovery_start_block, recovery_end_block)) clear_recovery_range(working_dir) return False else: # not recovering return False
[ "def", "check_recovery", "(", "working_dir", ")", ":", "recovery_start_block", ",", "recovery_end_block", "=", "get_recovery_range", "(", "working_dir", ")", "if", "recovery_start_block", "is", "not", "None", "and", "recovery_end_block", "is", "not", "None", ":", "l...
Do we need to recover on start-up?
[ "Do", "we", "need", "to", "recover", "on", "start", "-", "up?" ]
python
train
40.833333
kgori/treeCl
treeCl/bootstrap.py
https://github.com/kgori/treeCl/blob/fed624b3db1c19cc07175ca04e3eda6905a8d305/treeCl/bootstrap.py#L190-L206
def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs): """ index = index of the locus the bootstrap sample corresponds to - only important if using recalc=True in kwargs """ fit = np.empty((len(boot_collection), dimensions)) if ISPY3: query_trees = [PhyloTree(tree.encode(), rooted) for tree in boot_collection.trees] ref_trees = [PhyloTree(tree.encode(), rooted) for tree in ref_collection.trees] else: query_trees = [PhyloTree(tree, rooted) for tree in boot_collection.trees] ref_trees = [PhyloTree(tree, rooted) for tree in ref_collection.trees] for i, tree in enumerate(query_trees): distvec = np.array([task(tree, ref_tree, False) for ref_tree in ref_trees]) oos = OutOfSampleMDS(ref_distance_matrix) fit[i] = oos.fit(index, distvec, dimensions=dimensions, **kwargs) return fit
[ "def", "run_out_of_sample_mds", "(", "boot_collection", ",", "ref_collection", ",", "ref_distance_matrix", ",", "index", ",", "dimensions", ",", "task", "=", "_fast_geo", ",", "rooted", "=", "False", ",", "*", "*", "kwargs", ")", ":", "fit", "=", "np", ".", ...
index = index of the locus the bootstrap sample corresponds to - only important if using recalc=True in kwargs
[ "index", "=", "index", "of", "the", "locus", "the", "bootstrap", "sample", "corresponds", "to", "-", "only", "important", "if", "using", "recalc", "=", "True", "in", "kwargs" ]
python
train
55.941176
farshidce/touchworks-python
touchworks/api/http.py
https://github.com/farshidce/touchworks-python/blob/ea8f93a0f4273de1317a318e945a571f5038ba62/touchworks/api/http.py#L458-L480
def set_patient_medhx_flag(self, patient_id, medhx_status): """ invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param patient_id :param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and errors out if included. U=Unknown G=Granted D=Declined :return: JSON response """ magic = self._magic_json( action=TouchWorksMagicConstants.ACTION_SET_PATIENT_MEDHX_FLAG, patient_id=patient_id, parameter1=medhx_status ) response = self._http_request(TouchWorksEndPoints.MAGIC_JSON, data=magic) result = self._get_results_or_raise_if_magic_invalid( magic, response, TouchWorksMagicConstants.RESULT_SET_PATIENT_MEDHX_FLAG) return result
[ "def", "set_patient_medhx_flag", "(", "self", ",", "patient_id", ",", "medhx_status", ")", ":", "magic", "=", "self", ".", "_magic_json", "(", "action", "=", "TouchWorksMagicConstants", ".", "ACTION_SET_PATIENT_MEDHX_FLAG", ",", "patient_id", "=", "patient_id", ",",...
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param patient_id :param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and errors out if included. U=Unknown G=Granted D=Declined :return: JSON response
[ "invokes", "TouchWorksMagicConstants", ".", "ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT", "action", ":", "param", "patient_id", ":", "param", "medhx_status", "-", "Field", "in", "EEHR", "expects", "U", "G", "or", "D", ".", "SP", "defaults", "to", "Null", "and", "errors...
python
train
39.304348
mitsei/dlkit
dlkit/json_/assessment/sessions.py
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/json_/assessment/sessions.py#L7739-L7762
def alias_assessment_taken(self, assessment_taken_id, alias_id): """Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility. The primary ``Id`` of the ``AssessmentTaken`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer to another assessment taken, it is reassigned to the given assessment taken ``Id``. arg: assessment_taken_id (osid.id.Id): the ``Id`` of an ``AssessmentTaken`` arg: alias_id (osid.id.Id): the alias ``Id`` raise: AlreadyExists - ``alias_id`` is in use as a primary ``Id`` raise: NotFound - ``assessment_taken_id`` not found raise: NullArgument - ``assessment_taken_id`` or ``alias_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceAdminSession.alias_resources_template self._alias_id(primary_id=assessment_taken_id, equivalent_id=alias_id)
[ "def", "alias_assessment_taken", "(", "self", ",", "assessment_taken_id", ",", "alias_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceAdminSession.alias_resources_template", "self", ".", "_alias_id", "(", "primary_id", "=", "assessment_taken_id", ",",...
Adds an ``Id`` to an ``AssessmentTaken`` for the purpose of creating compatibility. The primary ``Id`` of the ``AssessmentTaken`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer to another assessment taken, it is reassigned to the given assessment taken ``Id``. arg: assessment_taken_id (osid.id.Id): the ``Id`` of an ``AssessmentTaken`` arg: alias_id (osid.id.Id): the alias ``Id`` raise: AlreadyExists - ``alias_id`` is in use as a primary ``Id`` raise: NotFound - ``assessment_taken_id`` not found raise: NullArgument - ``assessment_taken_id`` or ``alias_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure occurred *compliance: mandatory -- This method must be implemented.*
[ "Adds", "an", "Id", "to", "an", "AssessmentTaken", "for", "the", "purpose", "of", "creating", "compatibility", "." ]
python
train
50.583333
angr/angr
angr/exploration_techniques/director.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/exploration_techniques/director.py#L249-L263
def check_state(self, state): """ Check if the specific function is reached with certain arguments :param angr.SimState state: The state to check :return: True if the function is reached with certain arguments, False otherwise. :rtype: bool """ if state.addr == self.function.addr: arch = state.arch if self._check_arguments(arch, state): return True return False
[ "def", "check_state", "(", "self", ",", "state", ")", ":", "if", "state", ".", "addr", "==", "self", ".", "function", ".", "addr", ":", "arch", "=", "state", ".", "arch", "if", "self", ".", "_check_arguments", "(", "arch", ",", "state", ")", ":", "...
Check if the specific function is reached with certain arguments :param angr.SimState state: The state to check :return: True if the function is reached with certain arguments, False otherwise. :rtype: bool
[ "Check", "if", "the", "specific", "function", "is", "reached", "with", "certain", "arguments" ]
python
train
30.4
scott-maddox/openbandparams
src/openbandparams/iii_v_zinc_blende_strained.py
https://github.com/scott-maddox/openbandparams/blob/bc24e59187326bcb8948117434536082c9055777/src/openbandparams/iii_v_zinc_blende_strained.py#L150-L156
def CBO_Gamma(self, **kwargs): ''' Returns the strain-shifted Gamma-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally. ''' return (self.unstrained.CBO_Gamma(**kwargs) + self.CBO_strain_shift(**kwargs))
[ "def", "CBO_Gamma", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "(", "self", ".", "unstrained", ".", "CBO_Gamma", "(", "*", "*", "kwargs", ")", "+", "self", ".", "CBO_strain_shift", "(", "*", "*", "kwargs", ")", ")" ]
Returns the strain-shifted Gamma-valley conduction band offset (CBO), assuming the strain affects all conduction band valleys equally.
[ "Returns", "the", "strain", "-", "shifted", "Gamma", "-", "valley", "conduction", "band", "offset", "(", "CBO", ")", "assuming", "the", "strain", "affects", "all", "conduction", "band", "valleys", "equally", "." ]
python
train
43.142857
praekelt/jmbo-calendar
jmbo_calendar/admin.py
https://github.com/praekelt/jmbo-calendar/blob/ac39f3ad4c155d6755ec5c5a51fb815268b8c18c/jmbo_calendar/admin.py#L36-L46
def get_fieldsets(self, *args, **kwargs): """Re-order fields""" result = super(EventAdmin, self).get_fieldsets(*args, **kwargs) result = list(result) fields = list(result[0][1]['fields']) for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \ 'external_link', 'calendars'): fields.remove(name) fields.append(name) result[0][1]['fields'] = tuple(fields) return tuple(result)
[ "def", "get_fieldsets", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "EventAdmin", ",", "self", ")", ".", "get_fieldsets", "(", "*", "args", ",", "*", "*", "kwargs", ")", "result", "=", "list", "(",...
Re-order fields
[ "Re", "-", "order", "fields" ]
python
train
42.545455
google/identity-toolkit-python-client
identitytoolkit/rpchelper.py
https://github.com/google/identity-toolkit-python-client/blob/4cfe3013569c21576daa5d22ad21f9f4f8b30c4d/identitytoolkit/rpchelper.py#L129-L147
def UploadAccount(self, hash_algorithm, hash_key, accounts): """Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Response of the API. """ param = { 'hashAlgorithm': hash_algorithm, 'signerKey': hash_key, 'users': accounts } # pylint does not recognize the return type of simplejson.loads # pylint: disable=maybe-no-member return self._InvokeGitkitApi('uploadAccount', param)
[ "def", "UploadAccount", "(", "self", ",", "hash_algorithm", ",", "hash_key", ",", "accounts", ")", ":", "param", "=", "{", "'hashAlgorithm'", ":", "hash_algorithm", ",", "'signerKey'", ":", "hash_key", ",", "'users'", ":", "accounts", "}", "# pylint does not rec...
Uploads multiple accounts to Gitkit server. Args: hash_algorithm: string, algorithm to hash password. hash_key: string, base64-encoded key of the algorithm. accounts: array of accounts to be uploaded. Returns: Response of the API.
[ "Uploads", "multiple", "accounts", "to", "Gitkit", "server", "." ]
python
train
31.736842
bspaans/python-mingus
mingus/extra/tablature.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/extra/tablature.py#L328-L397
def from_Composition(composition, width=80): """Convert a mingus.containers.Composition to an ASCII tablature string. Automatically add an header based on the title, subtitle, author, e-mail and description attributes. An extra description of the piece can also be given. Tunings can be set by using the Track.instrument.tuning or Track.tuning attribute. """ # Collect tunings instr_tunings = [] for track in composition: tun = track.get_tuning() if tun: instr_tunings.append(tun) else: instr_tunings.append(default_tuning) result = add_headers( width, composition.title, composition.subtitle, composition.author, composition.email, composition.description, instr_tunings, ) # Some variables w = _get_width(width) barindex = 0 bars = width / w lastlen = 0 maxlen = max([len(x) for x in composition.tracks]) while barindex < maxlen: notfirst = False for tracks in composition: tuning = tracks.get_tuning() ascii = [] for x in xrange(bars): if barindex + x < len(tracks): bar = tracks[barindex + x] r = from_Bar(bar, w, tuning, collapse=False) barstart = r[1].find('||') + 2 # Add extra '||' to quarter note marks to connect tracks. if notfirst: r[0] = (r[0])[:barstart - 2] + '||' + (r[0])[barstart:] # Add bar to ascii if ascii != []: for i in range(1, len(r) + 1): item = r[len(r) - i] ascii[-i] += item[barstart:] else: ascii += r # Add extra '||' to connect tracks if notfirst and ascii != []: pad = ascii[-1].find('||') result += [' ' * pad + '||', ' ' * pad + '||'] else: notfirst = True # Finally, add ascii to result result += ascii result += ['', '', ''] barindex += bars return os.linesep.join(result)
[ "def", "from_Composition", "(", "composition", ",", "width", "=", "80", ")", ":", "# Collect tunings", "instr_tunings", "=", "[", "]", "for", "track", "in", "composition", ":", "tun", "=", "track", ".", "get_tuning", "(", ")", "if", "tun", ":", "instr_tuni...
Convert a mingus.containers.Composition to an ASCII tablature string. Automatically add an header based on the title, subtitle, author, e-mail and description attributes. An extra description of the piece can also be given. Tunings can be set by using the Track.instrument.tuning or Track.tuning attribute.
[ "Convert", "a", "mingus", ".", "containers", ".", "Composition", "to", "an", "ASCII", "tablature", "string", "." ]
python
train
31.671429
hydpy-dev/hydpy
hydpy/core/objecttools.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L1431-L1468
def enumeration(values, converter=str, default=''): """Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' >>> enumeration(('text', 3)) 'text and 3' >>> enumeration(('text',)) 'text' >>> enumeration(()) '' All given objects are converted to strings by function |str|, as shown by the first two examples. This behaviour can be changed by another function expecting a single argument and returning a string: >>> from hydpy.core.objecttools import classname >>> enumeration(('text', 3, []), converter=classname) 'str, int, and list' Furthermore, you can define a default string that is returned in case an empty iterable is given: >>> enumeration((), default='nothing') 'nothing' """ values = tuple(converter(value) for value in values) if not values: return default if len(values) == 1: return values[0] if len(values) == 2: return ' and '.join(values) return ', and '.join((', '.join(values[:-1]), values[-1]))
[ "def", "enumeration", "(", "values", ",", "converter", "=", "str", ",", "default", "=", "''", ")", ":", "values", "=", "tuple", "(", "converter", "(", "value", ")", "for", "value", "in", "values", ")", "if", "not", "values", ":", "return", "default", ...
Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' >>> enumeration(('text', 3)) 'text and 3' >>> enumeration(('text',)) 'text' >>> enumeration(()) '' All given objects are converted to strings by function |str|, as shown by the first two examples. This behaviour can be changed by another function expecting a single argument and returning a string: >>> from hydpy.core.objecttools import classname >>> enumeration(('text', 3, []), converter=classname) 'str, int, and list' Furthermore, you can define a default string that is returned in case an empty iterable is given: >>> enumeration((), default='nothing') 'nothing'
[ "Return", "an", "enumeration", "string", "based", "on", "the", "given", "values", "." ]
python
train
31.605263
zomux/deepy
deepy/dataset/basic.py
https://github.com/zomux/deepy/blob/090fbad22a08a809b12951cd0d4984f5bd432698/deepy/dataset/basic.py#L30-L40
def map(self, func): """ Process all data with given function. The scheme of function should be x,y -> x,y. """ if self._train_set: self._train_set = map(func, self._train_set) if self._valid_set: self._valid_set = map(func, self._valid_set) if self._test_set: self._test_set = map(func, self._test_set)
[ "def", "map", "(", "self", ",", "func", ")", ":", "if", "self", ".", "_train_set", ":", "self", ".", "_train_set", "=", "map", "(", "func", ",", "self", ".", "_train_set", ")", "if", "self", ".", "_valid_set", ":", "self", ".", "_valid_set", "=", "...
Process all data with given function. The scheme of function should be x,y -> x,y.
[ "Process", "all", "data", "with", "given", "function", ".", "The", "scheme", "of", "function", "should", "be", "x", "y", "-", ">", "x", "y", "." ]
python
test
35
xtuml/pyxtuml
xtuml/load.py
https://github.com/xtuml/pyxtuml/blob/7dd9343b9a0191d1db1887ab9288d0a026608d9a/xtuml/load.py#L274-L282
def populate_unique_identifiers(self, metamodel): ''' Populate a *metamodel* with class unique identifiers previously encountered from input. ''' for stmt in self.statements: if isinstance(stmt, CreateUniqueStmt): metamodel.define_unique_identifier(stmt.kind, stmt.name, *stmt.attributes)
[ "def", "populate_unique_identifiers", "(", "self", ",", "metamodel", ")", ":", "for", "stmt", "in", "self", ".", "statements", ":", "if", "isinstance", "(", "stmt", ",", "CreateUniqueStmt", ")", ":", "metamodel", ".", "define_unique_identifier", "(", "stmt", "...
Populate a *metamodel* with class unique identifiers previously encountered from input.
[ "Populate", "a", "*", "metamodel", "*", "with", "class", "unique", "identifiers", "previously", "encountered", "from", "input", "." ]
python
test
44.444444
ultrabug/py3status
py3status/core.py
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/core.py#L619-L694
def notify_user( self, msg, level="error", rate_limit=None, module_name="", icon=None, title="py3status", ): """ Display notification to user via i3-nagbar or send-notify We also make sure to log anything to keep trace of it. NOTE: Message should end with a '.' for consistency. """ dbus = self.config.get("dbus_notify") if dbus: # force msg, icon, title to be a string title = u"{}".format(title) msg = u"{}".format(msg) if icon: icon = u"{}".format(icon) else: msg = u"py3status: {}".format(msg) if level != "info" and module_name == "": fix_msg = u"{} Please try to fix this and reload i3wm (Mod+Shift+R)" msg = fix_msg.format(msg) # Rate limiting. If rate limiting then we need to calculate the time # period for which the message should not be repeated. We just use # A simple chunked time model where a message cannot be repeated in a # given time period. Messages can be repeated more frequently but must # be in different time periods. limit_key = "" if rate_limit: try: limit_key = time.time() // rate_limit except TypeError: pass # We use a hash to see if the message is being repeated. This is crude # and imperfect but should work for our needs. msg_hash = hash(u"{}#{}#{}#{}".format(module_name, limit_key, msg, title)) if msg_hash in self.notified_messages: return elif module_name: log_msg = 'Module `%s` sent a notification. "%s: %s"' % ( module_name, title, msg, ) self.log(log_msg, level) else: self.log(msg, level) self.notified_messages.add(msg_hash) try: if dbus: # fix any html entities msg = msg.replace("&", "&amp;") msg = msg.replace("<", "&lt;") msg = msg.replace(">", "&gt;") cmd = ["notify-send"] if icon: cmd += ["-i", icon] cmd += ["-u", DBUS_LEVELS.get(level, "normal"), "-t", "10000"] cmd += [title, msg] else: py3_config = self.config.get("py3_config", {}) nagbar_font = py3_config.get("py3status", {}).get("nagbar_font") wm_nag = self.config["wm"]["nag"] cmd = [wm_nag, "-m", msg, "-t", level] if nagbar_font: cmd += ["-f", nagbar_font] Popen(cmd, stdout=open("/dev/null", "w"), stderr=open("/dev/null", "w")) except Exception as err: self.log("notify_user error: %s" % err)
[ "def", "notify_user", "(", "self", ",", "msg", ",", "level", "=", "\"error\"", ",", "rate_limit", "=", "None", ",", "module_name", "=", "\"\"", ",", "icon", "=", "None", ",", "title", "=", "\"py3status\"", ",", ")", ":", "dbus", "=", "self", ".", "co...
Display notification to user via i3-nagbar or send-notify We also make sure to log anything to keep trace of it. NOTE: Message should end with a '.' for consistency.
[ "Display", "notification", "to", "user", "via", "i3", "-", "nagbar", "or", "send", "-", "notify", "We", "also", "make", "sure", "to", "log", "anything", "to", "keep", "trace", "of", "it", "." ]
python
train
37.605263
bitesofcode/projexui
projexui/menus/xmenu.py
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/menus/xmenu.py#L374-L387
def adjustMinimumWidth( self ): """ Updates the minimum width for this menu based on the font metrics \ for its title (if its shown). This method is called automatically \ when the menu is shown. """ if not self.showTitle(): return metrics = QFontMetrics(self.font()) width = metrics.width(self.title()) + 20 if self.minimumWidth() < width: self.setMinimumWidth(width)
[ "def", "adjustMinimumWidth", "(", "self", ")", ":", "if", "not", "self", ".", "showTitle", "(", ")", ":", "return", "metrics", "=", "QFontMetrics", "(", "self", ".", "font", "(", ")", ")", "width", "=", "metrics", ".", "width", "(", "self", ".", "tit...
Updates the minimum width for this menu based on the font metrics \ for its title (if its shown). This method is called automatically \ when the menu is shown.
[ "Updates", "the", "minimum", "width", "for", "this", "menu", "based", "on", "the", "font", "metrics", "\\", "for", "its", "title", "(", "if", "its", "shown", ")", ".", "This", "method", "is", "called", "automatically", "\\", "when", "the", "menu", "is", ...
python
train
33.714286
jwodder/doapi
doapi/doapi.py
https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/doapi.py#L651-L671
def fetch_all_images(self, type=None, private=None): # pylint: disable=redefined-builtin r""" Returns a generator that yields all of the images available to the account :param type: the type of images to fetch: ``"distribution"``, ``"application"``, or all (`None`); default: `None` :type type: string or None :param bool private: whether to only return the user's private images; default: return all images :rtype: generator of `Image`\ s :raises DOAPIError: if the API endpoint replies with an error """ params = {} if type is not None: params["type"] = type if private is not None: params["private"] = 'true' if private else 'false' return map(self._image, self.paginate('/v2/images', 'images', params=params))
[ "def", "fetch_all_images", "(", "self", ",", "type", "=", "None", ",", "private", "=", "None", ")", ":", "# pylint: disable=redefined-builtin", "params", "=", "{", "}", "if", "type", "is", "not", "None", ":", "params", "[", "\"type\"", "]", "=", "type", ...
r""" Returns a generator that yields all of the images available to the account :param type: the type of images to fetch: ``"distribution"``, ``"application"``, or all (`None`); default: `None` :type type: string or None :param bool private: whether to only return the user's private images; default: return all images :rtype: generator of `Image`\ s :raises DOAPIError: if the API endpoint replies with an error
[ "r", "Returns", "a", "generator", "that", "yields", "all", "of", "the", "images", "available", "to", "the", "account" ]
python
train
42.857143
saltstack/salt
salt/modules/s6.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s6.py#L135-L151
def status(name, sig=None): ''' Return the status for a service via s6, return pid if running CLI Example: .. code-block:: bash salt '*' s6.status <service name> ''' cmd = 's6-svstat {0}'.format(_service_path(name)) out = __salt__['cmd.run_stdout'](cmd) try: pid = re.search(r'up \(pid (\d+)\)', out).group(1) except AttributeError: pid = '' return pid
[ "def", "status", "(", "name", ",", "sig", "=", "None", ")", ":", "cmd", "=", "'s6-svstat {0}'", ".", "format", "(", "_service_path", "(", "name", ")", ")", "out", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "cmd", ")", "try", ":", "pid", "=",...
Return the status for a service via s6, return pid if running CLI Example: .. code-block:: bash salt '*' s6.status <service name>
[ "Return", "the", "status", "for", "a", "service", "via", "s6", "return", "pid", "if", "running" ]
python
train
23.705882
alex-kostirin/pyatomac
atomac/AXClasses.py
https://github.com/alex-kostirin/pyatomac/blob/3f46f6feb4504315eec07abb18bb41be4d257aeb/atomac/AXClasses.py#L457-L529
def _queueMouseButton(self, coord, mouseButton, modFlags, clickCount=1, dest_coord=None): """Private method to handle generic mouse button clicking. Parameters: coord (x, y) to click, mouseButton (e.g., kCGMouseButtonLeft), modFlags set (int) Optional: clickCount (default 1; set to 2 for double-click; 3 for triple-click on host) Returns: None """ # For now allow only left and right mouse buttons: mouseButtons = { Quartz.kCGMouseButtonLeft: 'LeftMouse', Quartz.kCGMouseButtonRight: 'RightMouse', } if mouseButton not in mouseButtons: raise ValueError('Mouse button given not recognized') eventButtonDown = getattr(Quartz, 'kCGEvent%sDown' % mouseButtons[mouseButton]) eventButtonUp = getattr(Quartz, 'kCGEvent%sUp' % mouseButtons[mouseButton]) eventButtonDragged = getattr(Quartz, 'kCGEvent%sDragged' % mouseButtons[ mouseButton]) # Press the button buttonDown = Quartz.CGEventCreateMouseEvent(None, eventButtonDown, coord, mouseButton) # Set modflags (default None) on button down: Quartz.CGEventSetFlags(buttonDown, modFlags) # Set the click count on button down: Quartz.CGEventSetIntegerValueField(buttonDown, Quartz.kCGMouseEventClickState, int(clickCount)) if dest_coord: # Drag and release the button buttonDragged = Quartz.CGEventCreateMouseEvent(None, eventButtonDragged, dest_coord, mouseButton) # Set modflags on the button dragged: Quartz.CGEventSetFlags(buttonDragged, modFlags) buttonUp = Quartz.CGEventCreateMouseEvent(None, eventButtonUp, dest_coord, mouseButton) else: # Release the button buttonUp = Quartz.CGEventCreateMouseEvent(None, eventButtonUp, coord, mouseButton) # Set modflags on the button up: Quartz.CGEventSetFlags(buttonUp, modFlags) # Set the click count on button up: Quartz.CGEventSetIntegerValueField(buttonUp, Quartz.kCGMouseEventClickState, int(clickCount)) # Queue the events self._queueEvent(Quartz.CGEventPost, (Quartz.kCGSessionEventTap, buttonDown)) if dest_coord: self._queueEvent(Quartz.CGEventPost, (Quartz.kCGHIDEventTap, buttonDragged)) self._queueEvent(Quartz.CGEventPost, (Quartz.kCGSessionEventTap, buttonUp))
[ "def", "_queueMouseButton", "(", "self", ",", "coord", ",", "mouseButton", ",", "modFlags", ",", "clickCount", "=", "1", ",", "dest_coord", "=", "None", ")", ":", "# For now allow only left and right mouse buttons:", "mouseButtons", "=", "{", "Quartz", ".", "kCGMo...
Private method to handle generic mouse button clicking. Parameters: coord (x, y) to click, mouseButton (e.g., kCGMouseButtonLeft), modFlags set (int) Optional: clickCount (default 1; set to 2 for double-click; 3 for triple-click on host) Returns: None
[ "Private", "method", "to", "handle", "generic", "mouse", "button", "clicking", "." ]
python
valid
47.520548
taskcluster/taskcluster-client.py
taskcluster/utils.py
https://github.com/taskcluster/taskcluster-client.py/blob/bcc95217f8bf80bed2ae5885a19fa0035da7ebc9/taskcluster/utils.py#L182-L194
def stableSlugId(): """Returns a closure which can be used to generate stable slugIds. Stable slugIds can be used in a graph to specify task IDs in multiple places without regenerating them, e.g. taskId, requires, etc. """ _cache = {} def closure(name): if name not in _cache: _cache[name] = slugId() return _cache[name] return closure
[ "def", "stableSlugId", "(", ")", ":", "_cache", "=", "{", "}", "def", "closure", "(", "name", ")", ":", "if", "name", "not", "in", "_cache", ":", "_cache", "[", "name", "]", "=", "slugId", "(", ")", "return", "_cache", "[", "name", "]", "return", ...
Returns a closure which can be used to generate stable slugIds. Stable slugIds can be used in a graph to specify task IDs in multiple places without regenerating them, e.g. taskId, requires, etc.
[ "Returns", "a", "closure", "which", "can", "be", "used", "to", "generate", "stable", "slugIds", ".", "Stable", "slugIds", "can", "be", "used", "in", "a", "graph", "to", "specify", "task", "IDs", "in", "multiple", "places", "without", "regenerating", "them", ...
python
train
29.307692
ymoch/apyori
apyori.py
https://github.com/ymoch/apyori/blob/8cc20a19d01b18b83e18e54aabb416c8dedabfde/apyori.py#L60-L91
def calc_support(self, items): """ Returns a support for items. Arguments: items -- Items as an iterable object (eg. ['A', 'B']). """ # Empty items is supported by all transactions. if not items: return 1.0 # Empty transactions supports no items. if not self.num_transaction: return 0.0 # Create the transaction index intersection. sum_indexes = None for item in items: indexes = self.__transaction_index_map.get(item) if indexes is None: # No support for any set that contains a not existing item. return 0.0 if sum_indexes is None: # Assign the indexes on the first time. sum_indexes = indexes else: # Calculate the intersection on not the first time. sum_indexes = sum_indexes.intersection(indexes) # Calculate and return the support. return float(len(sum_indexes)) / self.__num_transaction
[ "def", "calc_support", "(", "self", ",", "items", ")", ":", "# Empty items is supported by all transactions.", "if", "not", "items", ":", "return", "1.0", "# Empty transactions supports no items.", "if", "not", "self", ".", "num_transaction", ":", "return", "0.0", "# ...
Returns a support for items. Arguments: items -- Items as an iterable object (eg. ['A', 'B']).
[ "Returns", "a", "support", "for", "items", "." ]
python
train
32.84375
tomplus/kubernetes_asyncio
kubernetes_asyncio/client/api/apps_v1_api.py
https://github.com/tomplus/kubernetes_asyncio/blob/f9ab15317ec921409714c7afef11aeb0f579985d/kubernetes_asyncio/client/api/apps_v1_api.py#L1143-L1172
def delete_collection_namespaced_stateful_set(self, namespace, **kwargs): # noqa: E501 """delete_collection_namespaced_stateful_set # noqa: E501 delete collection of StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_stateful_set(namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: object name and auth scope, such as for teams and projects (required) :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs) # noqa: E501 else: (data) = self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs) # noqa: E501 return data
[ "def", "delete_collection_namespaced_stateful_set", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return",...
delete_collection_namespaced_stateful_set # noqa: E501 delete collection of StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_stateful_set(namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str namespace: object name and auth scope, such as for teams and projects (required) :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1Status If the method is called asynchronously, returns the request thread.
[ "delete_collection_namespaced_stateful_set", "#", "noqa", ":", "E501" ]
python
train
164.6
nsavch/python-dpcolors
dpcolors/__init__.py
https://github.com/nsavch/python-dpcolors/blob/9bca11416a21eca1c5a84b7dcc852d231d911981/dpcolors/__init__.py#L110-L142
def to_8bit(self): """ Convert to 8-bit color :return: Color8Bit instance """ h, s, v = colorsys.rgb_to_hsv(*self.scale(1)) # Check if the color is a shade of grey if s * v < 0.3: if v < 0.3: return Color8Bit(Color8Bit.BLACK, False) elif v < 0.66: return Color8Bit(Color8Bit.BLACK, True) elif v < 0.91: return Color8Bit(Color8Bit.WHITE, False) else: return Color8Bit(Color8Bit.WHITE, True) # not grey? What color is it then? if h < 0.041 or h > 0.92: res = Color8Bit.RED elif h < 0.11: # orange = dark yellow return Color8Bit(Color8Bit.YELLOW, False) elif h < 0.2: res = Color8Bit.YELLOW elif h < 0.45: res = Color8Bit.GREEN elif h < 0.6: res = Color8Bit.CYAN elif h < 0.74: res = Color8Bit.BLUE else: res = Color8Bit.MAGENTA return Color8Bit(res, v > 0.6)
[ "def", "to_8bit", "(", "self", ")", ":", "h", ",", "s", ",", "v", "=", "colorsys", ".", "rgb_to_hsv", "(", "*", "self", ".", "scale", "(", "1", ")", ")", "# Check if the color is a shade of grey", "if", "s", "*", "v", "<", "0.3", ":", "if", "v", "<...
Convert to 8-bit color :return: Color8Bit instance
[ "Convert", "to", "8", "-", "bit", "color", ":", "return", ":", "Color8Bit", "instance" ]
python
train
32.121212
foremast/foremast
src/foremast/utils/dns.py
https://github.com/foremast/foremast/blob/fb70f29b8ce532f061685a17d120486e47b215ba/src/foremast/utils/dns.py#L99-L123
def find_existing_record(env, zone_id, dns_name, check_key=None, check_value=None): """Check if a specific DNS record exists. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update. check_key(str): Key to look for in record. Example: "Type" check_value(str): Value to look for with check_key. Example: "CNAME" Returns: json: Found Record. Returns None if no record found """ client = boto3.Session(profile_name=env).client('route53') pager = client.get_paginator('list_resource_record_sets') existingrecord = None for rset in pager.paginate(HostedZoneId=zone_id): for record in rset['ResourceRecordSets']: if check_key: if record['Name'].rstrip('.') == dns_name and record.get(check_key) == check_value: LOG.info("Found existing record: %s", record) existingrecord = record break return existingrecord
[ "def", "find_existing_record", "(", "env", ",", "zone_id", ",", "dns_name", ",", "check_key", "=", "None", ",", "check_value", "=", "None", ")", ":", "client", "=", "boto3", ".", "Session", "(", "profile_name", "=", "env", ")", ".", "client", "(", "'rout...
Check if a specific DNS record exists. Args: env (str): Deployment environment. zone_id (str): Route53 zone id. dns_name (str): FQDN of application's dns entry to add/update. check_key(str): Key to look for in record. Example: "Type" check_value(str): Value to look for with check_key. Example: "CNAME" Returns: json: Found Record. Returns None if no record found
[ "Check", "if", "a", "specific", "DNS", "record", "exists", "." ]
python
train
41.6
clalancette/pycdlib
pycdlib/eltorito.py
https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/eltorito.py#L745-L790
def add_section(self, ino, sector_count, load_seg, media_name, system_type, efi, bootable): # type: (inode.Inode, int, int, str, int, bool, bool) -> None ''' A method to add an section header and entry to this Boot Catalog. Parameters: ino - The Inode object to associate with the new Entry. sector_count - The number of sectors to assign to the new Entry. load_seg - The load segment address of the boot image. media_name - The name of the media type, one of 'noemul', 'floppy', or 'hdemul'. system_type - The type of partition this entry should be. efi - Whether this section is an EFI section. bootable - Whether this entry should be bootable. Returns: Nothing. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalError('El Torito Boot Catalog not yet initialized') # The Eltorito Boot Catalog can only be 2048 bytes (1 extent). By # default, the first 64 bytes are used by the Validation Entry and the # Initial Entry, which leaves 1984 bytes. Each section takes up 32 # bytes for the Section Header and 32 bytes for the Section Entry, for # a total of 64 bytes, so we can have a maximum of 1984/64 = 31 # sections. if len(self.sections) == 31: raise pycdlibexception.PyCdlibInvalidInput('Too many Eltorito sections') sec = EltoritoSectionHeader() platform_id = self.validation_entry.platform_id if efi: platform_id = 0xef sec.new(b'\x00' * 28, platform_id) secentry = EltoritoEntry() secentry.new(sector_count, load_seg, media_name, system_type, bootable) secentry.set_inode(ino) ino.linked_records.append(secentry) sec.add_new_entry(secentry) if self.sections: self.sections[-1].set_record_not_last() self.sections.append(sec)
[ "def", "add_section", "(", "self", ",", "ino", ",", "sector_count", ",", "load_seg", ",", "media_name", ",", "system_type", ",", "efi", ",", "bootable", ")", ":", "# type: (inode.Inode, int, int, str, int, bool, bool) -> None", "if", "not", "self", ".", "_initialize...
A method to add an section header and entry to this Boot Catalog. Parameters: ino - The Inode object to associate with the new Entry. sector_count - The number of sectors to assign to the new Entry. load_seg - The load segment address of the boot image. media_name - The name of the media type, one of 'noemul', 'floppy', or 'hdemul'. system_type - The type of partition this entry should be. efi - Whether this section is an EFI section. bootable - Whether this entry should be bootable. Returns: Nothing.
[ "A", "method", "to", "add", "an", "section", "header", "and", "entry", "to", "this", "Boot", "Catalog", "." ]
python
train
42.434783
ladybug-tools/ladybug
ladybug/psychrometrics.py
https://github.com/ladybug-tools/ladybug/blob/c08b7308077a48d5612f644943f92d5b5dade583/ladybug/psychrometrics.py#L163-L173
def rel_humid_from_db_wb(db_temp, wet_bulb, b_press=101325): """Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa). """ # Calculate saturation pressure. p_ws = saturated_vapor_pressure(db_temp + 273.15) p_ws_wb = saturated_vapor_pressure(wet_bulb + 273.15) # calculate partial vapor pressure p_w = p_ws_wb - (b_press * 0.000662 * (db_temp - wet_bulb)) # Calculate the relative humidity. rel_humid = (p_w / p_ws) * 100 return rel_humid
[ "def", "rel_humid_from_db_wb", "(", "db_temp", ",", "wet_bulb", ",", "b_press", "=", "101325", ")", ":", "# Calculate saturation pressure.", "p_ws", "=", "saturated_vapor_pressure", "(", "db_temp", "+", "273.15", ")", "p_ws_wb", "=", "saturated_vapor_pressure", "(", ...
Relative Humidity (%) at db_temp(C), wet_bulb (C), and Pressure b_press (Pa).
[ "Relative", "Humidity", "(", "%", ")", "at", "db_temp", "(", "C", ")", "wet_bulb", "(", "C", ")", "and", "Pressure", "b_press", "(", "Pa", ")", "." ]
python
train
44.545455
CalebBell/thermo
thermo/eos.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/eos.py#L3192-L3202
def a_alpha_and_derivatives(self, T, full=True, quick=True): r'''Method to calculate `a_alpha` and its first and second derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Uses the set values of `Tc`, `omega`, and `a`. Because of its similarity for the TWUPR EOS, this has been moved to an external `TWU_a_alpha_common` function. See it for further documentation. ''' return TWU_a_alpha_common(T, self.Tc, self.omega, self.a, full=full, quick=quick, method='SRK')
[ "def", "a_alpha_and_derivatives", "(", "self", ",", "T", ",", "full", "=", "True", ",", "quick", "=", "True", ")", ":", "return", "TWU_a_alpha_common", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "omega", ",", "self", ".", "a", ",", "full", ...
r'''Method to calculate `a_alpha` and its first and second derivatives for this EOS. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. Uses the set values of `Tc`, `omega`, and `a`. Because of its similarity for the TWUPR EOS, this has been moved to an external `TWU_a_alpha_common` function. See it for further documentation.
[ "r", "Method", "to", "calculate", "a_alpha", "and", "its", "first", "and", "second", "derivatives", "for", "this", "EOS", ".", "Returns", "a_alpha", "da_alpha_dT", "and", "d2a_alpha_dT2", ".", "See", "GCEOS", ".", "a_alpha_and_derivatives", "for", "more", "docum...
python
valid
57
toomore/goristock
grs/BSR.py
https://github.com/toomore/goristock/blob/e61f57f11a626cfbc4afbf66337fd9d1c51e3e71/grs/BSR.py#L67-L71
def showinfo(self): ''' 總覽顯示 ''' print 'money:',self.money print 'store:',self.store print 'avgprice:',self.avgprice
[ "def", "showinfo", "(", "self", ")", ":", "print", "'money:'", ",", "self", ".", "money", "print", "'store:'", ",", "self", ".", "store", "print", "'avgprice:'", ",", "self", ".", "avgprice" ]
總覽顯示
[ "總覽顯示" ]
python
train
25.6
pantsbuild/pex
pex/executor.py
https://github.com/pantsbuild/pex/blob/87b2129d860250d3b9edce75b9cb62f9789ee521/pex/executor.py#L61-L77
def open_process(cls, cmd, **kwargs): """Opens a process object via subprocess.Popen(). :param string|list cmd: A list or string representing the command to run. :param **kwargs: Additional kwargs to pass through to subprocess.Popen. :return: A `subprocess.Popen` object. :raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist. """ assert len(cmd) > 0, 'cannot execute an empty command!' try: return subprocess.Popen(cmd, **kwargs) except (IOError, OSError) as e: if e.errno == errno.ENOENT: raise cls.ExecutableNotFound(cmd, e) else: raise cls.ExecutionError(repr(e), cmd, e)
[ "def", "open_process", "(", "cls", ",", "cmd", ",", "*", "*", "kwargs", ")", ":", "assert", "len", "(", "cmd", ")", ">", "0", ",", "'cannot execute an empty command!'", "try", ":", "return", "subprocess", ".", "Popen", "(", "cmd", ",", "*", "*", "kwarg...
Opens a process object via subprocess.Popen(). :param string|list cmd: A list or string representing the command to run. :param **kwargs: Additional kwargs to pass through to subprocess.Popen. :return: A `subprocess.Popen` object. :raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist.
[ "Opens", "a", "process", "object", "via", "subprocess", ".", "Popen", "()", "." ]
python
train
39.294118
Erotemic/utool
utool/util_path.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_path.py#L562-L628
def checkpath(path_, verbose=VERYVERBOSE, n=None, info=VERYVERBOSE): r""" verbose wrapper around ``os.path.exists`` Returns: true if ``path_`` exists on the filesystem show only the top `n` directories Args: path_ (str): path string verbose (bool): verbosity flag(default = False) n (int): (default = None) info (bool): (default = False) CommandLine: python -m utool.util_path --test-checkpath Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> path_ = ut.__file__ >>> verbose = True >>> n = None >>> info = False >>> result = checkpath(path_, verbose, n, info) >>> print(result) True Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> path_ = ut.__file__ + 'foobar' >>> verbose = True >>> result = checkpath(path_, verbose, n=None, info=True) >>> print(result) False """ assert isinstance(path_, six.string_types), ( 'path_=%r is not a string. type(path_) = %r' % (path_, type(path_))) path_ = normpath(path_) if sys.platform.startswith('win32'): # convert back to windows style path if using unix style if path_.startswith('\\'): dirs = path_.split('\\') if len(dirs) > 1 and len(dirs[0]) == 0 and len(dirs[1]) == 1: dirs[1] = dirs[1].upper() + ':' path_ = '\\'.join(dirs[1:]) does_exist = exists(path_) if verbose: #print_('[utool] checkpath(%r)' % (path_)) pretty_path = path_ndir_split(path_, n) caller_name = util_dbg.get_caller_name(allow_genexpr=False) print('[%s] checkpath(%r)' % (caller_name, pretty_path)) if does_exist: path_type = get_path_type(path_) #path_type = 'file' if isfile(path_) else 'directory' print('[%s] ...(%s) exists' % (caller_name, path_type,)) else: print('[%s] ... does not exist' % (caller_name)) if not does_exist and info: #print('[util_path] ! Does not exist') _longest_path = longest_existing_path(path_) _longest_path_type = get_path_type(_longest_path) print('[util_path] ... The longest existing path is: %r' % _longest_path) print('[util_path] ... and has type %r' % (_longest_path_type,)) return does_exist
[ "def", "checkpath", "(", "path_", ",", "verbose", "=", "VERYVERBOSE", ",", "n", "=", "None", ",", "info", "=", "VERYVERBOSE", ")", ":", "assert", "isinstance", "(", "path_", ",", "six", ".", "string_types", ")", ",", "(", "'path_=%r is not a string. type(pat...
r""" verbose wrapper around ``os.path.exists`` Returns: true if ``path_`` exists on the filesystem show only the top `n` directories Args: path_ (str): path string verbose (bool): verbosity flag(default = False) n (int): (default = None) info (bool): (default = False) CommandLine: python -m utool.util_path --test-checkpath Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> path_ = ut.__file__ >>> verbose = True >>> n = None >>> info = False >>> result = checkpath(path_, verbose, n, info) >>> print(result) True Example: >>> # DISABLE_DOCTEST >>> from utool.util_path import * # NOQA >>> import utool as ut >>> path_ = ut.__file__ + 'foobar' >>> verbose = True >>> result = checkpath(path_, verbose, n=None, info=True) >>> print(result) False
[ "r", "verbose", "wrapper", "around", "os", ".", "path", ".", "exists" ]
python
train
36.731343
totalgood/twip
twip/scripts/clean.py
https://github.com/totalgood/twip/blob/5c0411d2acfbe5b421841072814c9152591c03f7/twip/scripts/clean.py#L107-L146
def dropna(df, nonnull_rows=100, nonnull_cols=50, nanstrs=('nan', 'NaN', ''), nullstr=''): """Drop columns/rows with too many NaNs and replace NaNs in columns of strings with '' >>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]]) >>> dropna(df) Empty DataFrame Columns: [] Index: [] >>> dropna(df, nonnull_cols=0, nonnull_rows=0) 0 1 2 0 NaN str 1 0.1 and 2 2 NaN """ if 0 < nonnull_rows < 1: nonnull_rows = int(nonnull_rows * len(df)) if 0 < nonnull_cols < 1: nonnull_cols = int(nonnull_cols * len(df.columns)) for label in df.columns: series = df[label].copy() if series.dtype in (np.dtype('O'), np.dtype('U'), np.dtype('S')): for nanstr in nanstrs: series[series == nanstr] = np.nan df[label] = series # in iPython Notebook, try dropping with lower thresholds, checking column and row count each time print('The raw table shape is {}'.format(df.shape)) df = df.dropna(axis=1, thresh=nonnull_rows) print('After dropping columns with fewer than {} nonnull values, the table shape is {}'.format(nonnull_rows, df.shape)) df = df.dropna(axis=0, thresh=nonnull_cols) print('After dropping rows with fewer than {} nonnull values, the table shape is {}'.format(nonnull_cols, df.shape)) for label in df.columns: series = df[label].copy() if series.dtype == np.dtype('O'): nonnull_dtype = series.dropna(inplace=False).values.dtype if nonnull_dtype == np.dtype('O'): series[series.isnull()] = nullstr df[label] = series else: df[label] = series.astype(nonnull_dtype) return df
[ "def", "dropna", "(", "df", ",", "nonnull_rows", "=", "100", ",", "nonnull_cols", "=", "50", ",", "nanstrs", "=", "(", "'nan'", ",", "'NaN'", ",", "''", ")", ",", "nullstr", "=", "''", ")", ":", "if", "0", "<", "nonnull_rows", "<", "1", ":", "non...
Drop columns/rows with too many NaNs and replace NaNs in columns of strings with '' >>> df = pd.DataFrame([['nan',np.nan,'str'],[np.nan,0.1,'and'],[2.0,None,np.nan]]) >>> dropna(df) Empty DataFrame Columns: [] Index: [] >>> dropna(df, nonnull_cols=0, nonnull_rows=0) 0 1 2 0 NaN str 1 0.1 and 2 2 NaN
[ "Drop", "columns", "/", "rows", "with", "too", "many", "NaNs", "and", "replace", "NaNs", "in", "columns", "of", "strings", "with" ]
python
train
43.775
pytroll/satpy
satpy/writers/__init__.py
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/writers/__init__.py#L284-L302
def add_text(orig, dc, img, text=None): """Add text to an image using the pydecorate package. All the features of pydecorate's ``add_text`` are available. See documentation of :doc:`pydecorate:index` for more info. """ LOG.info("Add text to image.") dc.add_text(**text) arr = da.from_array(np.array(img) / 255.0, chunks=CHUNK_SIZE) new_data = xr.DataArray(arr, dims=['y', 'x', 'bands'], coords={'y': orig.data.coords['y'], 'x': orig.data.coords['x'], 'bands': list(img.mode)}, attrs=orig.data.attrs) return XRImage(new_data)
[ "def", "add_text", "(", "orig", ",", "dc", ",", "img", ",", "text", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"Add text to image.\"", ")", "dc", ".", "add_text", "(", "*", "*", "text", ")", "arr", "=", "da", ".", "from_array", "(", "np", ...
Add text to an image using the pydecorate package. All the features of pydecorate's ``add_text`` are available. See documentation of :doc:`pydecorate:index` for more info.
[ "Add", "text", "to", "an", "image", "using", "the", "pydecorate", "package", "." ]
python
train
35.526316