_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q242700
RemoteLRS.get_endpoint_server_root
train
def get_endpoint_server_root(self): """Parses RemoteLRS object's endpoint and returns its root :return: Root of the RemoteLRS object endpoint :rtype: unicode """ parsed = urlparse(self._endpoint) root = parsed.scheme + "://" + parsed.hostname if parsed.port is n...
python
{ "resource": "" }
q242701
SerializableBase.from_json
train
def from_json(cls, json_data): """Tries to convert a JSON representation to an object of the same type as self A class can provide a _fromJSON implementation in order to do specific type checking or other custom implementation details. This method will throw a ValueError for inv...
python
{ "resource": "" }
q242702
SerializableBase.to_json
train
def to_json(self, version=Version.latest): """Tries to convert an object into a JSON representation and return the resulting string An Object can define how it is serialized by overriding the as_version() implementation. A caller may further define how the object is serialized b...
python
{ "resource": "" }
q242703
SerializableBase.as_version
train
def as_version(self, version=Version.latest): """Returns a dict that has been modified based on versioning in order to be represented in JSON properly A class should overload as_version(self, version) implementation in order to tailor a more specific representation :param versi...
python
{ "resource": "" }
q242704
SerializableBase._filter_none
train
def _filter_none(obj): """Filters out attributes set to None prior to serialization, and returns a new object without those attributes. This saves the serializer from sending empty bytes over the network. This method also fixes the keys to look as expected by ignoring a leading '_' if it...
python
{ "resource": "" }
q242705
jsonify_timedelta
train
def jsonify_timedelta(value): """Converts a `datetime.timedelta` to an ISO 8601 duration string for JSON-ification. :param value: something to convert :type value: datetime.timedelta :return: the value after conversion :rtype unicode """ assert isinstance(value, datetime.timedelta) ...
python
{ "resource": "" }
q242706
zip_dicts
train
def zip_dicts(left, right, prefix=()): """ Modified zip through two dictionaries. Iterate through all keys of left dictionary, returning: - A nested path - A value and parent for both dictionaries """ for key, left_value in left.items(): path = prefix + (key, ) right...
python
{ "resource": "" }
q242707
configure
train
def configure(defaults, metadata, loader): """ Build a fresh configuration. :params defaults: a nested dictionary of keys and their default values :params metadata: the graph metadata :params loader: a configuration loader """ config = Configuration(defaults) config.merge(loader(metada...
python
{ "resource": "" }
q242708
boolean
train
def boolean(value): """ Configuration-friendly boolean type converter. Supports both boolean-valued and string-valued inputs (e.g. from env vars). """ if isinstance(value, bool): return value if value == "": return False return strtobool(value)
python
{ "resource": "" }
q242709
_load_from_environ
train
def _load_from_environ(metadata, value_func=None): """ Load configuration from environment variables. Any environment variable prefixed with the metadata's name will be used to recursively set dictionary keys, splitting on '__'. :param value_func: a mutator for the envvar's value (if any) """...
python
{ "resource": "" }
q242710
load_from_dict
train
def load_from_dict(dct=None, **kwargs): """ Load configuration from a dictionary. """ dct = dct or dict() dct.update(kwargs) def _load_from_dict(metadata): return dict(dct) return _load_from_dict
python
{ "resource": "" }
q242711
binding
train
def binding(key, registry=None): """ Creates a decorator that binds a factory function to a key. :param key: the binding key :param: registry: the registry to bind to; defaults to the global registry """ if registry is None: registry = _registry def decorator(func): regist...
python
{ "resource": "" }
q242712
defaults
train
def defaults(**kwargs): """ Creates a decorator that saves the provided kwargs as defaults for a factory function. """ def decorator(func): setattr(func, DEFAULTS, kwargs) return func return decorator
python
{ "resource": "" }
q242713
_invoke_hook
train
def _invoke_hook(hook_name, target): """ Generic hook invocation. """ try: for value in getattr(target, hook_name): func, args, kwargs = value func(target, *args, **kwargs) except AttributeError: # no hook defined pass except (TypeError, ValueErro...
python
{ "resource": "" }
q242714
_register_hook
train
def _register_hook(hook_name, target, func, *args, **kwargs): """ Generic hook registration. """ call = (func, args, kwargs) try: getattr(target, hook_name).append(call) except AttributeError: setattr(target, hook_name, [call])
python
{ "resource": "" }
q242715
on_resolve
train
def on_resolve(target, func, *args, **kwargs): """ Register a resolution hook. """ return _register_hook(ON_RESOLVE, target, func, *args, **kwargs)
python
{ "resource": "" }
q242716
create_cache
train
def create_cache(name): """ Create a cache by name. Defaults to `NaiveCache` """ caches = { subclass.name(): subclass for subclass in Cache.__subclasses__() } return caches.get(name, NaiveCache)()
python
{ "resource": "" }
q242717
get_config_filename
train
def get_config_filename(metadata): """ Derive a configuration file name from the FOO_SETTINGS environment variable. """ envvar = "{}__SETTINGS".format(underscore(metadata.name).upper()) try: return environ[envvar] except KeyError: return None
python
{ "resource": "" }
q242718
_load_from_file
train
def _load_from_file(metadata, load_func): """ Load configuration from a file. The file path is derived from an environment variable named after the service of the form FOO_SETTINGS. """ config_filename = get_config_filename(metadata) if config_filename is None: return dict() w...
python
{ "resource": "" }
q242719
ScopedFactory.get_scoped_config
train
def get_scoped_config(self, graph): """ Compute a configuration using the current scope. """ def loader(metadata): if not self.current_scope: target = graph.config else: target = graph.config.get(self.current_scope, {}) ...
python
{ "resource": "" }
q242720
ScopedFactory.resolve
train
def resolve(self, graph): """ Resolve a scoped component, respecting the graph cache. """ cached = graph.get(self.scoped_key) if cached: return cached component = self.create(graph) graph.assign(self.scoped_key, component) return component
python
{ "resource": "" }
q242721
ScopedFactory.create
train
def create(self, graph): """ Create a new scoped component. """ scoped_config = self.get_scoped_config(graph) scoped_graph = ScopedGraph(graph, scoped_config) return self.func(scoped_graph)
python
{ "resource": "" }
q242722
ScopedFactory.infect
train
def infect(cls, graph, key, default_scope=None): """ Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding """ f...
python
{ "resource": "" }
q242723
load_each
train
def load_each(*loaders): """ Loader factory that combines a series of loaders. """ def _load_each(metadata): return merge( loader(metadata) for loader in loaders ) return _load_each
python
{ "resource": "" }
q242724
Registry.all
train
def all(self): """ Return a synthetic dictionary of all factories. """ return { key: value for key, value in chain(self.entry_points.items(), self.factories.items()) }
python
{ "resource": "" }
q242725
Registry.defaults
train
def defaults(self): """ Return a nested dicionary of all registered factory defaults. """ return { key: get_defaults(value) for key, value in self.all.items() }
python
{ "resource": "" }
q242726
Registry.bind
train
def bind(self, key, factory): """ Bind a factory to a key. :raises AlreadyBoundError: if the key is alrady bound """ if key in self.factories: raise AlreadyBoundError(key) else: self.factories[key] = factory
python
{ "resource": "" }
q242727
Registry.resolve
train
def resolve(self, key): """ Resolve a key to a factory. Attempts to resolve explicit bindings and entry points, preferring explicit bindings. :raises NotBoundError: if the key cannot be resolved """ try: return self._resolve_from_binding(key) ...
python
{ "resource": "" }
q242728
expand_config
train
def expand_config(dct, separator='.', skip_to=0, key_func=lambda key: key.lower(), key_parts_filter=lambda key_parts: True, value_func=lambda value: value): """ Expand a dictionary recursively by splitting keys along the s...
python
{ "resource": "" }
q242729
create_object_graph
train
def create_object_graph(name, debug=False, testing=False, import_name=None, root_path=None, loader=load_from_environ, registry=_registry, profiler=None,...
python
{ "resource": "" }
q242730
ObjectGraph._reserve
train
def _reserve(self, key): """ Reserve a component's binding temporarily. Protects against cycles. """ self.assign(key, RESERVED) try: yield finally: del self._cache[key]
python
{ "resource": "" }
q242731
ObjectGraph._resolve_key
train
def _resolve_key(self, key): """ Attempt to lazily create a component. :raises NotBoundError: if the component does not have a bound factory :raises CyclicGraphError: if the factory function requires a cycle :raises LockedGraphError: if the graph is locked """ wi...
python
{ "resource": "" }
q242732
ScopedProxy.scoped_to
train
def scoped_to(self, scope): """ Context manager to switch scopes. """ previous_scope = self.__factory__.current_scope try: self.__factory__.current_scope = scope yield finally: self.__factory__.current_scope = previous_scope
python
{ "resource": "" }
q242733
ScopedProxy.scoped
train
def scoped(self, func): """ Decorator to switch scopes. """ @wraps(func) def wrapper(*args, **kwargs): scope = kwargs.get("scope", self.__factory__.default_scope) with self.scoped_to(scope): return func(*args, **kwargs) return wrap...
python
{ "resource": "" }
q242734
Configuration.merge
train
def merge(self, dct=None, **kwargs): """ Recursively merge a dictionary or kwargs into the current dict. """ if dct is None: dct = {} if kwargs: dct.update(**kwargs) for key, value in dct.items(): if all(( isinstan...
python
{ "resource": "" }
q242735
Requirement.validate
train
def validate(self, metadata, path, value): """ Validate this requirement. """ if isinstance(value, Requirement): # if the RHS is still a Requirement object, it was not set if metadata.testing and self.mock_value is not None: value = self.mock_valu...
python
{ "resource": "" }
q242736
ConjureDecoder.decode_conjure_union_type
train
def decode_conjure_union_type(cls, obj, conjure_type): """Decodes json into a conjure union type. Args: obj: the json object to decode conjure_type: a class object which is the union type we're decoding into Returns: An instance of type conjur...
python
{ "resource": "" }
q242737
ConjureDecoder.decode_conjure_enum_type
train
def decode_conjure_enum_type(cls, obj, conjure_type): """Decodes json into a conjure enum type. Args: obj: the json object to decode conjure_type: a class object which is the enum type we're decoding into. Returns: An instance of enum of type ...
python
{ "resource": "" }
q242738
ConjureDecoder.decode_list
train
def decode_list(cls, obj, element_type): # type: (List[Any], ConjureTypeType) -> List[Any] """Decodes json into a list, handling conversion of the elements. Args: obj: the json object to decode element_type: a class object which is the conjure type of the...
python
{ "resource": "" }
q242739
ConjureDecoder.do_decode
train
def do_decode(cls, obj, obj_type): # type: (Any, ConjureTypeType) -> Any """Decodes json into the specified type Args: obj: the json object to decode element_type: a class object which is the type we're decoding into. """ if inspect.isclass(obj_type) and ...
python
{ "resource": "" }
q242740
ConjureEncoder.encode_conjure_bean_type
train
def encode_conjure_bean_type(cls, obj): # type: (ConjureBeanType) -> Any """Encodes a conjure bean into json""" encoded = {} # type: Dict[str, Any] for attribute_name, field_definition in obj._fields().items(): encoded[field_definition.identifier] = cls.do_encode( ...
python
{ "resource": "" }
q242741
ConjureEncoder.encode_conjure_union_type
train
def encode_conjure_union_type(cls, obj): # type: (ConjureUnionType) -> Any """Encodes a conjure union into json""" encoded = {} # type: Dict[str, Any] encoded["type"] = obj.type for attr, field_definition in obj._options().items(): if field_definition.identifier == o...
python
{ "resource": "" }
q242742
ConjureEncoder.do_encode
train
def do_encode(cls, obj): # type: (Any) -> Any """Encodes the passed object into json""" if isinstance(obj, ConjureBeanType): return cls.encode_conjure_bean_type(obj) elif isinstance(obj, ConjureUnionType): return cls.encode_conjure_union_type(obj) elif i...
python
{ "resource": "" }
q242743
GeoPoint.radians_to
train
def radians_to(self, other): """ Returns the distance from this GeoPoint to another in radians. :param other: point the other GeoPoint :type other: GeoPoint :rtype: float """ d2r = math.pi / 180.0 lat1rad = self.latitude * d2r long1rad = self.long...
python
{ "resource": "" }
q242744
Abstract.append
train
def append(self, item): """Append item to end of model""" self.beginInsertRows(QtCore.QModelIndex(), self.rowCount(), self.rowCount()) self.items.append(item) self.endInsertRows()
python
{ "resource": "" }
q242745
Window.on_item_toggled
train
def on_item_toggled(self, index, state=None): """An item is requesting to be toggled""" if not index.data(model.IsIdle): return self.info("Cannot toggle") if not index.data(model.IsOptional): return self.info("This item is mandatory") if state is None: ...
python
{ "resource": "" }
q242746
Window.on_comment_entered
train
def on_comment_entered(self): """The user has typed a comment""" text_edit = self.findChild(QtWidgets.QWidget, "CommentBox") comment = text_edit.text() # Store within context context = self.controller.context context.data["comment"] = comment placeholder = self....
python
{ "resource": "" }
q242747
Window.on_finished
train
def on_finished(self): """Finished signal handler""" self.controller.is_running = False error = self.controller.current_error if error is not None: self.info(self.tr("Stopped due to error(s), see Terminal.")) else: self.info(self.tr("Finished successfully...
python
{ "resource": "" }
q242748
Window.reset
train
def reset(self): """Prepare GUI for reset""" self.info(self.tr("About to reset..")) models = self.data["models"] models["instances"].store_checkstate() models["plugins"].store_checkstate() # Reset current ids to secure no previous instances get mixed in. models...
python
{ "resource": "" }
q242749
Window.closeEvent
train
def closeEvent(self, event): """Perform post-flight checks before closing Make sure processing of any kind is wrapped up before closing """ # Make it snappy, but take care to clean it all up. # TODO(marcus): Enable GUI to return on problem, such # as asking whether or ...
python
{ "resource": "" }
q242750
Window.reject
train
def reject(self): """Handle ESC key""" if self.controller.is_running: self.info(self.tr("Stopping..")) self.controller.is_running = False
python
{ "resource": "" }
q242751
Window.info
train
def info(self, message): """Print user-facing information Arguments: message (str): Text message for the user """ info = self.findChild(QtWidgets.QLabel, "Info") info.setText(message) # Include message in terminal self.data["models"]["terminal"].ap...
python
{ "resource": "" }
q242752
LogView.rowsInserted
train
def rowsInserted(self, parent, start, end): """Automatically scroll to bottom on each new item added Arguments: parent (QtCore.QModelIndex): The model itself, since this is a list start (int): Start index of item end (int): End index of item """ sup...
python
{ "resource": "" }
q242753
Controller.reset
train
def reset(self): """Discover plug-ins and run collection""" self.context = pyblish.api.Context() self.plugins = pyblish.api.discover() self.was_discovered.emit() self.pair_generator = None self.current_pair = (None, None) self.current_error = None self....
python
{ "resource": "" }
q242754
Controller._load
train
def _load(self): """Initiate new generator and load first pair""" self.is_running = True self.pair_generator = self._iterator(self.plugins, self.context) self.current_pair = next(self.pair_generator, (None, None)) self.current_error = ...
python
{ "resource": "" }
q242755
Controller._process
train
def _process(self, plugin, instance=None): """Produce `result` from `plugin` and `instance` :func:`process` shares state with :func:`_iterator` such that an instance/plugin pair can be fetched and processed in isolation. Arguments: plugin (pyblish.api.Plugin): Produce resul...
python
{ "resource": "" }
q242756
Controller._run
train
def _run(self, until=float("inf"), on_finished=lambda: None): """Process current pair and store next pair for next process Arguments: until (pyblish.api.Order, optional): Keep fetching next() until this order, default value is infinity. on_finished (callable, opt...
python
{ "resource": "" }
q242757
Controller._iterator
train
def _iterator(self, plugins, context): """Yield next plug-in and instance to process. Arguments: plugins (list): Plug-ins to process context (pyblish.api.Context): Context to process """ test = pyblish.logic.registered_test() for plug, instance in pybl...
python
{ "resource": "" }
q242758
Controller.cleanup
train
def cleanup(self): """Forcefully delete objects from memory In an ideal world, this shouldn't be necessary. Garbage collection guarantees that anything without reference is automatically removed. However, because this application is designed to be run multiple times fro...
python
{ "resource": "" }
q242759
get_root_uri
train
def get_root_uri(uri): """Return root URI - strip query and fragment.""" chunks = urlsplit(uri) return urlunsplit((chunks.scheme, chunks.netloc, chunks.path, '', ''))
python
{ "resource": "" }
q242760
collect
train
def collect(since, to, top=DEFAULT_TOP): """Collect the CSP report. @returntype: CspReportSummary """ summary = CspReportSummary(since, to, top=top) queryset = CSPReport.objects.filter(created__range=(since, to)) valid_queryset = queryset.filter(is_valid=True) invalid_queryset = queryset.fi...
python
{ "resource": "" }
q242761
ViolationInfo.append
train
def append(self, report): """Append a new CSP report.""" assert report not in self.examples self.count += 1 if len(self.examples) < self.top: self.examples.append(report)
python
{ "resource": "" }
q242762
CspReportSummary.render
train
def render(self): """Render the summary.""" engine = Engine() return engine.from_string(SUMMARY_TEMPLATE).render(Context(self.__dict__))
python
{ "resource": "" }
q242763
_parse_date_input
train
def _parse_date_input(date_input, default_offset=0): """Parses a date input.""" if date_input: try: return parse_date_input(date_input) except ValueError as err: raise CommandError(force_text(err)) else: return get_midnight() - timedelta(days=default_offset)
python
{ "resource": "" }
q242764
CSPReport.nice_report
train
def nice_report(self): """Return a nicely formatted original report.""" if not self.json: return '[no CSP report data]' try: data = json.loads(self.json) except ValueError: return "Invalid CSP report: '{}'".format(self.json) if 'csp-report' not...
python
{ "resource": "" }
q242765
CSPReport.from_message
train
def from_message(cls, message): """Creates an instance from CSP report message. If the message is not valid, the result will still have as much fields set as possible. @param message: JSON encoded CSP report. @type message: text """ self = cls(json=message) try:...
python
{ "resource": "" }
q242766
CSPReport.data
train
def data(self): """ Returns self.json loaded as a python object. """ try: data = self._data except AttributeError: data = self._data = json.loads(self.json) return data
python
{ "resource": "" }
q242767
CSPReport.json_as_html
train
def json_as_html(self): """ Print out self.json in a nice way. """ # To avoid circular import from cspreports import utils formatted_json = utils.format_report(self.json) return mark_safe("<pre>\n%s</pre>" % escape(formatted_json))
python
{ "resource": "" }
q242768
process_report
train
def process_report(request): """ Given the HTTP request of a CSP violation report, log it in the required ways. """ if config.EMAIL_ADMINS: email_admins(request) if config.LOG: log_report(request) if config.SAVE: save_report(request) if config.ADDITIONAL_HANDLERS: run...
python
{ "resource": "" }
q242769
get_additional_handlers
train
def get_additional_handlers(): """ Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS. """ global _additional_handlers if not isinstance(_additional_handlers, list): handlers = [] for name in config.ADDITIONAL_HANDLERS: module_name, function_name ...
python
{ "resource": "" }
q242770
parse_date_input
train
def parse_date_input(value): """Return datetime based on the user's input. @param value: User's input @type value: str @raise ValueError: If the input is not valid. @return: Datetime of the beginning of the user's date. """ try: limit = parse_date(value) except ValueError: ...
python
{ "resource": "" }
q242771
get_midnight
train
def get_midnight(): """Return last midnight in localtime as datetime. @return: Midnight datetime """ limit = now() if settings.USE_TZ: limit = localtime(limit) return limit.replace(hour=0, minute=0, second=0, microsecond=0)
python
{ "resource": "" }
q242772
StimelaJob.python_job
train
def python_job(self, function, parameters=None): """ Run python function function : Python callable to execute name : Name of function (if not given, will used function.__name__) parameters : Parameters to parse to function label : Function label...
python
{ "resource": "" }
q242773
pull
train
def pull(image, store_path, docker=True): """ pull an image """ if docker: fp = "docker://{0:s}".format(image) else: fp = image utils.xrun("singularity", ["pull", "--force", "--name", store_path, fp]) return 0
python
{ "resource": "" }
q242774
Container.start
train
def start(self, *args): """ Create a singularity container instance """ if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Instantiating container [{0:s}]. Timeout set to {1:d}. The cont...
python
{ "resource": "" }
q242775
Container.run
train
def run(self, *args): """ Run a singularity container instance """ if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Starting container [{0:s}]. Timeout set to {1:d}. The container ID i...
python
{ "resource": "" }
q242776
Container.stop
train
def stop(self, *args): """ Stop a singularity container instance """ if self.volumes: volumes = " --bind " + " --bind ".join(self.volumes) else: volumes = "" self._print("Stopping container [{}]. The container ID is printed below.".forma...
python
{ "resource": "" }
q242777
build
train
def build(image, build_path, tag=None, build_args=None, fromline=None, args=[]): """ build a docker image""" if tag: image = ":".join([image, tag]) bdir = tempfile.mkdtemp() os.system('cp -r {0:s}/* {1:s}'.format(build_path, bdir)) if build_args: stdw = tempfile.NamedTemporaryFile(...
python
{ "resource": "" }
q242778
pull
train
def pull(image, tag=None): """ pull a docker image """ if tag: image = ":".join([image, tag]) utils.xrun("docker pull", [image])
python
{ "resource": "" }
q242779
info
train
def info(cabdir, header=False): """ prints out help information about a cab """ # First check if cab exists pfile = "{}/parameters.json".format(cabdir) if not os.path.exists(pfile): raise RuntimeError("Cab could not be found at : {}".format(cabdir)) # Get cab info cab_definition = cab.C...
python
{ "resource": "" }
q242780
xrun
train
def xrun(command, options, log=None, _log_container_as_started=False, logfile=None, timeout=-1, kill_callback=None): """ Run something on command line. Example: _run("ls", ["-lrt", "../"]) """ cmd = " ".join([command] + list(map(str, options)) ) def _print_info(msg): if ms...
python
{ "resource": "" }
q242781
sumcols
train
def sumcols(msname, col1=None, col2=None, outcol=None, cols=None, suntract=False): """ add col1 to col2, or sum columns in 'cols' list. If subtract, subtract col2 from col1 """ from pyrap.tables import table tab = table(msname, readonly=False) if cols: data = 0 for col in co...
python
{ "resource": "" }
q242782
compute_vis_noise
train
def compute_vis_noise(msname, sefd, spw_id=0): """Computes nominal per-visibility noise""" from pyrap.tables import table tab = table(msname) spwtab = table(msname + "/SPECTRAL_WINDOW") freq0 = spwtab.getcol("CHAN_FREQ")[spw_id, 0] wavelength = 300e+6/freq0 bw = spwtab.getcol("CHAN_WIDTH")...
python
{ "resource": "" }
q242783
fitsInfo
train
def fitsInfo(fitsname = None): """ Get fits info """ hdu = pyfits.open(fitsname) hdr = hdu[0].header ra = hdr['CRVAL1'] dra = abs(hdr['CDELT1']) raPix = hdr['CRPIX1'] dec = hdr['CRVAL2'] ddec = abs(hdr['CDELT2']) decPix = hdr['CRPIX2'] freq0 = 0 for i in range(1,hdr['...
python
{ "resource": "" }
q242784
sky2px
train
def sky2px(wcs,ra,dec,dra,ddec,cell, beam): """convert a sky region to pixel positions""" dra = beam if dra<beam else dra # assume every source is at least as large as the psf ddec = beam if ddec<beam else ddec offsetDec = int((ddec/2.)/cell) offsetRA = int((dra/2.)/cell) if offsetDec%2==1: ...
python
{ "resource": "" }
q242785
Quality.get_components
train
def get_components(self, root='C', visible=False): """ Get components of chord quality :param str root: the root note of the chord :param bool visible: returns the name of notes if True :rtype: list[str|int] :return: components of chord quality """ root_val = not...
python
{ "resource": "" }
q242786
Quality.append_on_chord
train
def append_on_chord(self, on_chord, root): """ Append on chord To create Am7/G q = Quality('m7') q.append_on_chord('G', root='A') :param str on_chord: bass note of the chord :param str root: root note of the chord """ root_val = note_to_val(root) ...
python
{ "resource": "" }
q242787
Quality.append_note
train
def append_note(self, note, root, scale=0): """ Append a note to quality :param str note: note to append on quality :param str root: root note of chord :param int scale: key scale """ root_val = note_to_val(root) note_val = note_to_val(note) - root_val + scale * ...
python
{ "resource": "" }
q242788
Quality.append_notes
train
def append_notes(self, notes, root, scale=0): """ Append notes to quality :param list[str] notes: notes to append on quality :param str root: root note of chord :param int scale: key scale """ for note in notes: self.append_note(note, root, scale)
python
{ "resource": "" }
q242789
ChordProgression.insert
train
def insert(self, index, chord): """ Insert a chord to chord progressions :param int index: Index to insert a chord :type chord: str|pychord.Chord :param chord: A chord to insert :return: """ self._chords.insert(index, as_chord(chord))
python
{ "resource": "" }
q242790
as_chord
train
def as_chord(chord): """ convert from str to Chord instance if input is str :type chord: str|pychord.Chord :param chord: Chord name or Chord instance :rtype: pychord.Chord :return: Chord instance """ if isinstance(chord, Chord): return chord elif isinstance(chord, str): ...
python
{ "resource": "" }
q242791
Chord.transpose
train
def transpose(self, trans, scale="C"): """ Transpose the chord :param int trans: Transpose key :param str scale: key scale :return: """ if not isinstance(trans, int): raise TypeError("Expected integers, not {}".format(type(trans))) self._root = transp...
python
{ "resource": "" }
q242792
Chord.components
train
def components(self, visible=True): """ Return the component notes of chord :param bool visible: returns the name of notes if True else list of int :rtype: list[(str or int)] :return: component notes of chord """ if self._on: self._quality.append_on_chord(sel...
python
{ "resource": "" }
q242793
Chord._parse
train
def _parse(self, chord): """ parse a chord :param str chord: Name of chord. """ root, quality, appended, on = parse(chord) self._root = root self._quality = quality self._appended = appended self._on = on
python
{ "resource": "" }
q242794
transpose_note
train
def transpose_note(note, transpose, scale="C"): """ Transpose a note :param str note: note to transpose :type transpose: int :param str scale: key scale :rtype: str :return: transposed note """ val = note_to_val(note) val += transpose return val_to_note(val, scale)
python
{ "resource": "" }
q242795
parse
train
def parse(chord): """ Parse a string to get chord component :param str chord: str expression of a chord :rtype: (str, pychord.Quality, str, str) :return: (root, quality, appended, on) """ if len(chord) > 1 and chord[1] in ("b", "#"): root = chord[:2] rest = chord[2:] else: ...
python
{ "resource": "" }
q242796
check_note
train
def check_note(note, chord): """ Return True if the note is valid. :param str note: note to check its validity :param str chord: the chord which includes the note :rtype: bool """ if note not in NOTE_VAL_DICT: raise ValueError("Invalid chord {}: Unknown note {}".format(chord, note)) ...
python
{ "resource": "" }
q242797
note_to_chord
train
def note_to_chord(notes): """ Convert note list to chord list :param list[str] notes: list of note arranged from lower note. ex) ["C", "Eb", "G"] :rtype: list[pychord.Chord] :return: list of chord """ if not notes: raise ValueError("Please specify notes which consist a chord.") root...
python
{ "resource": "" }
q242798
notes_to_positions
train
def notes_to_positions(notes, root): """ Get notes positions. ex) notes_to_positions(["C", "E", "G"], "C") -> [0, 4, 7] :param list[str] notes: list of notes :param str root: the root note :rtype: list[int] :return: list of note positions """ root_pos = note_to_val(root) current_po...
python
{ "resource": "" }
q242799
get_all_rotated_notes
train
def get_all_rotated_notes(notes): """ Get all rotated notes get_all_rotated_notes([1,3,5]) -> [[1,3,5],[3,5,1],[5,1,3]] :type notes: list[str] :rtype: list[list[str]] """ notes_list = [] for x in range(len(notes)): notes_list.append(notes[x:] + notes[:x]) return notes_list
python
{ "resource": "" }