text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_transaction(self, to_account):
"""Create a transaction for this statement amount and account, into to_account This will also set this StatementLine's ``transaction`` attribute to the newly created transaction. Args: to_account (Account):
The account the transaction is into / out of. Returns: Transaction: The newly created (and committed) transaction. """ |
from_account = self.statement_import.bank_account
transaction = Transaction.objects.create()
Leg.objects.create(
transaction=transaction, account=from_account, amount=+(self.amount * -1)
)
Leg.objects.create(transaction=transaction, account=to_account, amount=-(self.amount * -1))
transaction.date = self.date
transaction.save()
self.transaction = transaction
self.save()
return transaction |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def currency_exchange( source, source_amount, destination, destination_amount, trading_account, fee_destination=None, fee_amount=None, date=None, description=None, ):
""" Exchange funds from one currency to another Use this method to represent a real world currency transfer. Note this process doesn't care about exchange rates, only about the value of currency going in and out of the transaction. You can also record any exchange fees by syphoning off funds to ``fee_account`` of amount ``fee_amount``. Note that the free currency must be the same as the source currency. Examples: For example, imagine our Canadian bank has obligingly transferred 120 CAD into our US bank account. We sent CAD 120, and received USD 100. We were also changed 1.50 CAD in fees. We can represent this exchange in Hordak as follows:: from hordak.utilities.currency import currency_exchange currency_exchange( # Source account and amount source=cad_cash, source_amount=Money(120, 'CAD'), # Destination account and amount destination=usd_cash, destination_amount=Money(100, 'USD'), # Trading account the exchange will be done through trading_account=trading, # We also incur some fees fee_destination=banking_fees, fee_amount=Money(1.50, 'CAD') ) We should now find that: 1. ``cad_cash.balance()`` has decreased by ``CAD 120`` 2. ``usd_cash.balance()`` has increased by ``USD 100`` 3. ``banking_fees.balance()`` is ``CAD 1.50`` 4. ``trading_account.balance()`` is ``USD 100, CAD -120`` You can perform ``trading_account.normalise()`` to discover your unrealised gains/losses on currency traded through that account. Args: source (Account):
The account the funds will be taken from source_amount (Money):
A ``Money`` instance containing the inbound amount and currency. destination (Account):
The account the funds will be placed into destination_amount (Money):
A ``Money`` instance containing the outbound amount and currency trading_account (Account):
The trading account to be used. The normalised balance of this account will indicate gains/losses you have made as part of your activity via this account. Note that the normalised balance fluctuates with the current exchange rate. fee_destination (Account):
Your exchange may incur fees. Specifying this will move incurred fees into this account (optional). fee_amount (Money):
The amount and currency of any incurred fees (optional). description (str):
Description for the transaction. Will default to describing funds in/out & fees (optional). date (datetime.date):
The date on which the transaction took place. Defaults to today (optional). Returns: (Transaction):
The transaction created See Also: You can see the above example in practice in ``CurrencyExchangeTestCase.test_fees`` in `test_currency.py`_. .. _test_currency.py: https://github.com/adamcharnock/django-hordak/blob/master/hordak/tests/utilities/test_currency.py """ |
from hordak.models import Account, Transaction, Leg
if trading_account.type != Account.TYPES.trading:
raise TradingAccountRequiredError(
"Account {} must be a trading account".format(trading_account)
)
if (fee_destination or fee_amount) and not (fee_destination and fee_amount):
raise RuntimeError(
"You must specify either neither or both fee_destination and fee_amount."
)
if fee_amount is None:
# If fees are not specified then set fee_amount to be zero
fee_amount = Money(0, source_amount.currency)
else:
# If we do have fees then make sure the fee currency matches the source currency
if fee_amount.currency != source_amount.currency:
raise InvalidFeeCurrency(
"Fee amount currency ({}) must match source amount currency ({})".format(
fee_amount.currency, source_amount.currency
)
)
# Checks over and done now. Let's create the transaction
with db_transaction.atomic():
transaction = Transaction.objects.create(
date=date or datetime.date.today(),
description=description
or "Exchange of {} to {}, incurring {} fees".format(
source_amount, destination_amount, "no" if fee_amount is None else fee_amount
),
)
# Source currency into trading account
Leg.objects.create(transaction=transaction, account=source, amount=source_amount)
Leg.objects.create(
transaction=transaction, account=trading_account, amount=-(source_amount - fee_amount)
)
# Any fees
if fee_amount and fee_destination:
Leg.objects.create(
transaction=transaction,
account=fee_destination,
amount=-fee_amount,
description="Fees",
)
# Destination currency out of trading account
Leg.objects.create(
transaction=transaction, account=trading_account, amount=destination_amount
)
Leg.objects.create(transaction=transaction, account=destination, amount=-destination_amount)
return transaction |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cache_rate(self, currency, date, rate):
""" Cache a rate for future use """ |
if not self.is_supported(defaults.INTERNAL_CURRENCY):
logger.info('Tried to cache unsupported currency "{}". Ignoring.'.format(currency))
else:
cache.set(_cache_key(currency, date), str(rate), _cache_timeout(date)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_rate(self, currency, date):
"""Get the exchange rate for ``currency`` against ``_INTERNAL_CURRENCY`` If implementing your own backend, you should probably override :meth:`_get_rate()` rather than this. """ |
if str(currency) == defaults.INTERNAL_CURRENCY:
return Decimal(1)
cached = cache.get(_cache_key(currency, date))
if cached:
return Decimal(cached)
else:
# Expect self._get_rate() to implement caching
return Decimal(self._get_rate(currency, date)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(self, money, to_currency, date=None):
"""Convert the given ``money`` to ``to_currency`` using exchange rate on ``date`` If ``date`` is omitted then the date given by ``money.date`` will be used. """ |
if str(money.currency) == str(to_currency):
return copy.copy(money)
return Money(
amount=money.amount
* self.rate(money.currency, to_currency, date or datetime.date.today()),
currency=to_currency,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rate(self, from_currency, to_currency, date):
"""Get the exchange rate between the specified currencies""" |
return (1 / self.backend.get_rate(from_currency, date)) * self.backend.get_rate(
to_currency, date
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def currencies(self):
"""Get all currencies with non-zero values""" |
return [m.currency.code for m in self.monies() if m.amount] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalise(self, to_currency):
"""Normalise this balance into a single currency Args: to_currency (str):
Destination currency Returns: (Balance):
A new balance object containing a single Money value in the specified currency """ |
out = Money(currency=to_currency)
for money in self._money_obs:
out += converter.convert(money, to_currency)
return Balance([out]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_active(self, *args, **kwargs):
""" Return only the 'active' hits. How you count a hit/view will depend on personal choice: Should the same user/visitor *ever* be counted twice? After a week, or a month, or a year, should their view be counted again? The defaulf is to consider a visitor's hit still 'active' if they return within a the last seven days.. After that the hit will be counted again. So if one person visits once a week for a year, they will add 52 hits to a given object. Change how long the expiration is by adding to settings.py: HITCOUNT_KEEP_HIT_ACTIVE = {'days' : 30, 'minutes' : 30} Accepts days, seconds, microseconds, milliseconds, minutes, hours, and weeks. It's creating a datetime.timedelta object. """ |
grace = getattr(settings, 'HITCOUNT_KEEP_HIT_ACTIVE', {'days': 7})
period = timezone.now() - timedelta(**grace)
return self.filter(created__gte=period).filter(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def unload_fixture(apps, schema_editor):
"Brutally deleting all entries for this model..."
MyModel = apps.get_model("blog", "Post")
MyModel.objects.all().delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_ip(request):
""" Retrieves the remote IP address from the request data. If the user is behind a proxy, they may have a comma-separated list of IP addresses, so we need to account for that. In such a case, only the first IP in the list will be retrieved. Also, some hosts that use a proxy will put the REMOTE_ADDR into HTTP_X_FORWARDED_FOR. This will handle pulling back the IP from the proper place. **NOTE** This function was taken from django-tracking (MIT LICENSE) http://code.google.com/p/django-tracking/ """ |
# if neither header contain a value, just use local loopback
ip_address = request.META.get('HTTP_X_FORWARDED_FOR',
request.META.get('REMOTE_ADDR', '127.0.0.1'))
if ip_address:
# make sure we have one and only one IP
try:
ip_address = IP_RE.match(ip_address)
if ip_address:
ip_address = ip_address.group(0)
else:
# no IP, probably from some dirty proxy or other device
# throw in some bogus IP
ip_address = '10.0.0.1'
except IndexError:
pass
return ip_address |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_hit_count_ajax(request, *args, **kwargs):
""" Deprecated in 1.2. Use hitcount.views.HitCountJSONView instead. """ |
warnings.warn(
"hitcount.views.update_hit_count_ajax is deprecated. "
"Use hitcount.views.HitCountJSONView instead.",
RemovedInHitCount13Warning
)
view = HitCountJSONView.as_view()
return view(request, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_hit_count_from_obj_variable(context, obj_variable, tag_name):
""" Helper function to return a HitCount for a given template object variable. Raises TemplateSyntaxError if the passed object variable cannot be parsed. """ |
error_to_raise = template.TemplateSyntaxError(
"'%(a)s' requires a valid individual model variable "
"in the form of '%(a)s for [model_obj]'.\n"
"Got: %(b)s" % {'a': tag_name, 'b': obj_variable}
)
try:
obj = obj_variable.resolve(context)
except template.VariableDoesNotExist:
raise error_to_raise
try:
ctype = ContentType.objects.get_for_model(obj)
except AttributeError:
raise error_to_raise
hit_count, created = HitCount.objects.get_or_create(
content_type=ctype, object_pk=obj.pk)
return hit_count |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _start(self):
""" Starts streaming the feed using the provided session and feed options. """ |
params = self._translate(self._options)
self._resp = self._r_session.get(self._url, params=params, stream=True)
self._resp.raise_for_status()
self._lines = self._resp.iter_lines(self._chunk_size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self):
""" Handles the iteration by pulling the next line out of the stream, attempting to convert the response to JSON if necessary. :returns: Data representing what was seen in the feed """ |
while True:
if not self._resp:
self._start()
if self._stop:
raise StopIteration
skip, data = self._process_data(next_(self._lines))
if not skip:
break
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_data(self, line):
""" Validates and processes the line passed in and converts it to a Python object if necessary. """ |
skip = False
if self._raw_data:
return skip, line
line = unicode_(line)
if not line:
if (self._options.get('heartbeat', False) and
self._options.get('feed') in ('continuous', 'longpoll') and
not self._last_seq):
line = None
else:
skip = True
elif line in ('{"results":[', '],'):
skip = True
elif line[-1] == ',':
line = line[:-1]
elif line[:10] == ('"last_seq"'):
line = '{' + line
try:
if line:
data = json.loads(line)
if data.get('last_seq'):
self._last_seq = data['last_seq']
skip = True
else:
data = None
except ValueError:
data = {"error": "Bad JSON line", "line": line}
return skip, data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next(self):
""" Handles the iteration by pulling the next line out of the stream and converting the response to JSON. :returns: Data representing what was seen in the feed """ |
while True:
if self._source == 'CouchDB':
raise CloudantFeedException(101)
if self._last_seq:
self._options.update({'since': self._last_seq})
self._resp = None
self._last_seq = None
if not self._resp:
self._start()
if self._stop:
raise StopIteration
skip, data = self._process_data(next_(self._lines))
if not skip:
break
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def features(self):
""" lazy fetch and cache features """ |
if self._features is None:
metadata = self.metadata()
if "features" in metadata:
self._features = metadata["features"]
else:
self._features = []
return self._features |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
""" Starts up an authentication session for the client using cookie authentication if necessary. """ |
if self.r_session:
self.session_logout()
if self.admin_party:
self._use_iam = False
self.r_session = ClientSession(
timeout=self._timeout
)
elif self._use_basic_auth:
self._use_iam = False
self.r_session = BasicSession(
self._user,
self._auth_token,
self.server_url,
timeout=self._timeout
)
elif self._use_iam:
self.r_session = IAMSession(
self._auth_token,
self.server_url,
auto_renew=self._auto_renew,
client_id=self._iam_client_id,
client_secret=self._iam_client_secret,
timeout=self._timeout
)
else:
self.r_session = CookieSession(
self._user,
self._auth_token,
self.server_url,
auto_renew=self._auto_renew,
timeout=self._timeout
)
# If a Transport Adapter was supplied add it to the session
if self.adapter is not None:
self.r_session.mount(self.server_url, self.adapter)
if self._client_user_header is not None:
self.r_session.headers.update(self._client_user_header)
self.session_login()
# Utilize an event hook to append to the response message
# using :func:`~cloudant.common_util.append_response_error_content`
self.r_session.hooks['response'].append(append_response_error_content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self):
""" Ends a client authentication session, performs a logout and a clean up. """ |
if self.r_session:
self.session_logout()
self.r_session = None
self.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def session_login(self, user=None, passwd=None):
""" Performs a session login by posting the auth information to the _session endpoint. :param str user: Username used to connect to server. :param str auth_token: Authentication token used to connect to server. """ |
self.change_credentials(user=user, auth_token=passwd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change_credentials(self, user=None, auth_token=None):
""" Change login credentials. :param str user: Username used to connect to server. :param str auth_token: Authentication token used to connect to server. """ |
self.r_session.set_credentials(user, auth_token)
self.r_session.login() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_dbs(self):
""" Retrieves a list of all database names for the current client. :returns: List of database names for the client """ |
url = '/'.join((self.server_url, '_all_dbs'))
resp = self.r_session.get(url)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_database(self, dbname, partitioned=False, **kwargs):
""" Creates a new database on the remote server with the name provided and adds the new database object to the client's locally cached dictionary before returning it to the caller. The method will optionally throw a CloudantClientException if the database exists remotely. :param str dbname: Name used to create the database. :param bool throw_on_exists: Boolean flag dictating whether or not to throw a CloudantClientException when attempting to create a database that already exists. :param bool partitioned: Create as a partitioned database. Defaults to ``False``. :returns: The newly created database object """ |
new_db = self._DATABASE_CLASS(self, dbname, partitioned=partitioned)
try:
new_db.create(kwargs.get('throw_on_exists', False))
except CloudantDatabaseException as ex:
if ex.status_code == 412:
raise CloudantClientException(412, dbname)
super(CouchDB, self).__setitem__(dbname, new_db)
return new_db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_database(self, dbname):
""" Removes the named database remotely and locally. The method will throw a CloudantClientException if the database does not exist. :param str dbname: Name of the database to delete. """ |
db = self._DATABASE_CLASS(self, dbname)
if not db.exists():
raise CloudantClientException(404, dbname)
db.delete()
if dbname in list(self.keys()):
super(CouchDB, self).__delitem__(dbname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metadata(self):
""" Retrieves the remote server metadata dictionary. :returns: Dictionary containing server metadata details """ |
resp = self.r_session.get(self.server_url)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keys(self, remote=False):
""" Returns the database names for this client. Default is to return only the locally cached database names, specify ``remote=True`` to make a remote request to include all databases. :param bool remote: Dictates whether the list of locally cached database names are returned or a remote request is made to include an up to date list of databases from the server. Defaults to False. :returns: List of database names """ |
if not remote:
return list(super(CouchDB, self).keys())
return self.all_dbs() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, default=None, remote=False):
""" Overrides dictionary get behavior to retrieve database objects with support for returning a default. If remote=True then a remote request is made to retrieve the database from the remote server, otherwise the client's locally cached database object is returned. :param str key: Database name used to retrieve the database object. :param str default: Default database name. Defaults to None. :param bool remote: Dictates whether the locally cached database is returned or a remote request is made to retrieve the database from the server. Defaults to False. :returns: Database object """ |
if not remote:
return super(CouchDB, self).get(key, default)
db = self._DATABASE_CLASS(self, key)
if db.exists():
super(CouchDB, self).__setitem__(key, db)
return db
return default |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _usage_endpoint(self, endpoint, year=None, month=None):
""" Common helper for getting usage and billing reports with optional year and month URL elements. :param str endpoint: Cloudant usage endpoint. :param int year: Year to query against. Optional parameter. Defaults to None. If used, it must be accompanied by ``month``. :param int month: Month to query against that must be an integer between 1 and 12. Optional parameter. Defaults to None. If used, it must be accompanied by ``year``. """ |
err = False
if year is None and month is None:
resp = self.r_session.get(endpoint)
else:
try:
if int(year) > 0 and int(month) in range(1, 13):
resp = self.r_session.get(
'/'.join((endpoint, str(int(year)), str(int(month)))))
else:
err = True
except (ValueError, TypeError):
err = True
if err:
raise CloudantArgumentError(101, year, month)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bill(self, year=None, month=None):
""" Retrieves Cloudant billing data, optionally for a given year and month. :param int year: Year to query against, for example 2014. Optional parameter. Defaults to None. If used, it must be accompanied by ``month``. :param int month: Month to query against that must be an integer between 1 and 12. Optional parameter. Defaults to None. If used, it must be accompanied by ``year``. :returns: Billing data in JSON format """ |
endpoint = '/'.join((self.server_url, '_api', 'v2', 'bill'))
return self._usage_endpoint(endpoint, year, month) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def volume_usage(self, year=None, month=None):
""" Retrieves Cloudant volume usage data, optionally for a given year and month. :param int year: Year to query against, for example 2014. Optional parameter. Defaults to None. If used, it must be accompanied by ``month``. :param int month: Month to query against that must be an integer between 1 and 12. Optional parameter. Defaults to None. If used, it must be accompanied by ``year``. :returns: Volume usage data in JSON format """ |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'usage', 'data_volume'))
return self._usage_endpoint(endpoint, year, month) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def requests_usage(self, year=None, month=None):
""" Retrieves Cloudant requests usage data, optionally for a given year and month. :param int year: Year to query against, for example 2014. Optional parameter. Defaults to None. If used, it must be accompanied by ``month``. :param int month: Month to query against that must be an integer between 1 and 12. Optional parameter. Defaults to None. If used, it must be accompanied by ``year``. :returns: Requests usage data in JSON format """ |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'usage', 'requests'))
return self._usage_endpoint(endpoint, year, month) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shared_databases(self):
""" Retrieves a list containing the names of databases shared with this account. :returns: List of database names """ |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'shared_databases'))
resp = self.r_session.get(endpoint)
resp.raise_for_status()
data = response_to_json_dict(resp)
return data.get('shared_databases', []) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cors_configuration(self):
""" Retrieves the current CORS configuration. :returns: CORS data in JSON format """ |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.get(endpoint)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disable_cors(self):
""" Switches CORS off. :returns: CORS status in JSON format """ |
return self.update_cors_configuration(
enable_cors=False,
allow_credentials=False,
origins=[],
overwrite_origins=True
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_cors_configuration( self, enable_cors=True, allow_credentials=True, origins=None, overwrite_origins=False):
""" Merges existing CORS configuration with updated values. :param bool enable_cors: Enables/disables CORS. Defaults to True. :param bool allow_credentials: Allows authentication credentials. Defaults to True. :param list origins: List of allowed CORS origin(s). Special cases are a list containing a single "*" which will allow any origin and an empty list which will not allow any origin. Defaults to None. :param bool overwrite_origins: Dictates whether the origins list is overwritten of appended to. Defaults to False. :returns: CORS configuration update status in JSON format """ |
if origins is None:
origins = []
cors_config = {
'enable_cors': enable_cors,
'allow_credentials': allow_credentials,
'origins': origins
}
if overwrite_origins:
return self._write_cors_configuration(cors_config)
old_config = self.cors_configuration()
# update config values
updated_config = old_config.copy()
updated_config['enable_cors'] = cors_config.get('enable_cors')
updated_config['allow_credentials'] = cors_config.get('allow_credentials')
if cors_config.get('origins') == ["*"]:
updated_config['origins'] = ["*"]
elif old_config.get('origins') != cors_config.get('origins'):
new_origins = list(
set(old_config.get('origins')).union(
set(cors_config.get('origins')))
)
updated_config['origins'] = new_origins
return self._write_cors_configuration(updated_config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write_cors_configuration(self, config):
""" Overwrites the entire CORS config with the values updated in update_cors_configuration. :param dict config: Dictionary containing the updated CORS configuration. :returns: CORS configuration update status in JSON format """ |
endpoint = '/'.join((
self.server_url, '_api', 'v2', 'user', 'config', 'cors'))
resp = self.r_session.put(
endpoint,
data=json.dumps(config, cls=self.encoder),
headers={'Content-Type': 'application/json'}
)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bluemix(cls, vcap_services, instance_name=None, service_name=None, **kwargs):
""" Create a Cloudant session using a VCAP_SERVICES environment variable. :param vcap_services: VCAP_SERVICES environment variable :type vcap_services: dict or str :param str instance_name: Optional Bluemix instance name. Only required if multiple Cloudant instances are available. :param str service_name: Optional Bluemix service name. Example usage: .. code-block:: python import os from cloudant.client import Cloudant client = Cloudant.bluemix(os.getenv('VCAP_SERVICES'), 'Cloudant NoSQL DB') print client.all_dbs() """ |
service_name = service_name or 'cloudantNoSQLDB' # default service
try:
service = CloudFoundryService(vcap_services,
instance_name=instance_name,
service_name=service_name)
except CloudantException:
raise CloudantClientException(103)
if hasattr(service, 'iam_api_key'):
return Cloudant.iam(service.username,
service.iam_api_key,
url=service.url,
**kwargs)
return Cloudant(service.username,
service.password,
url=service.url,
**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iam(cls, account_name, api_key, **kwargs):
""" Create a Cloudant client that uses IAM authentication. :param account_name: Cloudant account name. :param api_key: IAM authentication API key. """ |
return cls(None,
api_key,
account=account_name,
auto_renew=kwargs.get('auto_renew', True),
use_iam=True,
**kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url(self):
""" Constructs and returns the Query URL. :returns: Query URL """ |
if self._partition_key:
base_url = self._database.database_partition_url(
self._partition_key)
else:
base_url = self._database.database_url
return base_url + '/_find' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_doc(self, doc_id):
""" Get replication document state for a given replication document ID. """ |
resp = self._r_session.get('/'.join([self._scheduler, 'docs', '_replicator', doc_id]))
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def document_partition_url(self, partition_key):
""" Retrieve the design document partition URL. :param str partition_key: Partition key. :return: Design document partition URL. :rtype: str """ |
return '/'.join((
self._database.database_partition_url(partition_key),
'_design',
url_quote_plus(self['_id'][8:], safe='')
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_show_function(self, show_name, show_func):
""" Appends a show function to the locally cached DesignDocument shows dictionary. :param show_name: Name used to identify the show function. :param show_func: Javascript show function. """ |
if self.get_show_function(show_name) is not None:
raise CloudantArgumentError(110, show_name)
self.shows.__setitem__(show_name, show_func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_index(self, index_name):
""" Removes an existing index in the locally cached DesignDocument indexes dictionary. :param str index_name: Name used to identify the index. """ |
index = self.get_index(index_name)
if index is None:
return
self.indexes.__delitem__(index_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_show_function(self, show_name):
""" Removes an existing show function in the locally cached DesignDocument shows dictionary. :param show_name: Name used to identify the list. """ |
if self.get_show_function(show_name) is None:
return
self.shows.__delitem__(show_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self):
""" Retrieves the remote design document content and populates the locally cached DesignDocument dictionary. View content is stored either as View or QueryIndexView objects which are extensions of the ``dict`` type. All other design document data are stored directly as ``dict`` types. """ |
super(DesignDocument, self).fetch()
if self.views:
for view_name, view_def in iteritems_(self.get('views', dict())):
if self.get('language', None) != QUERY_LANGUAGE:
self['views'][view_name] = View(
self,
view_name,
view_def.pop('map', None),
view_def.pop('reduce', None),
**view_def
)
else:
self['views'][view_name] = QueryIndexView(
self,
view_name,
view_def.pop('map', None),
view_def.pop('reduce', None),
**view_def
)
for prop in self._nested_object_names:
# Ensure dict for each sub-object exists in locally cached DesignDocument.
getattr(self, prop, self.setdefault(prop, dict())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Saves changes made to the locally cached DesignDocument object's data structures to the remote database. If the design document does not exist remotely then it is created in the remote database. If the object does exist remotely then the design document is updated remotely. In either case the locally cached DesignDocument object is also updated accordingly based on the successful response of the operation. """ |
if self.views:
if self.get('language', None) != QUERY_LANGUAGE:
for view_name, view in self.iterviews():
if isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(104, view_name)
else:
for view_name, view in self.iterviews():
if not isinstance(view, QueryIndexView):
raise CloudantDesignDocumentException(105, view_name)
if self.indexes:
if self.get('language', None) != QUERY_LANGUAGE:
for index_name, search in self.iterindexes():
# Check the instance of the javascript search function
if not isinstance(search['index'], STRTYPE):
raise CloudantDesignDocumentException(106, index_name)
else:
for index_name, index in self.iterindexes():
if not isinstance(index['index'], dict):
raise CloudantDesignDocumentException(107, index_name)
for prop in self._nested_object_names:
if not getattr(self, prop):
# Ensure empty dict for each sub-object is not saved remotely.
self.__delitem__(prop)
super(DesignDocument, self).save()
for prop in self._nested_object_names:
# Ensure views, indexes, and lists dict exist in locally cached DesignDocument.
getattr(self, prop, self.setdefault(prop, dict())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(self):
""" Retrieves the design document view information data, returns dictionary GET databasename/_design/{ddoc}/_info """ |
ddoc_info = self.r_session.get(
'/'.join([self.document_url, '_info']))
ddoc_info.raise_for_status()
return response_to_json_dict(ddoc_info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_info(self, search_index):
""" Retrieves information about a specified search index within the design document, returns dictionary GET databasename/_design/{ddoc}/_search_info/{search_index} """ |
ddoc_search_info = self.r_session.get(
'/'.join([self.document_url, '_search_info', search_index]))
ddoc_search_info.raise_for_status()
return response_to_json_dict(ddoc_search_info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_disk_size(self, search_index):
""" Retrieves disk size information about a specified search index within the design document, returns dictionary GET databasename/_design/{ddoc}/_search_disk_size/{search_index} """ |
ddoc_search_disk_size = self.r_session.get(
'/'.join([self.document_url, '_search_disk_size', search_index]))
ddoc_search_disk_size.raise_for_status()
return response_to_json_dict(ddoc_search_disk_size) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def creds(self):
""" Retrieves a dictionary of useful authentication information that can be used to authenticate against this database. :returns: Dictionary containing authentication information """ |
session = self.client.session()
if session is None:
return None
return {
"basic_auth": self.client.basic_auth_str(),
"user_ctx": session.get('userCtx')
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self):
""" Performs an existence check on the remote database. :returns: Boolean True if the database exists, False otherwise """ |
resp = self.r_session.head(self.database_url)
if resp.status_code not in [200, 404]:
resp.raise_for_status()
return resp.status_code == 200 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def metadata(self):
""" Retrieves the remote database metadata dictionary. :returns: Dictionary containing database metadata details """ |
resp = self.r_session.get(self.database_url)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partition_metadata(self, partition_key):
""" Retrieves the metadata dictionary for the remote database partition. :param str partition_key: Partition key. :returns: Metadata dictionary for the database partition. :rtype: dict """ |
resp = self.r_session.get(self.database_partition_url(partition_key))
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_document(self):
""" Creates a new, empty document in the remote and locally cached database, auto-generating the _id. :returns: Document instance corresponding to the new document in the database """ |
doc = Document(self, None)
doc.create()
super(CouchDatabase, self).__setitem__(doc['_id'], doc)
return doc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def design_documents(self):
""" Retrieve the JSON content for all design documents in this database. Performs a remote call to retrieve the content. :returns: All design documents found in this database in JSON format """ |
url = '/'.join((self.database_url, '_all_docs'))
query = "startkey=\"_design\"&endkey=\"_design0\"&include_docs=true"
resp = self.r_session.get(url, params=query)
resp.raise_for_status()
data = response_to_json_dict(resp)
return data['rows'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_design_document(self, ddoc_id):
""" Retrieves a design document. If a design document exists remotely then that content is wrapped in a DesignDocument object and returned to the caller. Otherwise a "shell" DesignDocument object is returned. :param str ddoc_id: Design document id :returns: A DesignDocument instance, if exists remotely then it will be populated accordingly """ |
ddoc = DesignDocument(self, ddoc_id)
try:
ddoc.fetch()
except HTTPError as error:
if error.response.status_code != 404:
raise
return ddoc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_partitioned_view_result(self, partition_key, ddoc_id, view_name, raw_result=False, **kwargs):
""" Retrieves the partitioned view result based on the design document and view name. See :func:`~cloudant.database.CouchDatabase.get_view_result` method for further details. :param str partition_key: Partition key. :param str ddoc_id: Design document id used to get result. :param str view_name: Name of the view used to get result. :param bool raw_result: Dictates whether the view result is returned as a default Result object or a raw JSON response. Defaults to False. :param kwargs: See :func:`~cloudant.database.CouchDatabase.get_view_result` method for available keyword arguments. :returns: The result content either wrapped in a QueryResult or as the raw response JSON content. :rtype: QueryResult, dict """ |
ddoc = DesignDocument(self, ddoc_id)
view = View(ddoc, view_name, partition_key=partition_key)
return self._get_view_result(view, raw_result, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_view_result(view, raw_result, **kwargs):
""" Get view results helper. """ |
if raw_result:
return view(**kwargs)
if kwargs:
return Result(view, **kwargs)
return view.result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, throw_on_exists=False):
""" Creates a database defined by the current database object, if it does not already exist and raises a CloudantException if the operation fails. If the database already exists then this method call is a no-op. :param bool throw_on_exists: Boolean flag dictating whether or not to throw a CloudantDatabaseException when attempting to create a database that already exists. :returns: The database object """ |
if not throw_on_exists and self.exists():
return self
resp = self.r_session.put(self.database_url, params={
'partitioned': TYPE_CONVERTERS.get(bool)(self._partitioned)
})
if resp.status_code == 201 or resp.status_code == 202:
return self
raise CloudantDatabaseException(
resp.status_code, self.database_url, resp.text
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Deletes the current database from the remote instance. """ |
resp = self.r_session.delete(self.database_url)
resp.raise_for_status() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partitioned_all_docs(self, partition_key, **kwargs):
""" Wraps the _all_docs primary index on the database partition, and returns the results by value. See :func:`~cloudant.database.CouchDatabase.all_docs` method for further details. :param str partition_key: Partition key. :param kwargs: See :func:`~cloudant.database.CouchDatabase.all_docs` method for available keyword arguments. :returns: Raw JSON response content from ``_all_docs`` endpoint. :rtype: dict """ |
resp = get_docs(self.r_session,
'/'.join([
self.database_partition_url(partition_key),
'_all_docs'
]),
self.client.encoder,
**kwargs)
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keys(self, remote=False):
""" Retrieves the list of document ids in the database. Default is to return only the locally cached document ids, specify remote=True to make a remote request to include all document ids from the remote database instance. :param bool remote: Dictates whether the list of locally cached document ids are returned or a remote request is made to include an up to date list of document ids from the server. Defaults to False. :returns: List of document ids """ |
if not remote:
return list(super(CouchDatabase, self).keys())
docs = self.all_docs()
return [row['id'] for row in docs.get('rows', [])] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def missing_revisions(self, doc_id, *revisions):
""" Returns a list of document revision values that do not exist in the current remote database for the specified document id and specified list of revision values. :param str doc_id: Document id to check for missing revisions against. :param list revisions: List of document revisions values to check against. :returns: List of missing document revision values """ |
url = '/'.join((self.database_url, '_missing_revs'))
data = {doc_id: list(revisions)}
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data, cls=self.client.encoder)
)
resp.raise_for_status()
resp_json = response_to_json_dict(resp)
missing_revs = resp_json['missing_revs'].get(doc_id)
if missing_revs is None:
missing_revs = []
return missing_revs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def revisions_diff(self, doc_id, *revisions):
""" Returns the differences in the current remote database for the specified document id and specified list of revision values. :param str doc_id: Document id to check for revision differences against. :param list revisions: List of document revisions values to check against. :returns: The revision differences in JSON format """ |
url = '/'.join((self.database_url, '_revs_diff'))
data = {doc_id: list(revisions)}
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(data, cls=self.client.encoder)
)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_revision_limit(self):
""" Retrieves the limit of historical revisions to store for any single document in the current remote database. :returns: Revision limit value for the current remote database """ |
url = '/'.join((self.database_url, '_revs_limit'))
resp = self.r_session.get(url)
resp.raise_for_status()
try:
ret = int(resp.text)
except ValueError:
raise CloudantDatabaseException(400, response_to_json_dict(resp))
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_revision_limit(self, limit):
""" Sets the limit of historical revisions to store for any single document in the current remote database. :param int limit: Number of revisions to store for any single document in the current remote database. :returns: Revision limit set operation status in JSON format """ |
url = '/'.join((self.database_url, '_revs_limit'))
resp = self.r_session.put(url, data=json.dumps(limit, cls=self.client.encoder))
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view_cleanup(self):
""" Removes view files that are not used by any design document in the remote database. :returns: View cleanup status in JSON format """ |
url = '/'.join((self.database_url, '_view_cleanup'))
resp = self.r_session.post(
url,
headers={'Content-Type': 'application/json'}
)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_list_function_result(self, ddoc_id, list_name, view_name, **kwargs):
""" Retrieves a customized MapReduce view result from the specified database based on the list function provided. List functions are used, for example, when you want to access Cloudant directly from a browser, and need data to be returned in a different format, such as HTML. Note: All query parameters for View requests are supported. See :class:`~cloudant.database.get_view_result` for all supported query parameters. For example: .. code-block:: python # Assuming that 'view001' exists as part of the # Retrieve documents where the list function is 'list1' resp = db.get_list_function_result('ddoc001', 'list1', 'view001', limit=10) for row in resp['rows']: # Process data (in text format). For more detail on list functions, refer to the `Cloudant list documentation <https://console.bluemix.net/docs/services/Cloudant/api/ design_documents.html#list-functions>`_. :param str ddoc_id: Design document id used to get result. :param str list_name: Name used in part to identify the list function. :param str view_name: Name used in part to identify the view. :return: Formatted view result data in text format """ |
ddoc = DesignDocument(self, ddoc_id)
headers = {'Content-Type': 'application/json'}
resp = get_docs(self.r_session,
'/'.join([ddoc.document_url, '_list', list_name, view_name]),
self.client.encoder,
headers,
**kwargs)
return resp.text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_show_function_result(self, ddoc_id, show_name, doc_id):
""" Retrieves a formatted document from the specified database based on the show function provided. Show functions, for example, are used when you want to access Cloudant directly from a browser, and need data to be returned in a different format, such as HTML. For example: .. code-block:: python # Assuming that 'view001' exists as part of the # Retrieve a formatted 'doc001' document where the show function is 'show001' resp = db.get_show_function_result('ddoc001', 'show001', 'doc001') for row in resp['rows']: # Process data (in text format). For more detail on show functions, refer to the `Cloudant show documentation <https://console.bluemix.net/docs/services/Cloudant/api/ design_documents.html#show-functions>`_. :param str ddoc_id: Design document id used to get the result. :param str show_name: Name used in part to identify the show function. :param str doc_id: The ID of the document to show. :return: Formatted document result data in text format """ |
ddoc = DesignDocument(self, ddoc_id)
headers = {'Content-Type': 'application/json'}
resp = get_docs(self.r_session,
'/'.join([ddoc.document_url, '_show', show_name, doc_id]),
self.client.encoder,
headers)
return resp.text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_handler_result(self, ddoc_id, handler_name, doc_id=None, data=None, **params):
""" Creates or updates a document from the specified database based on the update handler function provided. Update handlers are used, for example, to provide server-side modification timestamps, and document updates to individual fields without the latest revision. You can provide query parameters needed by the update handler function using the ``params`` argument. Create a document with a generated ID: .. code-block:: python # Assuming that 'update001' update handler exists as part of the # Execute 'update001' to create a new document resp = db.update_handler_result('ddoc001', 'update001', data={'name': 'John', 'message': 'hello'}) Create or update a document with the specified ID: .. code-block:: python # Assuming that 'update001' update handler exists as part of the # Execute 'update001' to update document 'doc001' in the database resp = db.update_handler_result('ddoc001', 'update001', 'doc001', data={'month': 'July'}) For more details, see the `update handlers documentation <https://console.bluemix.net/docs/services/Cloudant/api/design_documents.html#update-handlers>`_. :param str ddoc_id: Design document id used to get result. :param str handler_name: Name used in part to identify the update handler function. :param str doc_id: Optional document id used to specify the document to be handled. :returns: Result of update handler function in text format """ |
ddoc = DesignDocument(self, ddoc_id)
if doc_id:
resp = self.r_session.put(
'/'.join([ddoc.document_url, '_update', handler_name, doc_id]),
params=params, data=data)
else:
resp = self.r_session.post(
'/'.join([ddoc.document_url, '_update', handler_name]),
params=params, data=data)
resp.raise_for_status()
return resp.text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_query_indexes(self, raw_result=False):
""" Retrieves query indexes from the remote database. :param bool raw_result: If set to True then the raw JSON content for the request is returned. Default is to return a list containing :class:`~cloudant.index.Index`, :class:`~cloudant.index.TextIndex`, and :class:`~cloudant.index.SpecialIndex` wrapped objects. :returns: The query indexes in the database """ |
url = '/'.join((self.database_url, '_index'))
resp = self.r_session.get(url)
resp.raise_for_status()
if raw_result:
return response_to_json_dict(resp)
indexes = []
for data in response_to_json_dict(resp).get('indexes', []):
if data.get('type') == JSON_INDEX_TYPE:
indexes.append(Index(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
elif data.get('type') == TEXT_INDEX_TYPE:
indexes.append(TextIndex(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
elif data.get('type') == SPECIAL_INDEX_TYPE:
indexes.append(SpecialIndex(
self,
data.get('ddoc'),
data.get('name'),
partitioned=data.get('partitioned', False),
**data.get('def', {})
))
else:
raise CloudantDatabaseException(101, data.get('type'))
return indexes |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_query_index( self, design_document_id=None, index_name=None, index_type='json', partitioned=False, **kwargs ):
""" Creates either a JSON or a text query index in the remote database. :param str index_type: The type of the index to create. Can be either 'text' or 'json'. Defaults to 'json'. :param str design_document_id: Optional identifier of the design document in which the index will be created. If omitted the default is that each index will be created in its own design document. Indexes can be grouped into design documents for efficiency. However, a change to one index in a design document will invalidate all other indexes in the same document. :param str index_name: Optional name of the index. If omitted, a name will be generated automatically. :param list fields: A list of fields that should be indexed. For JSON indexes, the fields parameter is mandatory and should follow the 'sort syntax'. For example ``fields=['name', {'age': 'desc'}]`` will create an index on the 'name' field in ascending order and the 'age' field in descending order. For text indexes, the fields parameter is optional. If it is included then each field element in the fields list must be a single element dictionary where the key is the field name and the value is the field type. For example ``fields=[{'name': 'string'}, {'age': 'number'}]``. Valid field types are ``'string'``, ``'number'``, and ``'boolean'``. :param dict default_field: Optional parameter that specifies how the ``$text`` operator can be used with the index. Only valid when creating a text index. :param dict selector: Optional parameter that can be used to limit the index to a specific set of documents that match a query. It uses the same syntax used for selectors in queries. Only valid when creating a text index. :returns: An Index object representing the index created in the remote database """ |
if index_type == JSON_INDEX_TYPE:
index = Index(self, design_document_id, index_name,
partitioned=partitioned, **kwargs)
elif index_type == TEXT_INDEX_TYPE:
index = TextIndex(self, design_document_id, index_name,
partitioned=partitioned, **kwargs)
else:
raise CloudantArgumentError(103, index_type)
index.create()
return index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_query_index(self, design_document_id, index_type, index_name):
""" Deletes the query index identified by the design document id, index type and index name from the remote database. :param str design_document_id: The design document id that the index exists in. :param str index_type: The type of the index to be deleted. Must be either 'text' or 'json'. :param str index_name: The index name of the index to be deleted. """ |
if index_type == JSON_INDEX_TYPE:
index = Index(self, design_document_id, index_name)
elif index_type == TEXT_INDEX_TYPE:
index = TextIndex(self, design_document_id, index_name)
else:
raise CloudantArgumentError(103, index_type)
index.delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_partitioned_query_result(self, partition_key, selector, fields=None, raw_result=False, **kwargs):
""" Retrieves the partitioned query result from the specified database based on the query parameters provided. See :func:`~cloudant.database.CouchDatabase.get_query_result` method for further details. :param str partition_key: Partition key. :param str selector: Dictionary object describing criteria used to select documents. :param list fields: A list of fields to be returned by the query. :param bool raw_result: Dictates whether the query result is returned wrapped in a QueryResult or if the response JSON is returned. Defaults to False. :param kwargs: See :func:`~cloudant.database.CouchDatabase.get_query_result` method for available keyword arguments. :returns: The result content either wrapped in a QueryResult or as the raw response JSON content. :rtype: QueryResult, dict """ |
query = Query(self,
selector=selector,
fields=fields,
partition_key=partition_key)
return self._get_query_result(query, raw_result, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_query_result(query, raw_result, **kwargs):
""" Get query results helper. """ |
if raw_result:
return query(**kwargs)
if kwargs:
return QueryResult(query, **kwargs)
return query.result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shards(self):
""" Retrieves information about the shards in the current remote database. :returns: Shard information retrieval status in JSON format """ |
url = '/'.join((self.database_url, '_shards'))
resp = self.r_session.get(url)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_partitioned_search_result(self, partition_key, ddoc_id, index_name, **query_params):
""" Retrieves the raw JSON content from the remote database based on the partitioned search index on the server, using the query_params provided as query parameters. See :func:`~cloudant.database.CouchDatabase.get_search_result` method for further details. :param str partition_key: Partition key. :param str ddoc_id: Design document id used to get the search result. :param str index_name: Name used in part to identify the index. :param query_params: See :func:`~cloudant.database.CloudantDatabase.get_search_result` method for available keyword arguments. :returns: Search query result data in JSON format. :rtype: dict """ |
ddoc = DesignDocument(self, ddoc_id)
return self._get_search_result(
'/'.join((
ddoc.document_partition_url(partition_key),
'_search',
index_name
)),
**query_params
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_search_result(self, ddoc_id, index_name, **query_params):
""" Retrieves the raw JSON content from the remote database based on the search index on the server, using the query_params provided as query parameters. A ``query`` parameter containing the Lucene query syntax is mandatory. Example for search queries: .. code-block:: python # Assuming that 'searchindex001' exists as part of the # Retrieve documents where the Lucene field name is 'name' and # the value is 'julia*' resp = db.get_search_result('ddoc001', 'searchindex001', query='name:julia*', include_docs=True) for row in resp['rows']: # Process search index data (in JSON format). Example if the search query requires grouping by using the ``group_field`` parameter: .. code-block:: python # Assuming that 'searchindex001' exists as part of the # Retrieve JSON response content, limiting response to 10 documents resp = db.get_search_result('ddoc001', 'searchindex001', query='name:julia*', group_field='name', limit=10) for group in resp['groups']: for row in group['rows']: # Process search index data (in JSON format). :param str ddoc_id: Design document id used to get the search result. :param str index_name: Name used in part to identify the index. :param str bookmark: Optional string that enables you to specify which page of results you require. Only valid for queries that do not specify the ``group_field`` query parameter. :param list counts: Optional JSON array of field names for which counts should be produced. The response will contain counts for each unique value of this field name among the documents matching the search query. Requires the index to have faceting enabled. :param list drilldown: Optional list of fields that each define a pair of a field name and a value. This field can be used several times. The search will only match documents that have the given value in the field name. It differs from using ``query=fieldname:value`` only in that the values are not analyzed. :param str group_field: Optional string field by which to group search matches. Fields containing other data (numbers, objects, arrays) can not be used. :param int group_limit: Optional number with the maximum group count. This field can only be used if ``group_field`` query parameter is specified. :param group_sort: Optional JSON field that defines the order of the groups in a search using ``group_field``. The default sort order is relevance. This field can have the same values as the sort field, so single fields as well as arrays of fields are supported. :param int limit: Optional number to limit the maximum count of the returned documents. In case of a grouped search, this parameter limits the number of documents per group. :param query/q: A Lucene query in the form of ``name:value``. If name is omitted, the special value ``default`` is used. The ``query`` parameter can be abbreviated as ``q``. :param ranges: Optional JSON facet syntax that reuses the standard Lucene syntax to return counts of results which fit into each specified category. Inclusive range queries are denoted by brackets. Exclusive range queries are denoted by curly brackets. For example ``ranges={"price":{"cheap":"[0 TO 100]"}}`` has an inclusive range of 0 to 100. Requires the index to have faceting enabled. :param sort: Optional JSON string of the form ``fieldname<type>`` for ascending or ``-fieldname<type>`` for descending sort order. Fieldname is the name of a string or number field and type is either number or string or a JSON array of such strings. The type part is optional and defaults to number. :param str stale: Optional string to allow the results from a stale index to be used. This makes the request return immediately, even if the index has not been completely built yet. :param list highlight_fields: Optional list of fields which should be highlighted. :param str highlight_pre_tag: Optional string inserted before the highlighted word in the highlights output. Defaults to ``<em>``. :param str highlight_post_tag: Optional string inserted after the highlighted word in the highlights output. Defaults to ``</em>``. :param int highlight_number: Optional number of fragments returned in highlights. If the search term occurs less often than the number of fragments specified, longer fragments are returned. Default is 1. :param int highlight_size: Optional number of characters in each fragment for highlights. Defaults to 100 characters. :param list include_fields: Optional list of field names to include in search results. Any fields included must have been indexed with the ``store:true`` option. :returns: Search query result data in JSON format """ |
ddoc = DesignDocument(self, ddoc_id)
return self._get_search_result(
'/'.join((ddoc.document_url, '_search', index_name)),
**query_params
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_search_result(self, query_url, **query_params):
""" Get search results helper. """ |
param_q = query_params.get('q')
param_query = query_params.get('query')
# Either q or query parameter is required
if bool(param_q) == bool(param_query):
raise CloudantArgumentError(104, query_params)
# Validate query arguments and values
for key, val in iteritems_(query_params):
if key not in list(SEARCH_INDEX_ARGS.keys()):
raise CloudantArgumentError(105, key)
if not isinstance(val, SEARCH_INDEX_ARGS[key]):
raise CloudantArgumentError(106, key, SEARCH_INDEX_ARGS[key])
# Execute query search
headers = {'Content-Type': 'application/json'}
resp = self.r_session.post(
query_url,
headers=headers,
data=json.dumps(query_params, cls=self.client.encoder)
)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_replication(self, source_db=None, target_db=None, repl_id=None, **kwargs):
""" Creates a new replication task. :param source_db: Database object to replicate from. Can be either a ``CouchDatabase`` or ``CloudantDatabase`` instance. :param target_db: Database object to replicate to. Can be either a ``CouchDatabase`` or ``CloudantDatabase`` instance. :param str repl_id: Optional replication id. Generated internally if not explicitly set. :param dict user_ctx: Optional user to act as. Composed internally if not explicitly set. :param bool create_target: Specifies whether or not to create the target, if it does not already exist. :param bool continuous: If set to True then the replication will be continuous. :returns: Replication document as a Document instance """ |
if source_db is None:
raise CloudantReplicatorException(101)
if target_db is None:
raise CloudantReplicatorException(102)
data = dict(
_id=repl_id if repl_id else str(uuid.uuid4()),
**kwargs
)
# replication source
data['source'] = {'url': source_db.database_url}
if source_db.admin_party:
pass # no credentials required
elif source_db.client.is_iam_authenticated:
data['source'].update({'auth': {
'iam': {'api_key': source_db.client.r_session.get_api_key}
}})
else:
data['source'].update({'headers': {
'Authorization': source_db.creds['basic_auth']
}})
# replication target
data['target'] = {'url': target_db.database_url}
if target_db.admin_party:
pass # no credentials required
elif target_db.client.is_iam_authenticated:
data['target'].update({'auth': {
'iam': {'api_key': target_db.client.r_session.get_api_key}
}})
else:
data['target'].update({'headers': {
'Authorization': target_db.creds['basic_auth']
}})
# add user context delegation
if not data.get('user_ctx') and self.database.creds and \
self.database.creds.get('user_ctx'):
data['user_ctx'] = self.database.creds['user_ctx']
return self.database.create_document(data, throw_on_exists=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_replications(self):
""" Retrieves all replication documents from the replication database. :returns: List containing replication Document objects """ |
docs = self.database.all_docs(include_docs=True)['rows']
documents = []
for doc in docs:
if doc['id'].startswith('_design/'):
continue
document = Document(self.database, doc['id'])
document.update(doc['doc'])
documents.append(document)
return documents |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def follow_replication(self, repl_id):
""" Blocks and streams status of a given replication. For example: .. code-block:: python for doc in replicator.follow_replication(repl_doc_id):
# Process replication information as it comes in :param str repl_id: Replication id used to identify the replication to inspect. :returns: Iterable stream of copies of the replication Document and replication state as a ``str`` for the specified replication id """ |
def update_state():
"""
Retrieves the replication state.
"""
if "scheduler" in self.client.features():
try:
arepl_doc = Scheduler(self.client).get_doc(repl_id)
return arepl_doc, arepl_doc['state']
except HTTPError:
return None, None
else:
try:
arepl_doc = self.database[repl_id]
arepl_doc.fetch()
return arepl_doc, arepl_doc.get('_replication_state')
except KeyError:
return None, None
while True:
# Make sure we fetch the state up front, just in case it moves
# too fast and we miss it in the changes feed.
repl_doc, state = update_state()
if repl_doc:
yield repl_doc
if state is not None and state in ['error', 'completed']:
return
# Now listen on changes feed for the state
for change in self.database.changes():
if change.get('id') == repl_id:
repl_doc, state = update_state()
if repl_doc is not None:
yield repl_doc
if state is not None and state in ['error', 'completed']:
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_replication(self, repl_id):
""" Stops a replication based on the provided replication id by deleting the replication document from the replication database. The replication can only be stopped if it has not yet completed. If it has already completed then the replication document is still deleted from replication database. :param str repl_id: Replication id used to identify the replication to stop. """ |
try:
repl_doc = self.database[repl_id]
except KeyError:
raise CloudantReplicatorException(404, repl_id)
repl_doc.fetch()
repl_doc.delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base64_user_pass(self):
""" Composes a basic http auth string, suitable for use with the _replicator database, and other places that need it. :returns: Basic http authentication string """ |
if self._username is None or self._password is None:
return None
hash_ = base64.urlsafe_b64encode(bytes_("{username}:{password}".format(
username=self._username,
password=self._password
)))
return "Basic {0}".format(unicode_(hash_)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, method, url, **kwargs):
""" Overrides ``requests.Session.request`` to set the timeout. """ |
resp = super(ClientSession, self).request(
method, url, timeout=self._timeout, **kwargs)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(self):
""" Get session information. """ |
if self._session_url is None:
return None
resp = self.get(self._session_url)
resp.raise_for_status()
return response_to_json_dict(resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_credentials(self, username, password):
""" Set a new username and password. :param str username: New username. :param str password: New password. """ |
if username is not None:
self._username = username
if password is not None:
self._password = password |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def request(self, method, url, **kwargs):
""" Overrides ``requests.Session.request`` to provide basic access authentication. """ |
auth = None
if self._username is not None and self._password is not None:
auth = (self._username, self._password)
return super(BasicSession, self).request(
method, url, auth=auth, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self):
""" Perform cookie based user login. """ |
resp = super(CookieSession, self).request(
'POST',
self._session_url,
data={'name': self._username, 'password': self._password},
)
resp.raise_for_status() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logout(self):
""" Logout cookie based user. """ |
resp = super(CookieSession, self).request('DELETE', self._session_url)
resp.raise_for_status() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self):
""" Perform IAM cookie based user login. """ |
access_token = self._get_access_token()
try:
super(IAMSession, self).request(
'POST',
self._session_url,
headers={'Content-Type': 'application/json'},
data=json.dumps({'access_token': access_token})
).raise_for_status()
except RequestException:
raise CloudantException(
'Failed to exchange IAM token with Cloudant') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_access_token(self):
""" Get IAM access token using API key. """ |
err = 'Failed to contact IAM token service'
try:
resp = super(IAMSession, self).request(
'POST',
self._token_url,
auth=self._token_auth,
headers={'Accepts': 'application/json'},
data={
'grant_type': 'urn:ibm:params:oauth:grant-type:apikey',
'response_type': 'cloud_iam',
'apikey': self._api_key
}
)
err = response_to_json_dict(resp).get('errorMessage', err)
resp.raise_for_status()
return response_to_json_dict(resp)['access_token']
except KeyError:
raise CloudantException('Invalid response from IAM token service')
except RequestException:
raise CloudantException(err) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def document_url(self):
""" Constructs and returns the document URL. :returns: Document URL """ |
if '_id' not in self or self['_id'] is None:
return None
# handle design document url
if self['_id'].startswith('_design/'):
return '/'.join((
self._database_host,
url_quote_plus(self._database_name),
'_design',
url_quote(self['_id'][8:], safe='')
))
# handle document url
return '/'.join((
self._database_host,
url_quote_plus(self._database_name),
url_quote(self['_id'], safe='')
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exists(self):
""" Retrieves whether the document exists in the remote database or not. :returns: True if the document exists in the remote database, otherwise False """ |
if '_id' not in self or self['_id'] is None:
return False
resp = self.r_session.head(self.document_url)
if resp.status_code not in [200, 404]:
resp.raise_for_status()
return resp.status_code == 200 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self):
""" Creates the current document in the remote database and if successful, updates the locally cached Document object with the ``_id`` and ``_rev`` returned as part of the successful response. """ |
# Ensure that an existing document will not be "updated"
doc = dict(self)
if doc.get('_rev') is not None:
doc.__delitem__('_rev')
headers = {'Content-Type': 'application/json'}
resp = self.r_session.post(
self._database.database_url,
headers=headers,
data=json.dumps(doc, cls=self.encoder)
)
resp.raise_for_status()
data = response_to_json_dict(resp)
super(Document, self).__setitem__('_id', data['id'])
super(Document, self).__setitem__('_rev', data['rev']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(self):
""" Retrieves the content of the current document from the remote database and populates the locally cached Document object with that content. A call to fetch will overwrite any dictionary content currently in the locally cached Document object. """ |
if self.document_url is None:
raise CloudantDocumentException(101)
resp = self.r_session.get(self.document_url)
resp.raise_for_status()
self.clear()
self.update(response_to_json_dict(resp, cls=self.decoder)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self):
""" Saves changes made to the locally cached Document object's data structures to the remote database. If the document does not exist remotely then it is created in the remote database. If the object does exist remotely then the document is updated remotely. In either case the locally cached Document object is also updated accordingly based on the successful response of the operation. """ |
headers = {}
headers.setdefault('Content-Type', 'application/json')
if not self.exists():
self.create()
return
put_resp = self.r_session.put(
self.document_url,
data=self.json(),
headers=headers
)
put_resp.raise_for_status()
data = response_to_json_dict(put_resp)
super(Document, self).__setitem__('_rev', data['rev'])
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_field_append(doc, field, value):
""" Appends a value to a list field in a locally cached Document object. If a field does not exist it will be created first. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. :param str field: Name of the field list to append to. :param value: Value to append to the field list. """ |
if doc.get(field) is None:
doc[field] = []
if not isinstance(doc[field], list):
raise CloudantDocumentException(102, field)
if value is not None:
doc[field].append(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_field_remove(doc, field, value):
""" Removes a value from a list field in a locally cached Document object. :param Document doc: Locally cached Document object that can be a Document, DesignDocument or dict. :param str field: Name of the field list to remove from. :param value: Value to remove from the field list. """ |
if not isinstance(doc[field], list):
raise CloudantDocumentException(102, field)
doc[field].remove(value) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.