_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q8000
crud_for_app
train
def crud_for_app(app_label, urlprefix=None): """ Returns list of ``url`` items to CRUD an app. """ if urlprefix is None: urlprefix = app_label + '/' app = apps.get_app_config(app_label) urls = [] for model in app.get_models(): urls += crud_for_model(model, urlprefix) retu...
python
{ "resource": "" }
q8001
CRUDMixin.get_context_data
train
def get_context_data(self, **kwargs): """ Adds available urls and names. """ context = super(CRUDMixin, self).get_context_data(**kwargs) context.update({ 'model_verbose_name': self.model._meta.verbose_name, 'model_verbose_name_plural': self.model._meta.ver...
python
{ "resource": "" }
q8002
CRUDMixin.get_template_names
train
def get_template_names(self): """ Adds crud_template_name to default template names. """ names = super(CRUDMixin, self).get_template_names() if self.crud_template_name: names.append(self.crud_template_name) return names
python
{ "resource": "" }
q8003
install
train
def install(): """Install Fleaker. In a function so we can protect this file so it's only run when we explicitly invoke it and not, say, when py.test collects all Python modules. """ _version_re = re.compile(r"__version__\s+=\s+(.*)") # pylint: disable=invalid-name with open('./fleaker/__...
python
{ "resource": "" }
q8004
JSONField.python_value
train
def python_value(self, value): """Return the JSON in the database as a ``dict``. Returns: dict: The field run through json.loads """ value = super(JSONField, self).python_value(value) if value is not None: return flask.json.loads(value, **self._load_kwar...
python
{ "resource": "" }
q8005
JSONField.db_value
train
def db_value(self, value): """Store the value in the database. If the value is a dict like object, it is converted to a string before storing. """ # Everything is encoded being before being surfaced value = flask.json.dumps(value) return super(JSONField, self).d...
python
{ "resource": "" }
q8006
SearchMixin.search
train
def search(cls, term, fields=()): """Generic SQL search function that uses SQL ``LIKE`` to search the database for matching records. The records are sorted by their relavancey to the search term. The query searches and sorts on the folling criteria, in order, where the target st...
python
{ "resource": "" }
q8007
ForeignKeyField._add_to_schema
train
def _add_to_schema(self, field_name, schema): """Set the ``attribute`` attr to the field in question so this always gets deserialzed into the field name without ``_id``. Args: field_name (str): The name of the field (the attribute name being set in the schema). ...
python
{ "resource": "" }
q8008
ForeignKeyField._serialize
train
def _serialize(self, value, attr, obj): """Grab the ID value off the Peewee model so we serialize an ID back. """ # this might be an optional field if value: value = value.id return super(ForeignKeyField, self)._serialize(value, attr, obj)
python
{ "resource": "" }
q8009
_discover_ideal_backend
train
def _discover_ideal_backend(orm_backend): """Auto-discover the ideal backend based on what is installed. Right now, handles discovery of: * PeeWee * SQLAlchemy Args: orm_backend (str): The ``orm_backend`` value that was passed to the ``create_app`` function. That is, the OR...
python
{ "resource": "" }
q8010
ORMAwareApp._init_peewee_ext
train
def _init_peewee_ext(cls, app, dummy_configuration=None, dummy_configure_args=None): """Init the actual PeeWee extension with the app that was created. Since PeeWee requires the ``DATABASE`` config parameter to be present IMMEDIATELY upon initializing the application, w...
python
{ "resource": "" }
q8011
MultiStageConfigurableApp.configure
train
def configure(self, *args, **kwargs): """Configure the Application through a varied number of sources of different types. This function chains multiple possible configuration methods together in order to just "make it work". You can pass multiple configuration sources in to the ...
python
{ "resource": "" }
q8012
MultiStageConfigurableApp._configure_from_module
train
def _configure_from_module(self, item): """Configure from a module by import path. Effectively, you give this an absolute or relative import path, it will import it, and then pass the resulting object to ``_configure_from_object``. Args: item (str): ...
python
{ "resource": "" }
q8013
MultiStageConfigurableApp._configure_from_mapping
train
def _configure_from_mapping(self, item, whitelist_keys=False, whitelist=None): """Configure from a mapping, or dict, like object. Args: item (dict): A dict-like object that we can pluck values from. Keyword Args: whitelist...
python
{ "resource": "" }
q8014
MultiStageConfigurableApp.configure_from_environment
train
def configure_from_environment(self, whitelist_keys=False, whitelist=None): """Configure from the entire set of available environment variables. This is really a shorthand for grabbing ``os.environ`` and passing to :meth:`_configure_from_mapping`. As always, only uppercase keys are loa...
python
{ "resource": "" }
q8015
MultiStageConfigurableApp._run_post_configure_callbacks
train
def _run_post_configure_callbacks(self, configure_args): """Run all post configure callbacks we have stored. Functions are passed the configuration that resulted from the call to :meth:`configure` as the first argument, in an immutable form; and are given the arguments passed to :meth:`...
python
{ "resource": "" }
q8016
Schema.make_instance
train
def make_instance(cls, data): """Validate the data and create a model instance from the data. Args: data (dict): The unserialized data to insert into the new model instance through it's constructor. Returns: peewee.Model|sqlalchemy.Model: The model insta...
python
{ "resource": "" }
q8017
Schema.invalid_fields
train
def invalid_fields(self, data, original_data): """Validator that checks if any keys provided aren't in the schema. Say your schema has support for keys ``a`` and ``b`` and the data provided has keys ``a``, ``b``, and ``c``. When the data is loaded into the schema, a :class:`marshmallow....
python
{ "resource": "" }
q8018
ArrowDateTimeField.python_value
train
def python_value(self, value): """Return the value in the data base as an arrow object. Returns: arrow.Arrow: An instance of arrow with the field filled in. """ value = super(ArrowDateTimeField, self).python_value(value) if (isinstance(value, (datetime.datetime, dat...
python
{ "resource": "" }
q8019
ArrowDateTimeField.db_value
train
def db_value(self, value): """Convert the Arrow instance to a datetime for saving in the db.""" if isinstance(value, string_types): value = arrow.get(value) if isinstance(value, arrow.Arrow): value = value.datetime return super(ArrowDateTimeField, self).db_value...
python
{ "resource": "" }
q8020
Component._context_callbacks
train
def _context_callbacks(app, key, original_context=_CONTEXT_MISSING): """Register the callbacks we need to properly pop and push the app-local context for a component. Args: app (flask.Flask): The app who this context belongs to. This is the only sender our Blinker si...
python
{ "resource": "" }
q8021
Component.update_context
train
def update_context(self, context, app=None): """Replace the component's context with a new one. Args: context (dict): The new context to set this component's context to. Keyword Args: app (flask.Flask, optional): The app to update this context for. If no...
python
{ "resource": "" }
q8022
Component.clear_context
train
def clear_context(self, app=None): """Clear the component's context. Keyword Args: app (flask.Flask, optional): The app to clear this component's context for. If omitted, the value from ``Component.app`` is used. """ if (app is None and self._...
python
{ "resource": "" }
q8023
Component.app
train
def app(self): """Internal method that will supply the app to use internally. Returns: flask.Flask: The app to use within the component. Raises: RuntimeError: This is raised if no app was provided to the component and the method is being called outside o...
python
{ "resource": "" }
q8024
Component._get_context_name
train
def _get_context_name(self, app=None): """Generate the name of the context variable for this component & app. Because we store the ``context`` in a Local so the component can be used across multiple apps, we cannot store the context on the instance itself. This function will generate a ...
python
{ "resource": "" }
q8025
BaseApplication.create_app
train
def create_app(cls, import_name, **settings): """Create a standard Fleaker web application. This is the main entrypoint for creating your Fleaker application. Instead of defining your own app factory function, it's preferred that you use :meth:`create_app`, which is responsible for auto...
python
{ "resource": "" }
q8026
FleakerLogFormatter.format
train
def format(self, record): """Format the log record.""" levelname = getattr(record, 'levelname', None) record.levelcolor = '' record.endlevelcolor = '' if levelname: level_color = getattr(self.TermColors, levelname, '') record.levelcolor = level_color ...
python
{ "resource": "" }
q8027
FleakerBaseException.errorhandler_callback
train
def errorhandler_callback(cls, exc): """This function should be called in the global error handlers. This will allow for consolidating of cleanup tasks if the exception bubbles all the way to the top of the stack. For example, this method will automatically rollback the database ...
python
{ "resource": "" }
q8028
ErrorAwareApp.post_create_app
train
def post_create_app(cls, app, **settings): """Register the errorhandler for the AppException to the passed in App. Args: app (fleaker.base.BaseApplication): A Flask application that extends the Fleaker Base Application, such that the hooks are impleme...
python
{ "resource": "" }
q8029
create_app
train
def create_app(): """Create the standard app for ``fleaker_config`` and register the two routes required. """ app = App.create_app(__name__) app.configure('.configs.settings') # yes, I should use blueprints; but I don't really care for such a small # toy app @app.route('/config') de...
python
{ "resource": "" }
q8030
FieldSignatureMixin.update_signature
train
def update_signature(self): """Update the signature field by hashing the ``signature_fields``. Raises: AttributeError: This is raised if ``Meta.signature_fields`` has no values in it or if a field in there is not a field on the model. """ if n...
python
{ "resource": "" }
q8031
connect
train
def connect(service_account, credentials_file_path, api_version='v2'): """ Connect to the google play interface """ # Create an httplib2.Http object to handle our HTTP requests an # authorize it with the Credentials. Note that the first parameter, # service_account_name, is the Email address create...
python
{ "resource": "" }
q8032
PendulumField._deserialize
train
def _deserialize(self, value, attr, obj): """Deserializes a string into a Pendulum object.""" if not self.context.get('convert_dates', True) or not value: return value value = super(PendulumField, self)._deserialize(value, attr, value) timezone = self.get_field_value('timezo...
python
{ "resource": "" }
q8033
PhoneNumberField._format_phone_number
train
def _format_phone_number(self, value, attr): """Format and validate a phone number.""" strict_validation = self.get_field_value( 'strict_phone_validation', default=False ) strict_region = self.get_field_value( 'strict_phone_region', default...
python
{ "resource": "" }
q8034
PhoneNumberField._deserialize
train
def _deserialize(self, value, attr, data): """Format and validate the phone number using libphonenumber.""" if value: value = self._format_phone_number(value, attr) return super(PhoneNumberField, self)._deserialize(value, attr, data)
python
{ "resource": "" }
q8035
PhoneNumberField._serialize
train
def _serialize(self, value, attr, obj): """Format and validate the phone number user libphonenumber.""" value = super(PhoneNumberField, self)._serialize(value, attr, obj) if value: value = self._format_phone_number(value, attr) return value
python
{ "resource": "" }
q8036
FleakerJSONEncoder.default
train
def default(self, obj): """Encode individual objects into their JSON representation. This method is used by :class:`flask.json.JSONEncoder` to encode individual items in the JSON object. Args: obj (object): Any Python object we wish to convert to JSON. Returns: ...
python
{ "resource": "" }
q8037
ArrowField._serialize
train
def _serialize(self, value, attr, obj): """Convert the Arrow object into a string.""" if isinstance(value, arrow.arrow.Arrow): value = value.datetime return super(ArrowField, self)._serialize(value, attr, obj)
python
{ "resource": "" }
q8038
ArrowField._deserialize
train
def _deserialize(self, value, attr, data): """Deserializes a string into an Arrow object.""" if not self.context.get('convert_dates', True) or not value: return value value = super(ArrowField, self)._deserialize(value, attr, data) timezone = self.get_field_value('timezone') ...
python
{ "resource": "" }
q8039
PendulumDateTimeField.python_value
train
def python_value(self, value): """Return the value in the database as an Pendulum object. Returns: pendulum.Pendulum: An instance of Pendulum with the field filled in. """ value = super(PendulumDateTimeField, self).python_value(value) if isinstance(v...
python
{ "resource": "" }
q8040
PendulumDateTimeField.db_value
train
def db_value(self, value): """Convert the Pendulum instance to a datetime for saving in the db.""" if isinstance(value, pendulum.Pendulum): value = datetime.datetime( value.year, value.month, value.day, value.hour, value.minute, value.second, value.microsecond...
python
{ "resource": "" }
q8041
check_rollout
train
def check_rollout(edits_service, package_name, days): """Check if package_name has a release on staged rollout for too long""" edit = edits_service.insert(body={}, packageName=package_name).execute() response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execu...
python
{ "resource": "" }
q8042
FleakerJSONSchema.generate_json_schema
train
def generate_json_schema(cls, schema, context=DEFAULT_DICT): """Generate a JSON Schema from a Marshmallow schema. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one, to create the JSON schema for. Keyword Args: file_...
python
{ "resource": "" }
q8043
FleakerJSONSchema.write_schema_to_file
train
def write_schema_to_file(cls, schema, file_pointer=stdout, folder=MISSING, context=DEFAULT_DICT): """Given a Marshmallow schema, create a JSON Schema for it. Args: schema (marshmallow.Schema|str): The Marshmallow schema, or the Python path to one...
python
{ "resource": "" }
q8044
FleakerJSONSchema._get_schema
train
def _get_schema(cls, schema): """Method that will fetch a Marshmallow schema flexibly. Args: schema (marshmallow.Schema|str): Either the schema class, an instance of a schema, or a Python path to a schema. Returns: marshmallow.Schema: The desired schema....
python
{ "resource": "" }
q8045
FleakerJSONSchema._get_object_from_python_path
train
def _get_object_from_python_path(python_path): """Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: ...
python
{ "resource": "" }
q8046
MarshmallowAwareApp.post_create_app
train
def post_create_app(cls, app, **settings): """Automatically register and init the Flask Marshmallow extension. Args: app (flask.Flask): The application instance in which to initialize Flask Marshmallow upon. Kwargs: settings (dict): The settings passed t...
python
{ "resource": "" }
q8047
get_original_before_save
train
def get_original_before_save(sender, instance, created): """Event listener to get the original instance before it's saved.""" if not instance._meta.event_ready or created: return instance.get_original()
python
{ "resource": "" }
q8048
post_save_event_listener
train
def post_save_event_listener(sender, instance, created): """Event listener to create creation and update events.""" if not instance._meta.event_ready: return if created: instance.create_creation_event() else: instance.create_update_event() # Reset the original key insta...
python
{ "resource": "" }
q8049
validate_event_type
train
def validate_event_type(sender, event, created): """Verify that the Event's code is a valid one.""" if event.code not in sender.event_codes(): raise ValueError("The Event.code '{}' is not a valid Event " "code.".format(event.code))
python
{ "resource": "" }
q8050
EventMixin.get_original
train
def get_original(self): """Get the original instance of this instance before it's updated. Returns: fleaker.peewee.EventMixin: The original instance of the model. """ pk_value = self._get_pk_value() if isinstance(pk_value, int) and not self._original...
python
{ "resource": "" }
q8051
EventMixin.create_creation_event
train
def create_creation_event(self): """Parse the create message DSL to insert the data into the Event. Returns: fleaker.peewee.EventStorageMixin: A new Event instance with data put in it """ event = self.create_audit_event(code='AUDIT_CREATE') if self._...
python
{ "resource": "" }
q8052
EventMixin.create_update_event
train
def create_update_event(self): """Parse the update messages DSL to insert the data into the Event. Returns: list[fleaker.peewee.EventStorageMixin]: All the events that were created for the update. """ events = [] for fields, rules in iteritems(self._...
python
{ "resource": "" }
q8053
EventMixin.create_deletion_event
train
def create_deletion_event(self): """Parse the delete message DSL to insert data into the Event. Return: Event: The Event with the relevant information put in it. """ event = self.create_audit_event(code='AUDIT_DELETE') if self._meta.delete_message: event...
python
{ "resource": "" }
q8054
EventMixin.parse_meta
train
def parse_meta(self, meta): """Parses the meta field in the message, copies it's keys into a new dict and replaces the values, which should be attribute paths relative to the passed in object, with the current value at the end of that path. This function will run recursively when it enco...
python
{ "resource": "" }
q8055
EventMixin.get_path_attribute
train
def get_path_attribute(obj, path): """Given a path like `related_record.related_record2.id`, this method will be able to pull the value of ID from that object, returning None if it doesn't exist. Args: obj (fleaker.db.Model): The object to attempt to pull the...
python
{ "resource": "" }
q8056
EventMixin.copy_foreign_keys
train
def copy_foreign_keys(self, event): """Copies possible foreign key values from the object into the Event, skipping common keys like modified and created. Args: event (Event): The Event instance to copy the FKs into obj (fleaker.db.Model): The object to pull the values fr...
python
{ "resource": "" }
q8057
EventMixin.create_audit_event
train
def create_audit_event(self, code='AUDIT'): """Creates a generic auditing Event logging the changes between saves and the initial data in creates. Kwargs: code (str): The code to set the new Event to. Returns: Event: A new event with relevant info inserted into ...
python
{ "resource": "" }
q8058
EventMixin.populate_audit_fields
train
def populate_audit_fields(self, event): """Populates the the audit JSON fields with raw data from the model, so all changes can be tracked and diffed. Args: event (Event): The Event instance to attach the data to instance (fleaker.db.Model): The newly created/updated mod...
python
{ "resource": "" }
q8059
EventStorageMixin.formatted_message
train
def formatted_message(self): """Method that will return the formatted message for the event. This formatting is done with Jinja and the template text is stored in the ``body`` attribute. The template is supplied the following variables, as well as the built in Flask ones: - ``e...
python
{ "resource": "" }
q8060
CreatedMixin._get_cached_time
train
def _get_cached_time(self): """Method that will allow for consistent modified and archived timestamps. Returns: self.Meta.datetime: This method will return a datetime that is compatible with the current class's datetime library. """ if not self._cache...
python
{ "resource": "" }
q8061
_get_list_of_completed_locales
train
def _get_list_of_completed_locales(product, channel): """ Get all the translated locales supported by Google play So, locale unsupported by Google play won't be downloaded Idem for not translated locale """ return utils.load_json_url(_ALL_LOCALES_URL.format(product=product, channel=channel))
python
{ "resource": "" }
q8062
FleakerFieldMixin.get_field_value
train
def get_field_value(self, key, default=MISSING): """Method to fetch a value from either the fields metadata or the schemas context, in that order. Args: key (str): The name of the key to grab the value for. Keyword Args: default (object, optional): If the value ...
python
{ "resource": "" }
q8063
Model.get_by_id
train
def get_by_id(cls, record_id, execute=True): """Return a single instance of the model queried by ID. Args: record_id (int): Integer representation of the ID to query on. Keyword Args: execute (bool, optional): Should this method execute the query or retu...
python
{ "resource": "" }
q8064
Model.update_instance
train
def update_instance(self, data): """Update a single record by id with the provided data. Args: data (dict): The new data to update the record with. Returns: self: This is an instance of itself with the updated data. Raises: AttributeError: This is r...
python
{ "resource": "" }
q8065
ProcessStarter.wait
train
def wait(self, log_file): "Wait until the process is ready." lines = map(self.log_line, self.filter_lines(self.get_lines(log_file))) return any( std.re.search(self.pattern, line) for line in lines )
python
{ "resource": "" }
q8066
CompatStarter.prep
train
def prep(self, wait, args, env=None): """ Given the return value of a preparefunc, prepare this CompatStarter. """ self.pattern = wait self.env = env self.args = args # wait is a function, supersedes the default behavior if callable(wait): ...
python
{ "resource": "" }
q8067
CompatStarter.wrap
train
def wrap(self, starter_cls): """ If starter_cls is not a ProcessStarter, assume it's the legacy preparefunc and return it bound to a CompatStarter. """ if isinstance(starter_cls, type) and issubclass(starter_cls, ProcessStarter): return starter_cls depr_msg = ...
python
{ "resource": "" }
q8068
BaseClient._construct_url
train
def _construct_url(self, url, base, quote): """ Adds the orderbook to the url if base and quote are specified. """ if not base and not quote: return url else: url = url + base.lower() + quote.lower() + "/" return url
python
{ "resource": "" }
q8069
BaseClient._request
train
def _request(self, func, url, version=1, *args, **kwargs): """ Make a generic request, adding in any proxy defined by the instance. Raises a ``requests.HTTPError`` if the response status isn't 200, and raises a :class:`BitstampError` if the response contains a json encoded error...
python
{ "resource": "" }
q8070
Public.ticker
train
def ticker(self, base="btc", quote="usd"): """ Returns dictionary. """ url = self._construct_url("ticker/", base, quote) return self._get(url, return_json=True, version=2)
python
{ "resource": "" }
q8071
Public.order_book
train
def order_book(self, group=True, base="btc", quote="usd"): """ Returns dictionary with "bids" and "asks". Each is a list of open orders and each order is represented as a list of price and amount. """ params = {'group': group} url = self._construct_url("order_boo...
python
{ "resource": "" }
q8072
Public.transactions
train
def transactions(self, time=TransRange.HOUR, base="btc", quote="usd"): """ Returns transactions for the last 'timedelta' seconds. Parameter time is specified by one of two values of TransRange class. """ params = {'time': time} url = self._construct_url("transactions/", b...
python
{ "resource": "" }
q8073
Trading.get_nonce
train
def get_nonce(self): """ Get a unique nonce for the bitstamp API. This integer must always be increasing, so use the current unix time. Every time this variable is requested, it automatically increments to allow for more than one API request per second. This isn't a thr...
python
{ "resource": "" }
q8074
Trading._default_data
train
def _default_data(self, *args, **kwargs): """ Generate a one-time signature and other data required to send a secure POST request to the Bitstamp API. """ data = super(Trading, self)._default_data(*args, **kwargs) data['key'] = self.key nonce = self.get_nonce() ...
python
{ "resource": "" }
q8075
Trading.cancel_order
train
def cancel_order(self, order_id, version=1): """ Cancel the order specified by order_id. Version 1 (default for backwards compatibility reasons): Returns True if order was successfully canceled, otherwise raise a BitstampError. Version 2: Returns dictionary of t...
python
{ "resource": "" }
q8076
Trading.buy_limit_order
train
def buy_limit_order(self, amount, price, base="btc", quote="usd", limit_price=None): """ Order to buy amount of bitcoins for specified price. """ data = {'amount': amount, 'price': price} if limit_price is not None: data['limit_price'] = limit_price url = self...
python
{ "resource": "" }
q8077
Trading.buy_market_order
train
def buy_market_order(self, amount, base="btc", quote="usd"): """ Order to buy amount of bitcoins for market price. """ data = {'amount': amount} url = self._construct_url("buy/market/", base, quote) return self._post(url, data=data, return_json=True, version=2)
python
{ "resource": "" }
q8078
Trading.check_bitstamp_code
train
def check_bitstamp_code(self, code): """ Returns JSON dictionary containing USD and BTC amount included in given bitstamp code. """ data = {'code': code} return self._post("check_code/", data=data, return_json=True, version=1)
python
{ "resource": "" }
q8079
Trading.redeem_bitstamp_code
train
def redeem_bitstamp_code(self, code): """ Returns JSON dictionary containing USD and BTC amount added to user's account. """ data = {'code': code} return self._post("redeem_code/", data=data, return_json=True, version=1)
python
{ "resource": "" }
q8080
Trading.withdrawal_requests
train
def withdrawal_requests(self, timedelta = 86400): """ Returns list of withdrawal requests. Each request is represented as a dictionary. By default, the last 24 hours (86400 seconds) are returned. """ data = {'timedelta': timedelta} return self._post("withdrawal_...
python
{ "resource": "" }
q8081
Trading.litecoin_withdrawal
train
def litecoin_withdrawal(self, amount, address): """ Send litecoins to another litecoin wallet specified by address. """ data = {'amount': amount, 'address': address} return self._post("ltc_withdrawal/", data=data, return_json=True, version=2)
python
{ "resource": "" }
q8082
Trading.ripple_withdrawal
train
def ripple_withdrawal(self, amount, address, currency): """ Returns true if successful. """ data = {'amount': amount, 'address': address, 'currency': currency} response = self._post("ripple_withdrawal/", data=data, return_json=True) return se...
python
{ "resource": "" }
q8083
Trading.xrp_withdrawal
train
def xrp_withdrawal(self, amount, address, destination_tag=None): """ Sends xrps to another xrp wallet specified by address. Returns withdrawal id. """ data = {'amount': amount, 'address': address} if destination_tag: data['destination_tag'] = destination_tag ...
python
{ "resource": "" }
q8084
Trading.transfer_to_main
train
def transfer_to_main(self, amount, currency, subaccount=None): """ Returns dictionary with status. subaccount has to be the numerical id of the subaccount, not the name """ data = {'amount': amount, 'currency': currency,} if subaccount is not None: ...
python
{ "resource": "" }
q8085
Sound.resample
train
def resample(self, target_sr): """ Returns a new sound with a samplerate of target_sr. """ y_hat = librosa.core.resample(self.y, self.sr, target_sr) return Sound(y_hat, target_sr)
python
{ "resource": "" }
q8086
Sound.as_ipywidget
train
def as_ipywidget(self): """ Provides an IPywidgets player that can be used in a notebook. """ from IPython.display import Audio return Audio(data=self.y, rate=self.sr)
python
{ "resource": "" }
q8087
Sound.from_file
train
def from_file(cls, filename, sr=22050): """ Loads an audiofile, uses sr=22050 by default. """ y, sr = librosa.load(filename, sr=sr) return cls(y, sr)
python
{ "resource": "" }
q8088
Sound.chunks
train
def chunks(self): """ Returns a chunk iterator over the sound. """ if not hasattr(self, '_it'): class ChunkIterator(object): def __iter__(iter): return iter def __next__(iter): try: chunk = self....
python
{ "resource": "" }
q8089
Sound.pitch_shifter
train
def pitch_shifter(self, chunk, shift): """ Pitch-Shift the given chunk by shift semi-tones. """ freq = numpy.fft.rfft(chunk) N = len(freq) shifted_freq = numpy.zeros(N, freq.dtype) S = numpy.round(shift if shift > 0 else N + shift, 0) s = N - S shifted_freq[:S]...
python
{ "resource": "" }
q8090
Sound._time_stretcher
train
def _time_stretcher(self, stretch_factor): """ Real time time-scale without pitch modification. :param int i: index of the beginning of the chunk to stretch :param float stretch_factor: audio scale factor (if > 1 speed up the sound else slow it down) .. warning:: This metho...
python
{ "resource": "" }
q8091
Parser.define
train
def define(self, p): """Defines a parser wrapped into this object.""" f = getattr(p, 'run', p) if debug: setattr(self, '_run', f) else: setattr(self, 'run', f) self.named(getattr(p, 'name', p.__doc__))
python
{ "resource": "" }
q8092
Sampler.play
train
def play(self, sound): """ Adds and plays a new Sound to the Sampler. :param sound: sound to play .. note:: If the sound is already playing, it will restart from the beginning. """ self.is_done.clear() # hold is_done until the sound is played if self.sr != sou...
python
{ "resource": "" }
q8093
Sampler.remove
train
def remove(self, sound): """ Remove a currently played sound. """ with self.chunk_available: sound.playing = False self.sounds.remove(sound)
python
{ "resource": "" }
q8094
Sampler.next_chunks
train
def next_chunks(self): """ Gets a new chunk from all played sound and mix them together. """ with self.chunk_available: while True: playing_sounds = [s for s in self.sounds if s.playing] chunks = [] for s in playing_sounds: ...
python
{ "resource": "" }
q8095
Sampler.run
train
def run(self): """ Play loop, i.e. send all sound chunk by chunk to the soundcard. """ self.running = True def chunks_producer(): while self.running: self.chunks.put(self.next_chunks()) t = Thread(target=chunks_producer) t.start() with self....
python
{ "resource": "" }
q8096
dependency_sort
train
def dependency_sort(dependency_tree): """ Sorts items 'dependencies first' in a given dependency tree. A dependency tree is a dictionary mapping an object to a collection its dependency objects. Result is a properly sorted list of items, where each item is a 2-tuple containing an object and it...
python
{ "resource": "" }
q8097
_sort_r
train
def _sort_r(sorted, processed, key, deps, dependency_tree): """Recursive topological sort implementation.""" if key in processed: return processed.add(key) for dep_key in deps: dep_deps = dependency_tree.get(dep_key) if dep_deps is None: log.debug('"%s" not found, ski...
python
{ "resource": "" }
q8098
TypedContent.resolve
train
def resolve(self, nobuiltin=False): """ Resolve the node's type reference and return the referenced type node. Returns self if the type is defined locally, e.g. as a <complexType> subnode. Otherwise returns the referenced external node. @param nobuiltin: Flag indicating whether...
python
{ "resource": "" }
q8099
Element.namespace
train
def namespace(self, prefix=None): """ Get this schema element's target namespace. In case of reference elements, the target namespace is defined by the referenced and not the referencing element node. @param prefix: The default prefix. @type prefix: str @return:...
python
{ "resource": "" }