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 get_withdrawal_quotas(self, currency):
"""Get withdrawal quotas for a currency https://docs.kucoin.com/#get-withdrawal-quotas :param currency: Name of currency :type currency: string .. code:: python quotas = client.get_withdrawal_quotas('ETH') :returns: ApiResponse .. code:: python { "currency": "ETH", "availableAmount": 2.9719999, "remainAmount": 2.9719999, "withdrawMinSize": 0.1000000, "limitBTCAmount": 2.0, "innerWithdrawMinFee": 0.00001, "isWithdrawEnabled": true, "withdrawMinFee": 0.0100000, "precision": 7 } :raises: KucoinResponseException, KucoinAPIException """ |
data = {
'currency': currency
}
return self._get('withdrawals/quotas', True, data=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 create_withdrawal(self, currency, amount, address, memo=None, is_inner=False, remark=None):
"""Process a withdrawal https://docs.kucoin.com/#apply-withdraw :param currency: Name of currency :type currency: string :param amount: Amount to withdraw :type amount: number :param address: Address to withdraw to :type address: string :param memo: (optional) Remark to the withdrawal address :type memo: string :param is_inner: (optional) Remark to the withdrawal address :type is_inner: bool :param remark: (optional) Remark :type remark: string .. code:: python withdrawal = client.create_withdrawal('NEO', 20, '598aeb627da3355fa3e851') :returns: ApiResponse .. code:: python { "withdrawalId": "5bffb63303aa675e8bbe18f9" } :raises: KucoinResponseException, KucoinAPIException """ |
data = {
'currency': currency,
'amount': amount,
'address': address
}
if memo:
data['memo'] = memo
if is_inner:
data['isInner'] = is_inner
if remark:
data['remark'] = remark
return self._post('withdrawals', True, data=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 create_market_order(self, symbol, side, size=None, funds=None, client_oid=None, remark=None, stp=None):
"""Create a market order One of size or funds must be set https://docs.kucoin.com/#place-a-new-order :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string :param side: buy or sell :type side: string :param size: (optional) Desired amount in base currency :type size: string :param funds: (optional) Desired amount of quote currency to use :type funds: string :param client_oid: (optional) Unique order id (default flat_uuid()) :type client_oid: string :param remark: (optional) remark for the order, max 100 utf8 characters :type remark: string :param stp: (optional) self trade protection CN, CO, CB or DC (default is None) :type stp: string .. code:: python order = client.create_market_order('NEO', Client.SIDE_BUY, size=20) :returns: ApiResponse .. code:: python { "orderOid": "596186ad07015679730ffa02" } :raises: KucoinResponseException, KucoinAPIException, MarketOrderException """ |
if not size and not funds:
raise MarketOrderException('Need size or fund parameter')
if size and funds:
raise MarketOrderException('Need size or fund parameter not both')
data = {
'side': side,
'symbol': symbol,
'type': self.ORDER_MARKET
}
if size:
data['size'] = size
if funds:
data['funds'] = funds
if client_oid:
data['clientOid'] = client_oid
else:
data['clientOid'] = flat_uuid()
if remark:
data['remark'] = remark
if stp:
data['stp'] = stp
return self._post('orders', True, data=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 cancel_all_orders(self, symbol=None):
"""Cancel all orders https://docs.kucoin.com/#cancel-all-orders .. code:: python res = client.cancel_all_orders() :returns: ApiResponse .. code:: python { "cancelledOrderIds": [ "5bd6e9286d99522a52e458de" ] } :raises: KucoinResponseException, KucoinAPIException """ |
data = {}
if symbol is not None:
data['symbol'] = symbol
return self._delete('orders', True, data=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 get_orders(self, symbol=None, status=None, side=None, order_type=None, start=None, end=None, page=None, limit=None):
"""Get list of orders https://docs.kucoin.com/#list-orders :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string :param status: (optional) Specify status active or done (default done) :type status: string :param side: (optional) buy or sell :type side: string :param order_type: (optional) limit, market, limit_stop or market_stop :type order_type: string :param start: (optional) Start time as unix timestamp :type start: string :param end: (optional) End time as unix timestamp :type end: string :param page: (optional) Page to fetch :type page: int :param limit: (optional) Number of orders :type limit: int .. code:: python orders = client.get_orders(symbol='KCS-BTC', status='active') :returns: ApiResponse .. code:: python { "currentPage": 1, "pageSize": 1, "totalNum": 153408, "totalPage": 153408, "items": [ { "id": "5c35c02703aa673ceec2a168", "symbol": "BTC-USDT", "opType": "DEAL", "type": "limit", "side": "buy", "price": "10", "size": "2", "funds": "0", "dealFunds": "0.166", "dealSize": "2", "fee": "0", "feeCurrency": "USDT", "stp": "", "stop": "", "stopTriggered": false, "stopPrice": "0", "timeInForce": "GTC", "postOnly": false, "hidden": false, "iceberge": false, "visibleSize": "0", "cancelAfter": 0, "channel": "IOS", "clientOid": null, "remark": null, "tags": null, "isActive": false, "cancelExist": false, "createdAt": 1547026471000 } ] } :raises: KucoinResponseException, KucoinAPIException """ |
data = {}
if symbol:
data['symbol'] = symbol
if status:
data['status'] = status
if side:
data['side'] = side
if order_type:
data['type'] = order_type
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['page'] = page
if limit:
data['pageSize'] = limit
return self._get('orders', True, data=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 get_historical_orders(self, symbol=None, side=None, start=None, end=None, page=None, limit=None):
"""List of KuCoin V1 historical orders. https://docs.kucoin.com/#get-v1-historical-orders-list :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string :param side: (optional) buy or sell :type side: string :param start: (optional) Start time as unix timestamp :type start: string :param end: (optional) End time as unix timestamp :type end: string :param page: (optional) Page to fetch :type page: int :param limit: (optional) Number of orders :type limit: int .. code:: python orders = client.get_historical_orders(symbol='KCS-BTC') :returns: ApiResponse .. code:: python { "currentPage": 1, "pageSize": 50, "totalNum": 1, "totalPage": 1, "items": [ { "symbol": "SNOV-ETH", "dealPrice": "0.0000246", "dealValue": "0.018942", "amount": "770", "fee": "0.00001137", "side": "sell", "createdAt": 1540080199 } ] } :raises: KucoinResponseException, KucoinAPIException """ |
data = {}
if symbol:
data['symbol'] = symbol
if side:
data['side'] = side
if start:
data['startAt'] = start
if end:
data['endAt'] = end
if page:
data['page'] = page
if limit:
data['pageSize'] = limit
return self._get('hist-orders', True, data=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 get_ticker(self, symbol=None):
"""Get symbol tick https://docs.kucoin.com/#get-ticker :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python all_ticks = client.get_ticker() ticker = client.get_ticker('ETH-BTC') :returns: ApiResponse .. code:: python { "sequence": "1545825031840", # now sequence "price": "3494.367783", # last trade price "size": "0.05027185", # last trade size "bestBid": "3494.367783", # best bid price "bestBidSize": "2.60323254", # size at best bid price "bestAsk": "3499.12", # best ask price "bestAskSize": "0.01474011" # size at best ask price } :raises: KucoinResponseException, KucoinAPIException """ |
data = {}
tick_path = 'market/allTickers'
if symbol is not None:
tick_path = 'market/orderbook/level1'
data = {
'symbol': symbol
}
return self._get(tick_path, False, data=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 get_fiat_prices(self, base=None, symbol=None):
"""Get fiat price for currency https://docs.kucoin.com/#get-fiat-price :param base: (optional) Fiat,eg.USD,EUR, default is USD. :type base: string :param symbol: (optional) Cryptocurrencies.For multiple cyrptocurrencies, please separate them with comma one by one. default is all :type symbol: string .. code:: python prices = client.get_fiat_prices() :returns: ApiResponse .. code:: python { "BTC": "3911.28000000", "ETH": "144.55492453", "LTC": "48.45888179", "KCS": "0.45546856" } :raises: KucoinResponseException, KucoinAPIException """ |
data = {}
if base is not None:
data['base'] = base
if symbol is not None:
data['currencies'] = symbol
return self._get('prices', False, data=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 get_24hr_stats(self, symbol):
"""Get 24hr stats for a symbol. Volume is in base currency units. open, high, low are in quote currency units. :param symbol: (optional) Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python stats = client.get_24hr_stats('ETH-BTC') :returns: ApiResponse Without a symbol param .. code:: python { "symbol": "BTC-USDT", "changeRate": "0.0128", # 24h change rate "changePrice": "0.8", # 24h rises and falls in price (if the change rate is a negative number, # the price rises; if the change rate is a positive number, the price falls.) "open": 61, # Opening price "close": 63.6, # Closing price "high": "63.6", # Highest price filled "low": "61", # Lowest price filled "vol": "244.78", # Transaction quantity "volValue": "15252.0127" # Transaction amount } :raises: KucoinResponseException, KucoinAPIException """ |
data = {
'symbol': symbol
}
return self._get('market/stats', False, data=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 get_order_book(self, symbol):
"""Get a list of bids and asks aggregated by price for a symbol. Returns up to 100 depth each side. Fastest Order book API https://docs.kucoin.com/#get-part-order-book-aggregated :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python orders = client.get_order_book('KCS-BTC') :returns: ApiResponse .. code:: python { "sequence": "3262786978", "bids": [ ["6500.12", "0.45054140"], # [price, size] ["6500.11", "0.45054140"] ], "asks": [ ["6500.16", "0.57753524"], ["6500.15", "0.57753524"] ] } :raises: KucoinResponseException, KucoinAPIException """ |
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2_100', False, data=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 get_full_order_book(self, symbol):
"""Get a list of all bids and asks aggregated by price for a symbol. This call is generally used by professional traders because it uses more server resources and traffic, and Kucoin has strict access frequency control. https://docs.kucoin.com/#get-full-order-book-aggregated :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python orders = client.get_order_book('KCS-BTC') :returns: ApiResponse .. code:: python { "sequence": "3262786978", "bids": [ ["6500.12", "0.45054140"], # [price size] ["6500.11", "0.45054140"] ], "asks": [ ["6500.16", "0.57753524"], ["6500.15", "0.57753524"] ] } :raises: KucoinResponseException, KucoinAPIException """ |
data = {
'symbol': symbol
}
return self._get('market/orderbook/level2', False, data=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 get_full_order_book_level3(self, symbol):
"""Get a list of all bids and asks non-aggregated for a symbol. This call is generally used by professional traders because it uses more server resources and traffic, and Kucoin has strict access frequency control. https://docs.kucoin.com/#get-full-order-book-atomic :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python orders = client.get_order_book('KCS-BTC') :returns: ApiResponse .. code:: python { "sequence": "1545896707028", "bids": [ [ "5c2477e503aa671a745c4057", # orderId "6", # price "0.999" # size ], [ "5c2477e103aa671a745c4054", "5", "0.999" ] ], "asks": [ [ "5c24736703aa671a745c401e", "200", "1" ], [ "5c2475c903aa671a745c4033", "201", "1" ] ] } :raises: KucoinResponseException, KucoinAPIException """ |
data = {
'symbol': symbol
}
return self._get('market/orderbook/level3', False, data=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 get_trade_histories(self, symbol):
"""List the latest trades for a symbol https://docs.kucoin.com/#get-trade-histories :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string .. code:: python orders = client.get_trade_histories('KCS-BTC') :returns: ApiResponse .. code:: python [ { "sequence": "1545896668571", "price": "0.07", # Filled price "size": "0.004", # Filled amount "side": "buy", # Filled side. The filled side is set to the taker by default. "time": 1545904567062140823 # Transaction time }, { "sequence": "1545896668578", "price": "0.054", "size": "0.066", "side": "buy", "time": 1545904581619888405 } ] :raises: KucoinResponseException, KucoinAPIException """ |
data = {
'symbol': symbol
}
return self._get('market/histories', False, data=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 get_kline_data(self, symbol, kline_type='5min', start=None, end=None):
"""Get kline data For each query, the system would return at most 1500 pieces of data. To obtain more data, please page the data by time. :param symbol: Name of symbol e.g. KCS-BTC :type symbol: string :param kline_type: type of symbol, type of candlestick patterns: 1min, 3min, 5min, 15min, 30min, 1hour, 2hour, 4hour, 6hour, 8hour, 12hour, 1day, 1week :type kline_type: string :param start: Start time as unix timestamp (optional) default start of day in UTC :type start: int :param end: End time as unix timestamp (optional) default now in UTC :type end: int https://docs.kucoin.com/#get-historic-rates .. code:: python klines = client.get_kline_data('KCS-BTC', '5min', 1507479171, 1510278278) :returns: ApiResponse .. code:: python [ [ "1545904980", //Start time of the candle cycle "0.058", //opening price "0.049", //closing price "0.058", //highest price "0.049", //lowest price "0.018", //Transaction amount "0.000945" //Transaction volume ], [ "1545904920", "0.058", "0.072", "0.072", "0.058", "0.103", "0.006986" ] ] :raises: KucoinResponseException, KucoinAPIException """ |
data = {
'symbol': symbol
}
if kline_type is not None:
data['type'] = kline_type
if start is not None:
data['startAt'] = start
else:
data['startAt'] = calendar.timegm(datetime.utcnow().date().timetuple())
if end is not None:
data['endAt'] = end
else:
data['endAt'] = int(time.time())
return self._get('market/candles', False, data=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 get_real_stored_key(self, session_key):
"""Return the real key name in redis storage @return string """ |
prefix = settings.SESSION_REDIS_PREFIX
if not prefix:
return session_key
return ':'.join([prefix, session_key]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def burn(features, sequence, zoom):
""" Burn a stream of GeoJSONs into a output stream of the tiles they intersect for a given zoom. """ |
features = [f for f in super_utils.filter_polygons(features)]
tiles = burntiles.burn(features, zoom)
for t in tiles:
click.echo(t.tolist()) |
<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, *args, **kwargs):
"""Saves this model instance to the database.""" |
max_retries = getattr(
settings,
'LOCALIZED_FIELDS_MAX_RETRIES',
100
)
if not hasattr(self, 'retries'):
self.retries = 0
with transaction.atomic():
try:
return super().save(*args, **kwargs)
except IntegrityError as ex:
# this is as retarded as it looks, there's no
# way we can put the retry logic inside the slug
# field class... we can also not only catch exceptions
# that apply to slug fields... so yea.. this is as
# retarded as it gets... i am sorry :(
if 'slug' not in str(ex):
raise ex
if self.retries >= max_retries:
raise ex
self.retries += 1
return self.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_python(self, value: Union[Dict[str, int], int, None]) -> LocalizedIntegerValue: """Converts the value from a database value into a Python value.""" |
db_value = super().to_python(value)
return self._convert_localized_value(db_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 get_prep_value(self, value: LocalizedIntegerValue) -> dict: """Gets the value in a format to store into the database.""" |
# apply default values
default_values = LocalizedIntegerValue(self.default)
if isinstance(value, LocalizedIntegerValue):
for lang_code, _ in settings.LANGUAGES:
local_value = value.get(lang_code)
if local_value is None:
value.set(lang_code, default_values.get(lang_code, None))
prepped_value = super().get_prep_value(value)
if prepped_value is None:
return None
# make sure all values are proper integers
for lang_code, _ in settings.LANGUAGES:
local_value = prepped_value[lang_code]
try:
if local_value is not None:
int(local_value)
except (TypeError, ValueError):
raise IntegrityError('non-integer value in column "%s.%s" violates '
'integer constraint' % (self.name, lang_code))
# convert to a string before saving because the underlying
# type is hstore, which only accept strings
prepped_value[lang_code] = str(local_value) if local_value is not None else None
return prepped_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 _make_unique_slug(slug: str, language: str, is_unique: Callable[[str], bool]) -> str: """Guarentees that the specified slug is unique by appending a number until it is unique. Arguments: slug: The slug to make unique. is_unique: Function that can be called to verify whether the generate slug is unique. Returns: A guarenteed unique slug. """ |
index = 1
unique_slug = slug
while not is_unique(unique_slug, language):
unique_slug = '%s-%d' % (slug, index)
index += 1
return unique_slug |
<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_populate_from_value(instance, field_name: Union[str, Tuple[str]], language: str):
"""Gets the value to create a slug from in the specified language. Arguments: instance: The model that the field resides on. field_name: The name of the field to generate a slug for. language: The language to generate the slug for. Returns: The text to generate a slug for. """ |
if callable(field_name):
return field_name(instance)
def get_field_value(name):
value = resolve_object_property(instance, name)
with translation.override(language):
return str(value)
if isinstance(field_name, tuple) or isinstance(field_name, list):
value = '-'.join([
value
for value in [get_field_value(name) for name in field_name]
if value
])
return value
return get_field_value(field_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 deconstruct(self):
"""Deconstructs the field into something the database can store.""" |
name, path, args, kwargs = super(
LocalizedUniqueSlugField, self).deconstruct()
kwargs['populate_from'] = self.populate_from
kwargs['include_time'] = self.include_time
return name, path, 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 contribute_to_class(self, model, name, **kwargs):
"""Adds this field to the specifed model. Arguments: cls: The model to add the field to. name: The name of the field to add. """ |
super(LocalizedField, self).contribute_to_class(model, name, **kwargs)
setattr(model, self.name, self.descriptor_class(self)) |
<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_prep_value(self, value: LocalizedValue) -> dict: """Turns the specified value into something the database can store. If an illegal value (non-LocalizedValue instance) is specified, we'll treat it as an empty :see:LocalizedValue instance, on which the validation will fail. Dictonaries are converted into :see:LocalizedValue instances. Arguments: value: The :see:LocalizedValue instance to serialize into a data type that the database can understand. Returns: A dictionary containing a key for every language, extracted from the specified value. """ |
if isinstance(value, dict):
value = LocalizedValue(value)
# default to None if this is an unknown type
if not isinstance(value, LocalizedValue) and value:
value = None
if value:
cleaned_value = self.clean(value)
self.validate(cleaned_value)
else:
cleaned_value = value
return super(LocalizedField, self).get_prep_value(
cleaned_value.__dict__ if cleaned_value else None
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean(self, value, *_):
"""Cleans the specified value into something we can store in the database. For example, when all the language fields are left empty, and the field is allowed to be null, we will store None instead of empty keys. Arguments: value: The value to clean. Returns: The cleaned value, ready for database storage. """ |
if not value or not isinstance(value, LocalizedValue):
return None
# are any of the language fiels None/empty?
is_all_null = True
for lang_code, _ in settings.LANGUAGES:
if value.get(lang_code) is not None:
is_all_null = False
break
# all fields have been left empty and we support
# null values, let's return null to represent that
if is_all_null and self.null:
return None
return 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 validate(self, value: LocalizedValue, *_):
"""Validates that the values has been filled in for all required languages Exceptions are raises in order to notify the user of invalid values. Arguments: value: The value to validate. """ |
if self.null:
return
for lang in self.required:
lang_val = getattr(value, settings.LANGUAGE_CODE)
if lang_val is None:
raise IntegrityError('null value in column "%s.%s" violates '
'not-null constraint' % (self.name, lang)) |
<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, language: str=None, default: str=None) -> str: """Gets the underlying value in the specified or primary language. Arguments: language: The language to get the value in. Returns: The value in the current language, or the primary language in case no language was specified. """ |
language = language or settings.LANGUAGE_CODE
value = super().get(language, default)
return value if value is not None else 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 set(self, language: str, value: str):
"""Sets the value in the specified language. Arguments: language: The language to set the value in. value: The value to set. """ |
self[language] = value
self.__dict__.update(self)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deconstruct(self) -> dict: """Deconstructs this value into a primitive type. Returns: A dictionary with all the localized values contained in this instance. """ |
path = 'localized_fields.value.%s' % self.__class__.__name__
return path, [self.__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 translate(self) -> Optional[str]: """Gets the value in the current language or falls back to the next language if there's no value in the current language.""" |
fallbacks = getattr(settings, 'LOCALIZED_FIELDS_FALLBACKS', {})
language = translation.get_language() or settings.LANGUAGE_CODE
languages = fallbacks.get(language, [settings.LANGUAGE_CODE])[:]
languages.insert(0, language)
for lang_code in languages:
value = self.get(lang_code)
if value:
return value or None
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(self):
"""Gets the value in the current language, or in the configured fallbck language.""" |
value = super().translate()
if value is None or (isinstance(value, str) and value.strip() == ''):
return None
return int(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 resolve_object_property(obj, path: str):
"""Resolves the value of a property on an object. Is able to resolve nested properties. For example, a path can be specified: 'other.beer.name' Raises: AttributeError: In case the property could not be resolved. Returns: The value of the specified property. """ |
value = obj
for path_part in path.split('.'):
value = getattr(value, path_part)
return 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 decompress(self, value: LocalizedValue) -> List[str]: """Decompresses the specified value so it can be spread over the internal widgets. Arguments: value: The :see:LocalizedValue to display in this widget. Returns: All values to display in the inner widgets. """ |
result = []
for lang_code, _ in settings.LANGUAGES:
if value:
result.append(value.get(lang_code))
else:
result.append(None)
return 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 register_target(repo_cmd, repo_service):
"""Decorator to register a class with an repo_service""" |
def decorate(klass):
log.debug('Loading service module class: {}'.format(klass.__name__) )
klass.command = repo_cmd
klass.name = repo_service
RepositoryService.service_map[repo_service] = klass
RepositoryService.command_map[repo_cmd] = repo_service
return klass
return decorate |
<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_service(cls, repository, command):
'''Accessor for a repository given a command
:param repository: git-python repository instance
:param command: aliased name of the service
:return: instance for using the service
'''
if not repository:
config = git_config.GitConfigParser(cls.get_config_path())
else:
config = repository.config_reader()
target = cls.command_map.get(command, command)
conf_section = list(filter(lambda n: 'gitrepo' in n and target in n, config.sections()))
http_section = [config._sections[scheme] for scheme in ('http', 'https') if scheme in config.sections()]
# check configuration constraints
if len(conf_section) == 0:
if not target:
raise ValueError('Service {} unknown'.format(target))
else:
config = dict()
elif len(conf_section) > 1:
raise ValueError('Too many configurations for service {}'.format(target))
# get configuration section as a dict
else:
config = config._sections[conf_section[0]]
if target in cls.service_map:
service = cls.service_map.get(target, cls)
service.name = target
else:
if 'type' not in config:
raise ValueError('Missing service type for custom service.')
if config['type'] not in cls.service_map:
raise ValueError('Service type {} does not exists.'.format(config['type']))
service = cls.service_map.get(config['type'], cls)
cls._current = service(repository, config, http_section)
return cls._current |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def format_path(self, repository, namespace=None, rw=False):
'''format the repository's URL
:param repository: name of the repository
:param namespace: namespace of the repository
:param rw: return a git+ssh URL if true, an https URL otherwise
:return: the full URI of the repository ready to use as remote
if namespace is not given, repository is expected to be of format
`<namespace>/<repository>`.
'''
repo = repository
if namespace:
repo = '{}/{}'.format(namespace, repository)
if not rw and repo.count('/') >= self._min_nested_namespaces:
return '{}/{}'.format(self.url_ro, repo)
elif rw and repo.count('/') >= self._min_nested_namespaces:
if self.url_rw.startswith('ssh://'):
return '{}/{}'.format(self.url_rw, repo)
else:
return '{}:{}'.format(self.url_rw, repo)
else:
raise ArgumentError("Cannot tell how to handle this url: `{}/{}`!".format(namespace, repo)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def open(self, user=None, repo=None):
'''Open the URL of a repository in the user's browser'''
webbrowser.open(self.format_path(repo, namespace=user, rw=False)) |
<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_fetch(self, user, repo, request, pull=False, force=False): #pragma: no cover
'''Fetches given request as a branch, and switch if pull is true
:param repo: name of the repository to create
Meant to be implemented by subclasses
'''
raise NotImplementedError |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def register_action(*args, **kwarg):
'''
Decorator for an action, the arguments order is not relevant, but it's best
to use the same order as in the docopt for clarity.
'''
def decorator(fun):
KeywordArgumentParser._action_dict[frozenset(args)] = fun
return fun
return decorator |
<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, bus_name, object_path=None, **kwargs):
"""Get a remote object. Parameters bus_name : string Name of the service that exposes this object. You may start with "." - then org.freedesktop will be automatically prepended. object_path : string, optional Path of the object. If not provided, bus_name translated to path format is used. Returns ------- ProxyObject implementing all the Interfaces exposed by the remote object. Note that it inherits from multiple Interfaces, so the method you want to use may be shadowed by another one, eg. from a newer version of the interface. Therefore, to interact with only a single interface, use: or simply which will give you access to the one specific interface. """ |
# Python 2 sux
for kwarg in kwargs:
if kwarg not in ("timeout",):
raise TypeError(self.__qualname__ + " got an unexpected keyword argument '{}'".format(kwarg))
timeout = kwargs.get("timeout", None)
bus_name = auto_bus_name(bus_name)
object_path = auto_object_path(bus_name, object_path)
ret = self.con.call_sync(
bus_name, object_path,
'org.freedesktop.DBus.Introspectable', "Introspect", None, GLib.VariantType.new("(s)"),
0, timeout_to_glib(timeout), None)
if not ret:
raise KeyError("no such object; you might need to pass object path as the 2nd argument for get()")
xml, = ret.unpack()
try:
introspection = ET.fromstring(xml)
except:
raise KeyError("object provides invalid introspection XML")
return CompositeInterface(introspection)(self, bus_name, object_path) |
<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_name(self, name, allow_replacement=True, replace=False):
"""Aquires a bus name. Returns ------- NameOwner An object you can use as a context manager to unown the name later. """ |
return NameOwner(self, name, allow_replacement, replace) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def subscribe(self, sender=None, iface=None, signal=None, object=None, arg0=None, flags=0, signal_fired=None):
"""Subscribes to matching signals. Subscribes to signals on connection and invokes signal_fired callback whenever the signal is received. To receive signal_fired callback, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters sender : string, optional Sender name to match on (unique or well-known name) or None to listen from all senders. iface : string, optional Interface name to match on or None to match on all interfaces. signal : string, optional Signal name to match on or None to match on all signals. object : string, optional Object path to match on or None to match on all object paths. arg0 : string, optional Contents of first string argument to match on or None to match on all kinds of arguments. flags : SubscriptionFlags, optional signal_fired : callable, optional Invoked when there is a signal matching the requested data. Parameters: sender, object, iface, signal, params Returns ------- Subscription An object you can use as a context manager to unsubscribe from the signal later. See Also -------- See https://developer.gnome.org/gio/2.44/GDBusConnection.html#g-dbus-connection-signal-subscribe for more information. """ |
callback = (lambda con, sender, object, iface, signal, params: signal_fired(sender, object, iface, signal, params.unpack())) if signal_fired is not None else lambda *args: None
return Subscription(self.con, sender, iface, signal, object, arg0, flags, callback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watch_name(self, name, flags=0, name_appeared=None, name_vanished=None):
"""Asynchronously watches a bus name. Starts watching name on the bus specified by bus_type and calls name_appeared and name_vanished when the name is known to have a owner respectively known to lose its owner. To receive name_appeared and name_vanished callbacks, you need an event loop. https://github.com/LEW21/pydbus/blob/master/doc/tutorial.rst#setting-up-an-event-loop Parameters name : string Bus name to watch flags : NameWatcherFlags, optional name_appeared : callable, optional Invoked when name is known to exist Called as name_appeared(name_owner). name_vanished : callable, optional Invoked when name is known to not exist Returns ------- NameWatcher An object you can use as a context manager to unwatch the name later. See Also -------- See https://developer.gnome.org/gio/2.44/gio-Watching-Bus-Names.html#g-bus-watch-name for more information. """ |
name_appeared_handler = (lambda con, name, name_owner: name_appeared(name_owner)) if name_appeared is not None else None
name_vanished_handler = (lambda con, name: name_vanished()) if name_vanished is not None else None
return NameWatcher(self.con, name, flags, name_appeared_handler, name_vanished_handler) |
<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):
""" retreive metadata and currenct price data """ |
url = "{}/v7/finance/quote?symbols={}".format(
self._base_url, self.ticker)
r = _requests.get(url=url).json()["quoteResponse"]["result"]
if len(r) > 0:
return r[0]
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 pingable_ws_connect(request=None, on_message_callback=None, on_ping_callback=None):
""" A variation on websocket_connect that returns a PingableWSClientConnection with on_ping_callback. """ |
# Copy and convert the headers dict/object (see comments in
# AsyncHTTPClient.fetch)
request.headers = httputil.HTTPHeaders(request.headers)
request = httpclient._RequestProxy(
request, httpclient.HTTPRequest._DEFAULTS)
# for tornado 4.5.x compatibility
if version_info[0] == 4:
conn = PingableWSClientConnection(io_loop=ioloop.IOLoop.current(),
request=request,
on_message_callback=on_message_callback,
on_ping_callback=on_ping_callback)
else:
conn = PingableWSClientConnection(request=request,
on_message_callback=on_message_callback,
on_ping_callback=on_ping_callback,
max_message_size=getattr(websocket, '_default_max_message_size', 10 * 1024 * 1024))
return conn.connect_future |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_with_asked_args(callback, args):
""" Call callback with only the args it wants from args Example 20 """ |
# FIXME: support default args
# FIXME: support kwargs
# co_varnames contains both args and local variables, in order.
# We only pick the local variables
asked_arg_names = callback.__code__.co_varnames[:callback.__code__.co_argcount]
asked_arg_values = []
missing_args = []
for asked_arg_name in asked_arg_names:
if asked_arg_name in args:
asked_arg_values.append(args[asked_arg_name])
else:
missing_args.append(asked_arg_name)
if missing_args:
raise TypeError(
'{}() missing required positional argument: {}'.format(
callback.__code__.co_name,
', '.join(missing_args)
)
)
return callback(*asked_arg_values) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port):
""" Create a SuperviseAndProxyHandler subclass with given parameters """ |
# FIXME: Set 'name' properly
class _Proxy(SuperviseAndProxyHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = name
self.proxy_base = name
self.absolute_url = absolute_url
self.requested_port = port
@property
def process_args(self):
return {
'port': self.port,
'base_url': self.base_url,
}
def _render_template(self, value):
args = self.process_args
if type(value) is str:
return value.format(**args)
elif type(value) is list:
return [self._render_template(v) for v in value]
elif type(value) is dict:
return {
self._render_template(k): self._render_template(v)
for k, v in value.items()
}
else:
raise ValueError('Value of unrecognized type {}'.format(type(value)))
def get_cmd(self):
if callable(command):
return self._render_template(call_with_asked_args(command, self.process_args))
else:
return self._render_template(command)
def get_env(self):
if callable(environment):
return self._render_template(call_with_asked_args(environment, self.process_args))
else:
return self._render_template(environment)
def get_timeout(self):
return timeout
return _Proxy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_handlers(base_url, server_processes):
""" Get tornado handlers for registered server_processes """ |
handlers = []
for sp in server_processes:
handler = _make_serverproxy_handler(
sp.name,
sp.command,
sp.environment,
sp.timeout,
sp.absolute_url,
sp.port,
)
handlers.append((
ujoin(base_url, sp.name, r'(.*)'), handler, dict(state={}),
))
handlers.append((
ujoin(base_url, sp.name), AddSlashHandler
))
return handlers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def open(self, port, proxied_path=''):
""" Called when a client opens a websocket connection. We establish a websocket connection to the proxied backend & set up a callback to relay messages through. """ |
if not proxied_path.startswith('/'):
proxied_path = '/' + proxied_path
client_uri = self.get_client_uri('ws', port, proxied_path)
headers = self.request.headers
def message_cb(message):
"""
Callback when the backend sends messages to us
We just pass it back to the frontend
"""
# Websockets support both string (utf-8) and binary data, so let's
# make sure we signal that appropriately when proxying
self._record_activity()
if message is None:
self.close()
else:
self.write_message(message, binary=isinstance(message, bytes))
def ping_cb(data):
"""
Callback when the backend sends pings to us.
We just pass it back to the frontend.
"""
self._record_activity()
self.ping(data)
async def start_websocket_connection():
self.log.info('Trying to establish websocket connection to {}'.format(client_uri))
self._record_activity()
request = httpclient.HTTPRequest(url=client_uri, headers=headers)
self.ws = await pingable_ws_connect(request=request,
on_message_callback=message_cb, on_ping_callback=ping_cb)
self._record_activity()
self.log.info('Websocket connection established to {}'.format(client_uri))
ioloop.IOLoop.current().add_callback(start_websocket_connection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_message(self, message):
""" Called when we receive a message from our client. We proxy it to the backend. """ |
self._record_activity()
if hasattr(self, 'ws'):
self.ws.write_message(message, binary=isinstance(message, bytes)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_ping(self, data):
""" Called when the client pings our websocket connection. We proxy it to the backend. """ |
self.log.debug('jupyter_server_proxy: on_ping: {}'.format(data))
self._record_activity()
if hasattr(self, 'ws'):
self.ws.protocol.write_ping(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 select_subprotocol(self, subprotocols):
'''Select a single Sec-WebSocket-Protocol during handshake.'''
if isinstance(subprotocols, list) and subprotocols:
self.log.info('Client sent subprotocols: {}'.format(subprotocols))
return subprotocols[0]
return super().select_subprotocol(subprotocols) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def port(self):
""" Allocate either the requested port or a random empty port for use by application """ |
if 'port' not in self.state:
sock = socket.socket()
sock.bind(('', self.requested_port))
self.state['port'] = sock.getsockname()[1]
sock.close()
return self.state['port'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setup_shiny():
'''Manage a Shiny instance.''' name = 'shiny' def _get_shiny_cmd(port):
conf = dedent(""" run_as {user}; server {{ listen {port}; location / {{ site_dir {site_dir}; log_dir {site_dir}/logs; directory_index on; }} }} """ | ).format(
user=getpass.getuser(),
port=str(port),
site_dir=os.getcwd()
)
f = tempfile.NamedTemporaryFile(mode='w', delete=False)
f.write(conf)
f.close()
return ['shiny-server', f.name]
return {
'command': _get_shiny_cmd,
'launcher_entry': {
'title': 'Shiny',
'icon_path': os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icons', 'shiny.svg')
}
} |
<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(self, result):
""" Filter the specified result based on query criteria. @param result: A potential result. @type result: L{sxbase.SchemaObject} @return: True if result should be excluded. @rtype: boolean """ |
if result is None:
return True
reject = result in self.history
if reject:
log.debug('result %s, rejected by\n%s', Repr(result), self)
return reject |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def result(self, result):
""" Query result post processing. @param result: A query result. @type result: L{sxbase.SchemaObject} """ |
if result is None:
log.debug('%s, not-found', self.ref)
return
if self.resolved:
result = result.resolve()
log.debug('%s, found as: %s', self.ref, Repr(result))
self.history.append(result)
return 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 add(self, *items):
""" Add items to be sorted. @param items: One or more items to be added. @type items: I{item} @return: self @rtype: L{DepList} """ |
for item in items:
self.unsorted.append(item)
key = item[0]
self.index[key] = item
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sort(self):
""" Sort the list based on dependancies. @return: The sorted items. @rtype: list """ |
self.sorted = list()
self.pushed = set()
for item in self.unsorted:
popped = []
self.push(item)
while len(self.stack):
try:
top = self.top()
ref = next(top[1])
refd = self.index.get(ref)
if refd is None:
log.debug('"%s" not found, skipped', Repr(ref))
continue
self.push(refd)
except StopIteration:
popped.append(self.pop())
continue
for p in popped:
self.sorted.append(p)
self.unsorted = self.sorted
return self.sorted |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push(self, item):
""" Push and item onto the sorting stack. @param item: An item to push. @type item: I{item} @return: The number of items pushed. @rtype: int """ |
if item in self.pushed:
return
frame = (item, iter(item[1]))
self.stack.append(frame)
self.pushed.add(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, url):
""" Download the docuemnt. @param url: A document url. @type url: str. @return: A file pointer to the docuemnt. @rtype: file-like """ |
store = DocumentStore()
fp = store.open(url)
if fp is None:
fp = self.options.transport.open(Request(url))
content = fp.read()
fp.close()
ctx = self.plugins.document.loaded(url=url, document=content)
content = ctx.document
sax = Parser()
return sax.parse(string=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 open(self, url):
""" Open a document at the specified url. @param url: A document URL. @type url: str @return: A file pointer to the document. @rtype: StringIO """ |
protocol, location = self.split(url)
if protocol == self.protocol:
return self.find(location)
else:
return None |
<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_children(self, root):
""" Add child objects using the factory """ |
for c in root.getChildren(ns=wsdlns):
child = Factory.create(c, self)
if child is None:
continue
self.children.append(child)
if isinstance(child, Import):
self.imports.append(child)
continue
if isinstance(child, Types):
self.types.append(child)
continue
if isinstance(child, Message):
self.messages[child.qname] = child
continue
if isinstance(child, PortType):
self.port_types[child.qname] = child
continue
if isinstance(child, Binding):
self.bindings[child.qname] = child
continue
if isinstance(child, Service):
self.services.append(child)
continue |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, definitions):
""" Load the object by opening the URL """ |
url = self.location
log.debug('importing (%s)', url)
if '://' not in url:
url = urljoin(definitions.url, url)
options = definitions.options
d = Definitions(url, options)
if d.root.match(Definitions.Tag, wsdlns):
self.import_definitions(definitions, d)
return
if d.root.match(Schema.Tag, Namespace.xsdns):
self.import_schema(definitions, d)
return
raise Exception('document at "%s" is unknown' % url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __getref(self, a, tns):
""" Get the qualified value of attribute named 'a'.""" |
s = self.root.get(a)
if s is None:
return s
else:
return qualify(s, self.root, tns) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translated(self, value, type):
""" translate using the schema type """ |
if value is not None:
resolved = type.resolve()
return resolved.translate(value)
else:
return 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 open(self, options):
""" Open and import the refrenced schema. @param options: An options dictionary. @type options: L{options.Options} @return: The referenced schema. @rtype: L{Schema} """ |
if self.opened:
return
self.opened = True
log.debug('%s, importing ns="%s", location="%s"',
self.id,
self.ns[1],
self.location
)
result = self.locate()
if result is None:
if self.location is None:
log.debug('imported schema (%s) not-found', self.ns[1])
else:
result = self.download(options)
log.debug('imported:\n%s', result)
return 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 open(self, options):
""" Open and include the refrenced schema. @param options: An options dictionary. @type options: L{options.Options} @return: The referenced schema. @rtype: L{Schema} """ |
if self.opened:
return
self.opened = True
log.debug('%s, including location="%s"', self.id, self.location)
result = self.download(options)
log.debug('included:\n%s', result)
return 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 download(self, options):
""" download the schema """ |
url = self.location
try:
if '://' not in url:
url = urljoin(self.schema.baseurl, url)
reader = DocumentReader(options)
d = reader.open(url)
root = d.root()
root.set('url', url)
self.__applytns(root)
return self.schema.instance(root, url, options)
except TransportError:
msg = 'include schema at (%s), failed' % url
log.error('%s, %s', self.id, msg, exc_info=True)
raise Exception(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(cls, root, schema, filter=('*',)):
""" Build an xsobject representation. @param root: An schema XML root. @type root: L{sax.element.Element} @param filter: A tag filter. @return: A schema object graph. @rtype: L{sxbase.SchemaObject} """ |
children = []
for node in root.getChildren(ns=Namespace.xsdns):
if '*' in filter or node.name in filter:
child = cls.create(node, schema)
if child is None:
continue
children.append(child)
c = cls.build(node, schema, child.childtags())
child.rawchildren = c
return children |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clone(self, parent=None):
""" Clone this object. @param parent: The parent for the clone. @type parent: L{element.Element} @return: A copy of this object assigned to the new parent. @rtype: L{Attribute} """ |
a = Attribute(self.qname(), self.value)
a.parent = parent
return a |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setValue(self, value):
""" Set the attributes value @param value: The new value (may be None) @type value: basestring @return: self @rtype: L{Attribute} """ |
if isinstance(value, Text):
self.value = value
else:
self.value = Text(value)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def namespace(self):
""" Get the attributes namespace. This may either be the namespace defined by an optional prefix, or its parent's namespace. @return: The attribute's namespace @rtype: (I{prefix}, I{name}) """ |
if self.prefix is None:
return Namespace.default
else:
return self.resolvePrefix(self.prefix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolvePrefix(self, prefix):
""" Resolve the specified prefix to a known namespace. @param prefix: A declared prefix @type prefix: basestring @return: The namespace that has been mapped to I{prefix} @rtype: (I{prefix}, I{name}) """ |
ns = Namespace.default
if self.parent is not None:
ns = self.parent.resolvePrefix(prefix)
return ns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unmarshaller(self, typed=True):
""" Get the appropriate XML decoder. @return: Either the (basic|typed) unmarshaller. @rtype: L{UmxTyped} """ |
if typed:
return UmxEncoded(self.schema())
else:
return RPC.unmarshaller(self, typed) |
<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_options(self, **kwargs):
""" Set options. @param kwargs: keyword arguments. @see: L{Options} """ |
p = Unskin(self.options)
p.update(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 clone(self):
""" Get a shallow clone of this object. The clone only shares the WSDL. All other attributes are unique to the cloned object including options. @return: A shallow clone. @rtype: L{Client} """ |
class Uninitialized(Client):
def __init__(self):
pass
clone = Uninitialized()
clone.options = Options()
cp = Unskin(clone.options)
mp = Unskin(self.options)
cp.update(deepcopy(mp))
clone.wsdl = self.wsdl
clone.factory = self.factory
clone.service = ServiceSelector(clone, self.wsdl.services)
clone.sd = self.sd
clone.messages = dict(tx=None, rx=None)
return clone |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __reply(self, reply, args, kwargs):
""" simulate the reply """ |
binding = self.method.binding.input
msg = binding.get_message(self.method, args, kwargs)
log.debug('inject (simulated) send message:\n%s', msg)
binding = self.method.binding.output
return self.succeeded(binding, reply) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tostr(object, encoding=None):
""" get a unicode safe string representation of an object """ |
if isinstance(object, basestring):
if encoding is None:
return object
else:
return object.encode(encoding)
if isinstance(object, tuple):
s = ['(']
for item in object:
if isinstance(item, basestring):
s.append(item)
else:
s.append(tostr(item))
s.append(', ')
s.append(')')
return ''.join(s)
if isinstance(object, list):
s = ['[']
for item in object:
if isinstance(item, basestring):
s.append(item)
else:
s.append(tostr(item))
s.append(', ')
s.append(']')
return ''.join(s)
if isinstance(object, dict):
s = ['{']
for item in object.items():
if isinstance(item[0], basestring):
s.append(item[0])
else:
s.append(tostr(item[0]))
s.append(' = ')
if isinstance(item[1], basestring):
s.append(item[1])
else:
s.append(tostr(item[1]))
s.append(', ')
s.append('}')
return ''.join(s)
try:
return unicode(object)
except:
return str(object) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, options):
""" Load the schema objects for the root nodes. - de-references schemas - merge schemas @param options: An options dictionary. @type options: L{options.Options} @return: The merged schema. @rtype: L{Schema} """ |
if options.autoblend:
self.autoblend()
for child in self.children:
child.build()
for child in self.children:
child.open_imports(options)
for child in self.children:
child.dereference()
log.debug('loaded:\n%s', self)
merged = self.merge()
log.debug('MERGED:\n%s', merged)
return merged |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autoblend(self):
""" Ensure that all schemas within the collection import each other which has a blending effect. @return: self @rtype: L{SchemaCollection} """ |
namespaces = self.namespaces.keys()
for s in self.children:
for ns in namespaces:
tns = s.root.get('targetNamespace')
if tns == ns:
continue
for imp in s.root.getChildren('import'):
if imp.get('namespace') == ns:
continue
imp = Element('import', ns=Namespace.xsdns)
imp.set('namespace', ns)
s.root.append(imp)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(self, schema):
""" Merge the contents from the schema. Only objects not already contained in this schema's collections are merged. This is to provide for bidirectional import which produce cyclic includes. @returns: self @rtype: L{Schema} """ |
for item in schema.attributes.items():
if item[0] in self.attributes:
continue
self.all.append(item[1])
self.attributes[item[0]] = item[1]
for item in schema.elements.items():
if item[0] in self.elements:
continue
self.all.append(item[1])
self.elements[item[0]] = item[1]
for item in schema.types.items():
if item[0] in self.types:
continue
self.all.append(item[1])
self.types[item[0]] = item[1]
for item in schema.groups.items():
if item[0] in self.groups:
continue
self.all.append(item[1])
self.groups[item[0]] = item[1]
for item in schema.agrps.items():
if item[0] in self.agrps:
continue
self.all.append(item[1])
self.agrps[item[0]] = item[1]
schema.merged = True
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def leaf(self, parent, parts):
""" Find the leaf. @param parts: A list of path parts. @type parts: [str,..] @param parent: The leaf's parent. @type parent: L{xsd.sxbase.SchemaObject} @return: The leaf. @rtype: L{xsd.sxbase.SchemaObject} """ |
name = splitPrefix(parts[-1])[1]
if name.startswith('@'):
result, path = parent.get_attribute(name[1:])
else:
result, ancestry = parent.get_child(name)
if result is None:
raise PathResolver.BadPath(name)
return 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 findattr(self, name, resolved=True):
""" Find an attribute type definition. @param name: An attribute name. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolved: boolean @return: The found schema I{type} @rtype: L{xsd.sxbase.SchemaObject} """ |
name = '@%s' % name
parent = self.top().resolved
if parent is None:
result, ancestry = self.query(name, node)
else:
result, ancestry = self.getchild(name, parent)
if result is None:
return result
if resolved:
result = result.resolve()
return 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 known(self, node):
""" resolve type referenced by @xsi:type """ |
ref = node.get('type', Namespace.xsins)
if ref is None:
return None
qref = qualify(ref, node, node.namespace())
query = BlindQuery(qref)
return query.execute(self.schema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def known(self, object):
""" get the type specified in the object's metadata """ |
try:
md = object.__metadata__
known = md.sxtype
return known
except:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pushprefixes(self):
""" Add our prefixes to the wsdl so that when users invoke methods and reference the prefixes, the will resolve properly. """ |
for ns in self.prefixes:
self.wsdl.root.addPrefix(ns[0], ns[1]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findport(self, port):
""" Find and return a port tuple for the specified port. Created and added when not found. @param port: A port. @type port: I{service.Port} @return: A port tuple. @rtype: (port, [method]) """ |
for p in self.ports:
if p[0] == p:
return p
p = (port, [])
self.ports.append(p)
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paramtypes(self):
""" get all parameter types """ |
for m in [p[1] for p in self.ports]:
for p in [p[1] for p in m]:
for pd in p:
if pd[1] in self.params:
continue
item = (pd[1], pd[1].resolve())
self.params.append(item) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def u2handlers(self):
""" Get a collection of urllib handlers. @return: A list of handlers to be installed in the opener. """ |
handlers = []
handlers.append(u2.ProxyHandler(self.proxy))
return handlers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setPrefix(self, p, u=None):
""" Set the element namespace prefix. @param p: A new prefix for the element. @type p: basestring @param u: A namespace URI to be mapped to the prefix. @type u: basestring @return: self @rtype: L{Element} """ |
self.prefix = p
if p is not None and u is not None:
self.addPrefix(p, u)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detach(self):
""" Detach from parent. @return: This element removed from its parent's child list and I{parent}=I{None} @rtype: L{Element} """ |
if self.parent is not None:
if self in self.parent.children:
self.parent.children.remove(self)
self.parent = None
return self |
<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(self, name, value):
""" Set an attribute's value. @param name: The name of the attribute. @type name: basestring @param value: The attribute value. @type value: basestring @see: __setitem__() """ |
attr = self.getAttribute(name)
if attr is None:
attr = Attribute(name, value)
self.append(attr)
else:
attr.setValue(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 trim(self):
""" Trim leading and trailing whitespace. @return: self @rtype: L{Element} """ |
if self.hasText():
self.text = self.text.trim()
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(self, child):
""" Remove the specified child element or attribute. @param child: A child to remove. @type child: L{Element}|L{Attribute} @return: The detached I{child} when I{child} is an element, else None. @rtype: L{Element}|None """ |
if isinstance(child, Element):
return child.detach()
if isinstance(child, Attribute):
self.attributes.remove(child)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detachChildren(self):
""" Detach and return this element's children. @return: The element's children (detached). """ |
detached = self.children
self.children = []
for child in detached:
child.parent = None
return detached |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clearPrefix(self, prefix):
""" Clear the specified prefix from the prefix mappings. @param prefix: A prefix to clear. @type prefix: basestring @return: self @rtype: L{Element} """ |
if prefix in self.nsprefixes:
del self.nsprefixes[prefix]
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findPrefix(self, uri, default=None):
""" Find the first prefix that has been mapped to a namespace URI. The local mapping is searched, then it walks up the tree until it reaches the top or finds a match. @param uri: A namespace URI. @type uri: basestring @param default: A default prefix when not found. @type default: basestring @return: A mapped prefix. @rtype: basestring """ |
for item in self.nsprefixes.items():
if item[1] == uri:
prefix = item[0]
return prefix
for item in self.specialprefixes.items():
if item[1] == uri:
prefix = item[0]
return prefix
if self.parent is not None:
return self.parent.findPrefix(uri, default)
else:
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 findPrefixes(self, uri, match='eq'):
""" Find all prefixes that has been mapped to a namespace URI. The local mapping is searched, then it walks up the tree until it reaches the top collecting all matches. @param uri: A namespace URI. @type uri: basestring @param match: A matching function L{Element.matcher}. @type match: basestring @return: A list of mapped prefixes. """ |
result = []
for item in self.nsprefixes.items():
if self.matcher[match](item[1], uri):
prefix = item[0]
result.append(prefix)
for item in self.specialprefixes.items():
if self.matcher[match](item[1], uri):
prefix = item[0]
result.append(prefix)
if self.parent is not None:
result += self.parent.findPrefixes(uri, match)
return 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 promotePrefixes(self):
""" Push prefix declarations up the tree as far as possible. Prefix mapping are pushed to its parent unless the parent has the prefix mapped to another URI or the parent has the prefix. This is propagated up the tree until the top is reached. @return: self @rtype: L{Element} """ |
for c in self.children:
c.promotePrefixes()
if self.parent is None:
return
_pref = []
for p, u in self.nsprefixes.items():
if p in self.parent.nsprefixes:
pu = self.parent.nsprefixes[p]
if pu == u:
_pref.append(p)
continue
if p != self.parent.prefix:
self.parent.nsprefixes[p] = u
_pref.append(p)
for x in _pref:
del self.nsprefixes[x]
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refitPrefixes(self):
""" Refit namespace qualification by replacing prefixes with explicit namespaces. Also purges prefix mapping table. @return: self @rtype: L{Element} """ |
for c in self.children:
c.refitPrefixes()
if self.prefix is not None:
ns = self.resolvePrefix(self.prefix)
if ns[1] is not None:
self.expns = ns[1]
self.prefix = None
self.nsprefixes = {}
return self |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.