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_blockchain_fee_estimates(coin_symbol='btc', api_key=None):
""" Returns high, medium, and low fee estimates for a given blockchain. """ |
overview = get_blockchain_overview(coin_symbol=coin_symbol, api_key=api_key)
return {
'high_fee_per_kb': overview['high_fee_per_kb'],
'medium_fee_per_kb': overview['medium_fee_per_kb'],
'low_fee_per_kb': overview['low_fee_per_kb'],
} |
<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_forwarding_address_details(destination_address, api_key, callback_url=None, coin_symbol='btc'):
""" Give a destination address and return the details of the input address that will automatically forward to the destination address Note: a blockcypher api_key is required for this method """ |
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'payments')
logger.info(url)
params = {'token': api_key}
data = {
'destination': destination_address,
}
if callback_url:
data['callback_url'] = callback_url
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) |
<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_forwarding_address(destination_address, api_key, callback_url=None, coin_symbol='btc'):
""" Give a destination address and return an input address that will automatically forward to the destination address. See get_forwarding_address_details if you also need the forwarding address ID. Note: a blockcypher api_key is required for this method """ |
assert api_key, 'api_key required'
resp_dict = get_forwarding_address_details(
destination_address=destination_address,
api_key=api_key,
callback_url=callback_url,
coin_symbol=coin_symbol
)
return resp_dict['input_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 delete_forwarding_address(payment_id, coin_symbol='btc', api_key=None):
'''
Delete a forwarding address on a specific blockchain, using its
payment id
'''
assert payment_id, 'payment_id required'
assert is_valid_coin_symbol(coin_symbol)
assert api_key, 'api_key required'
params = {'token': api_key}
url = make_url(**dict(payments=payment_id))
r = requests.delete(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=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 send_faucet_coins(address_to_fund, satoshis, api_key, coin_symbol='bcy'):
'''
Send yourself test coins on the bitcoin or blockcypher testnet
You can see your balance info at:
- https://live.blockcypher.com/bcy/ for BCY
- https://live.blockcypher.com/btc-testnet/ for BTC Testnet
'''
assert coin_symbol in ('bcy', 'btc-testnet')
assert is_valid_address_for_coinsymbol(b58_address=address_to_fund, coin_symbol=coin_symbol)
assert satoshis > 0
assert api_key, 'api_key required'
url = make_url(coin_symbol, 'faucet')
data = {
'address': address_to_fund,
'amount': satoshis,
}
params = {'token': api_key}
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) |
<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_wallet_names(api_key, is_hd_wallet=False, coin_symbol='btc'):
''' Get all the wallets belonging to an API key '''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key
params = {'token': api_key}
kwargs = dict(wallets='hd' if is_hd_wallet else '')
url = make_url(coin_symbol, **kwargs)
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) |
<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_wallet_from_address(wallet_name, address, api_key, coin_symbol='btc'):
'''
Create a new wallet with one address
You can add addresses with the add_address_to_wallet method below
You can delete the wallet with the delete_wallet method below
'''
assert is_valid_address_for_coinsymbol(address, coin_symbol)
assert api_key
assert is_valid_wallet_name(wallet_name), wallet_name
data = {
'name': wallet_name,
'addresses': [address, ],
}
params = {'token': api_key}
url = make_url(coin_symbol, 'wallets')
r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) |
<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_wallet_addresses(wallet_name, api_key, is_hd_wallet=False,
zero_balance=None, used=None, omit_addresses=False, coin_symbol='btc'):
'''
Returns a list of wallet addresses as well as some meta-data
'''
assert is_valid_coin_symbol(coin_symbol)
assert api_key
assert len(wallet_name) <= 25, wallet_name
assert zero_balance in (None, True, False)
assert used in (None, True, False)
assert isinstance(omit_addresses, bool), omit_addresses
params = {'token': api_key}
kwargs = {'hd/' if is_hd_wallet else '': wallet_name} # hack!
url = make_url(coin_symbol, 'wallets', **kwargs)
if zero_balance is True:
params['zerobalance'] = 'true'
elif zero_balance is False:
params['zerobalance'] = 'false'
if used is True:
params['used'] = 'true'
elif used is False:
params['used'] = 'false'
if omit_addresses:
params['omitWalletAddresses'] = 'true'
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r) |
<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_tx_signatures(txs_to_sign, privkey_list, pubkey_list):
""" Loops through txs_to_sign and makes signatures using privkey_list and pubkey_list Not sure what privkeys and pubkeys to supply? Use get_input_addresses() to return a list of addresses. Matching those addresses to keys is up to you and how you store your private keys. A future version of this library may handle this for you, but it is not trivial. Note that if spending multisig funds the process is significantly more complicated. Each tx_to_sign must be signed by *each* private key. In a 2-of-3 transaction, two of [privkey1, privkey2, privkey3] must sign each tx_to_sign http://dev.blockcypher.com/#multisig-transactions """ |
assert len(privkey_list) == len(pubkey_list) == len(txs_to_sign)
# in the event of multiple inputs using the same pub/privkey,
# that privkey should be included multiple times
signatures = []
for cnt, tx_to_sign in enumerate(txs_to_sign):
sig = der_encode_sig(*ecdsa_raw_sign(tx_to_sign.rstrip(' \t\r\n\0'), privkey_list[cnt]))
err_msg = 'Bad Signature: sig %s for tx %s with pubkey %s' % (
sig,
tx_to_sign,
pubkey_list[cnt],
)
assert ecdsa_raw_verify(tx_to_sign, der_decode_sig(sig), pubkey_list[cnt]), err_msg
signatures.append(sig)
return signatures |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def broadcast_signed_transaction(unsigned_tx, signatures, pubkeys, coin_symbol='btc', api_key=None):
'''
Broadcasts the transaction from create_unsigned_tx
'''
assert 'errors' not in unsigned_tx, unsigned_tx
assert api_key, 'api_key required'
url = make_url(coin_symbol, **dict(txs='send'))
data = unsigned_tx.copy()
data['signatures'] = signatures
data['pubkeys'] = pubkeys
params = {'token': api_key}
r = requests.post(url, params=params, json=data, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
if response_dict.get('tx') and response_dict.get('received'):
response_dict['tx']['received'] = parser.parse(response_dict['tx']['received'])
return response_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 simple_spend(from_privkey, to_address, to_satoshis, change_address=None,
privkey_is_compressed=True, min_confirmations=0, api_key=None, coin_symbol='btc'):
'''
Simple method to spend from one single-key address to another.
Signature takes place locally (client-side) after unsigned transaction is verified.
Returns the tx_hash of the newly broadcast tx.
If no change_address specified, change will be sent back to sender address.
Note that this violates the best practice.
To sweep, set to_satoshis=-1
Compressed public keys (and their corresponding addresses) have been the standard since v0.6,
set privkey_is_compressed=False if using uncompressed addresses.
Note that this currently only supports spending from single key addresses.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert isinstance(to_satoshis, int), to_satoshis
assert api_key, 'api_key required'
if privkey_is_compressed:
from_pubkey = compress(privkey_to_pubkey(from_privkey))
else:
from_pubkey = privkey_to_pubkey(from_privkey)
from_address = pubkey_to_address(
pubkey=from_pubkey,
# this method only supports paying from pubkey anyway
magicbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_pubkey'],
)
inputs = [{'address': from_address}, ]
logger.info('inputs: %s' % inputs)
outputs = [{'address': to_address, 'value': to_satoshis}, ]
logger.info('outputs: %s' % outputs)
# will fail loudly if tx doesn't verify client-side
unsigned_tx = create_unsigned_tx(
inputs=inputs,
outputs=outputs,
# may build with no change address, but if so will verify change in next step
# done for extra security in case of client-side bug in change address generation
change_address=change_address,
coin_symbol=coin_symbol,
min_confirmations=min_confirmations,
verify_tosigntx=False, # will verify in next step
include_tosigntx=True,
api_key=api_key,
)
logger.info('unsigned_tx: %s' % unsigned_tx)
if 'errors' in unsigned_tx:
print('TX Error(s): Tx NOT Signed or Broadcast')
for error in unsigned_tx['errors']:
print(error['error'])
# Abandon
raise Exception('Build Unsigned TX Error')
if change_address:
change_address_to_use = change_address
else:
change_address_to_use = from_address
tx_is_correct, err_msg = verify_unsigned_tx(
unsigned_tx=unsigned_tx,
inputs=inputs,
outputs=outputs,
sweep_funds=bool(to_satoshis == -1),
change_address=change_address_to_use,
coin_symbol=coin_symbol,
)
if not tx_is_correct:
print(unsigned_tx) # for debug
raise Exception('TX Verification Error: %s' % err_msg)
privkey_list, pubkey_list = [], []
for proposed_input in unsigned_tx['tx']['inputs']:
privkey_list.append(from_privkey)
pubkey_list.append(from_pubkey)
# paying from a single key should only mean one address per input:
assert len(proposed_input['addresses']) == 1, proposed_input['addresses']
# logger.info('privkey_list: %s' % privkey_list)
logger.info('pubkey_list: %s' % pubkey_list)
# sign locally
tx_signatures = make_tx_signatures(
txs_to_sign=unsigned_tx['tosign'],
privkey_list=privkey_list,
pubkey_list=pubkey_list,
)
logger.info('tx_signatures: %s' % tx_signatures)
# broadcast TX
broadcasted_tx = broadcast_signed_transaction(
unsigned_tx=unsigned_tx,
signatures=tx_signatures,
pubkeys=pubkey_list,
coin_symbol=coin_symbol,
api_key=api_key,
)
logger.info('broadcasted_tx: %s' % broadcasted_tx)
if 'errors' in broadcasted_tx:
print('TX Error(s): Tx May NOT Have Been Broadcast')
for error in broadcasted_tx['errors']:
print(error['error'])
print(broadcasted_tx)
return
return broadcasted_tx['tx']['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 get_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
'''
Get metadata using blockcypher's API.
This is data on blockcypher's servers and not embedded into the bitcoin (or other) blockchain.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key or not private, 'Cannot see private metadata without an API key'
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key} if api_key else {'private': 'true'}
r = requests.get(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
response_dict = get_valid_json(r)
return response_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 put_metadata(metadata_dict, address=None, tx_hash=None, block_hash=None, api_key=None, private=True, coin_symbol='btc'):
'''
Embed metadata using blockcypher's API.
This is not embedded into the bitcoin (or other) blockchain,
and is only stored on blockcypher's servers.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key
assert metadata_dict and isinstance(metadata_dict, dict), metadata_dict
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key}
if private:
params['private'] = 'true'
r = requests.put(url, json=metadata_dict, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=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 delete_metadata(address=None, tx_hash=None, block_hash=None, api_key=None, coin_symbol='btc'):
'''
Only available for metadata that was embedded privately.
'''
assert is_valid_coin_symbol(coin_symbol), coin_symbol
assert api_key, 'api_key required'
kwarg = get_valid_metadata_identifier(
coin_symbol=coin_symbol,
address=address,
tx_hash=tx_hash,
block_hash=block_hash,
)
url = make_url(coin_symbol, meta=True, **kwarg)
params = {'token': api_key}
r = requests.delete(url, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
return get_valid_json(r, allow_204=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 to_satoshis(input_quantity, input_type):
''' convert to satoshis, no rounding '''
assert input_type in UNIT_CHOICES, input_type
# convert to satoshis
if input_type in ('btc', 'mbtc', 'bit'):
satoshis = float(input_quantity) * float(UNIT_MAPPINGS[input_type]['satoshis_per'])
elif input_type == 'satoshi':
satoshis = input_quantity
else:
raise Exception('Invalid Unit Choice: %s' % input_type)
return int(satoshis) |
<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_txn_outputs(raw_tx_hex, output_addr_list, coin_symbol):
'''
Used to verify a transaction hex does what's expected of it.
Must supply a list of output addresses so that the library can try to
convert from script to address using both pubkey and script.
Returns a list of the following form:
[{'value': 12345, 'address': '1abc...'}, ...]
Uses @vbuterin's decoding methods.
'''
# Defensive checks:
err_msg = 'Library not able to parse %s transactions' % coin_symbol
assert lib_can_deserialize_cs(coin_symbol), err_msg
assert isinstance(output_addr_list, (list, tuple))
for output_addr in output_addr_list:
assert is_valid_address(output_addr), output_addr
output_addr_set = set(output_addr_list) # speed optimization
outputs = []
deserialized_tx = deserialize(str(raw_tx_hex))
for out in deserialized_tx.get('outs', []):
output = {'value': out['value']}
# determine if the address is a pubkey address, script address, or op_return
pubkey_addr = script_to_address(out['script'],
vbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_pubkey'])
script_addr = script_to_address(out['script'],
vbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_script'])
nulldata = out['script'] if out['script'][0:2] == '6a' else None
if pubkey_addr in output_addr_set:
address = pubkey_addr
output['address'] = address
elif script_addr in output_addr_set:
address = script_addr
output['address'] = address
elif nulldata:
output['script'] = nulldata
output['script_type'] = 'null-data'
else:
raise Exception('Script %s Does Not Contain a Valid Output Address: %s' % (
out['script'],
output_addr_set,
))
outputs.append(output)
return outputs |
<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_blockcypher_walletname_from_mpub(mpub, subchain_indices=[]):
'''
Blockcypher limits wallet names to 25 chars.
Hash the master pubkey (with subchain indexes) and take the first 25 chars.
Hackey determinstic method for naming.
'''
# http://stackoverflow.com/a/19877309/1754586
mpub = mpub.encode('utf-8')
if subchain_indices:
mpub += ','.join([str(x) for x in subchain_indices]).encode('utf-8')
return 'X%s' % sha256(mpub).hexdigest()[:24] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crl(self):
""" Returns up to date CRL of this CA """ |
revoked_certs = self.get_revoked_certs()
crl = crypto.CRL()
now_str = timezone.now().strftime(generalized_time)
for cert in revoked_certs:
revoked = crypto.Revoked()
revoked.set_serial(bytes_compat(cert.serial_number))
revoked.set_reason(b'unspecified')
revoked.set_rev_date(bytes_compat(now_str))
crl.add_revoked(revoked)
return crl.export(self.x509, self.pkey, days=1, digest=b'sha256') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crl(request, pk):
""" returns CRL of a CA """ |
authenticated = request.user.is_authenticated
authenticated = authenticated() if callable(authenticated) else authenticated
if app_settings.CRL_PROTECTED and not authenticated:
return HttpResponse(_('Forbidden'),
status=403,
content_type='text/plain')
ca = crl.ca_model.objects.get(pk=pk)
return HttpResponse(ca.crl,
status=200,
content_type='application/x-pem-file') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def font_list(text="test", test=False):
""" Print all fonts. :param text : input text :type text : str :param test: test flag :type test: bool :return: None """ |
fonts = set(FONT_MAP.keys())
if test:
fonts = fonts - set(TEST_FILTERED_FONTS)
for item in sorted(list(fonts)):
print(str(item) + " : ")
text_temp = text
try:
tprint(text_temp, str(item))
except Exception:
print(FONT_ENVIRONMENT_WARNING) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def art_list(test=False):
""" Print all 1-Line arts. :param test : exception test flag :type test : bool :return: None """ |
for i in sorted(list(art_dic.keys())):
try:
if test:
raise Exception
print(i)
aprint(i)
line()
except Exception:
print(ART_ENVIRONMENT_WARNING)
line()
if test:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def help_func():
""" Print help page. :return: None """ |
tprint("art")
tprint("v" + VERSION)
print(DESCRIPTION + "\n")
print("Webpage : http://art.shaghighi.ir\n")
print("Help : \n")
print(" - list --> (list of arts)\n")
print(" - fonts --> (list of fonts)\n")
print(" - test --> (run tests)\n")
print(" - text 'yourtext' 'font(optional)' --> (text art) Example : 'python -m art text exampletext block'\n")
print(" - shape 'shapename' --> (shape art) Example : 'python -m art shape butterfly'\n")
print(" - save 'yourtext' 'font(optional)' --> Example : 'python -m art save exampletext block'\n")
print(" - all 'yourtext' --> Example : 'python -m art all exampletext'") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aprint(artname, number=1, text=""):
""" Print 1-line art. :param artname: artname :type artname : str :return: None """ |
print(art(artname=artname, number=number, text=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 art(artname, number=1, text=""):
""" Return 1-line art. :param artname: artname :type artname : str :return: ascii art as str """ |
if isinstance(artname, str) is False:
raise artError(ART_TYPE_ERROR)
artname = artname.lower()
arts = sorted(art_dic.keys())
if artname == "random" or artname == "rand" or artname == "rnd":
filtered_arts = list(set(arts) - set(RANDOM_FILTERED_ARTS))
artname = random.choice(filtered_arts)
elif artname not in art_dic.keys():
distance_list = list(map(lambda x: distance_calc(artname, x),
arts))
min_distance = min(distance_list)
selected_art = arts[distance_list.index(min_distance)]
threshold = max(len(artname), len(selected_art)) / 2
if min_distance < threshold:
artname = selected_art
else:
raise artError(ART_NAME_ERROR)
art_value = art_dic[artname]
if isinstance(number, int) is False:
raise artError(NUMBER_TYPE_ERROR)
if isinstance(art_value, str):
return (art_value + " ") * number
if isinstance(text, str) is False:
raise artError(TEXT_TYPE_ERROR)
return (art_value[0] + text + art_value[1] + " ") * number |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distance_calc(s1, s2):
""" Calculate Levenshtein distance between two words. :param s1: first word :type s1 : str :param s2: second word :type s2 : str :return: distance between two word References : 1- https://stackoverflow.com/questions/2460177/edit-distance-in-python 2- https://en.wikipedia.org/wiki/Levenshtein_distance """ |
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2 + 1]
for i1, c1 in enumerate(s1):
if c1 == c2:
distances_.append(distances[i1])
else:
distances_.append(
1 + min((distances[i1], distances[i1 + 1], distances_[-1])))
distances = distances_
return distances[-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 wizard_font(text):
""" Check input text length for wizard mode. :param text: input text :type text:str :return: font as str """ |
text_length = len(text)
if text_length <= TEXT_XLARGE_THRESHOLD:
font = random.choice(XLARGE_WIZARD_FONT)
elif text_length > TEXT_XLARGE_THRESHOLD and text_length <= TEXT_LARGE_THRESHOLD:
font = random.choice(LARGE_WIZARD_FONT)
elif text_length > TEXT_LARGE_THRESHOLD and text_length <= TEXT_MEDIUM_THRESHOLD:
font = random.choice(MEDIUM_WIZARD_FONT)
else:
font = random.choice(SMALL_WIZARD_FONT)
return font |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indirect_font(font, fonts, text):
""" Check input font for indirect modes. :param font: input font :type font : str :param fonts: fonts list :type fonts : list :param text: input text :type text:str :return: font as str """ |
if font == "rnd-small" or font == "random-small" or font == "rand-small":
font = random.choice(RND_SIZE_DICT["small_list"])
return font
if font == "rnd-medium" or font == "random-medium" or font == "rand-medium":
font = random.choice(RND_SIZE_DICT["medium_list"])
return font
if font == "rnd-large" or font == "random-large" or font == "rand-large":
font = random.choice(RND_SIZE_DICT["large_list"])
return font
if font == "rnd-xlarge" or font == "random-xlarge" or font == "rand-xlarge":
font = random.choice(RND_SIZE_DICT["xlarge_list"])
return font
if font == "random" or font == "rand" or font == "rnd":
filtered_fonts = list(set(fonts) - set(RANDOM_FILTERED_FONTS))
font = random.choice(filtered_fonts)
return font
if font == "wizard" or font == "wiz" or font == "magic":
font = wizard_font(text)
return font
if font == "rnd-na" or font == "random-na" or font == "rand-na":
font = random.choice(TEST_FILTERED_FONTS)
return font
if font not in FONT_MAP.keys():
distance_list = list(map(lambda x: distance_calc(font, x), fonts))
font = fonts[distance_list.index(min(distance_list))]
return font |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __word2art(word, font, chr_ignore, letters):
""" Return art word. :param word: input word :type word: str :param font: input font :type font: str :param chr_ignore: ignore not supported character :type chr_ignore: bool :param letters: font letters table :type letters: dict :return: ascii art as str """ |
split_list = []
result_list = []
splitter = "\n"
for i in word:
if (ord(i) == 9) or (ord(i) == 32 and font == "block"):
continue
if (i not in letters.keys()):
if (chr_ignore):
continue
else:
raise artError(str(i) + " is invalid.")
if len(letters[i]) == 0:
continue
split_list.append(letters[i].split("\n"))
if font in ["mirror", "mirror_flip"]:
split_list.reverse()
if len(split_list) == 0:
return ""
for i in range(len(split_list[0])):
temp = ""
for j in range(len(split_list)):
if j > 0 and (
i == 1 or i == len(
split_list[0]) -
2) and font == "block":
temp = temp + " "
temp = temp + split_list[j][i]
result_list.append(temp)
if "win32" != sys.platform:
splitter = "\r\n"
result = (splitter).join(result_list)
if result[-1] != "\n":
result += splitter
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 set_default(font=DEFAULT_FONT, chr_ignore=True, filename="art", print_status=True):
""" Change text2art, tprint and tsave default values. :param font: input font :type font:str :param chr_ignore: ignore not supported character :type chr_ignore:bool :param filename: output file name (only tsave) :type filename:str :param print_status : save message print flag (only tsave) :type print_status:bool :return: None """ |
if isinstance(font, str) is False:
raise artError(FONT_TYPE_ERROR)
if isinstance(chr_ignore, bool) is False:
raise artError(CHR_IGNORE_TYPE_ERROR)
if isinstance(filename, str) is False:
raise artError(FILE_TYPE_ERROR)
if isinstance(print_status, bool) is False:
raise artError(PRINT_STATUS_TYPE_ERROR)
tprint.__defaults__ = (font, chr_ignore)
tsave.__defaults__ = (font, filename, chr_ignore, print_status)
text2art.__defaults__ = (font, chr_ignore) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def objectgetter(model, attr_name='pk', field_name='pk'):
""" Helper that returns a function suitable for use as the ``fn`` argument to the ``permission_required`` decorator. Internally uses ``get_object_or_404``, so keep in mind that this may raise ``Http404``. ``model`` can be a model class, manager or queryset. ``attr_name`` is the name of the view attribute. ``field_name`` is the model's field name by which the lookup is made, eg. "id", "slug", etc. """ |
def _getter(request, *view_args, **view_kwargs):
if attr_name not in view_kwargs:
raise ImproperlyConfigured(
'Argument {0} is not available. Given arguments: [{1}]'
.format(attr_name, ', '.join(view_kwargs.keys())))
try:
return get_object_or_404(model, **{field_name: view_kwargs[attr_name]})
except FieldError:
raise ImproperlyConfigured(
'Model {0} has no field named {1}'
.format(model, field_name))
return _getter |
<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_base_dir(self, base_dir):
""" Set the base directory to be used for all relative filenames. """ |
self._base_dir = base_dir
self.icon_cache.set_base_dir(base_dir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_alignment(alignment):
""" Convert a C++ alignment to the corresponding flags. """ |
align_flags = None
for qt_align in alignment.split('|'):
_, qt_align = qt_align.split('::')
align = getattr(QtCore.Qt, qt_align)
if align_flags is None:
align_flags = align
else:
align_flags |= align
return align_flags |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def any_i18n(*args):
""" Return True if any argument appears to be an i18n string. """ |
for a in args:
if a is not None and not isinstance(a, str):
return True
return 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 createWidgetItem(self, item_type, elem, getter, *getter_args):
""" Create a specific type of widget item. """ |
item = self.factory.createQObject(item_type, "item", (), False)
props = self.wprops
# Note that not all types of widget items support the full set of
# properties.
text = props.getProperty(elem, 'text')
status_tip = props.getProperty(elem, 'statusTip')
tool_tip = props.getProperty(elem, 'toolTip')
whats_this = props.getProperty(elem, 'whatsThis')
if self.any_i18n(text, status_tip, tool_tip, whats_this):
self.factory.invoke("item", getter, getter_args)
if text:
item.setText(text)
if status_tip:
item.setStatusTip(status_tip)
if tool_tip:
item.setToolTip(tool_tip)
if whats_this:
item.setWhatsThis(whats_this)
text_alignment = props.getProperty(elem, 'textAlignment')
if text_alignment:
item.setTextAlignment(text_alignment)
font = props.getProperty(elem, 'font')
if font:
item.setFont(font)
icon = props.getProperty(elem, 'icon')
if icon:
item.setIcon(icon)
background = props.getProperty(elem, 'background')
if background:
item.setBackground(background)
foreground = props.getProperty(elem, 'foreground')
if foreground:
item.setForeground(foreground)
flags = props.getProperty(elem, 'flags')
if flags:
item.setFlags(flags)
check_state = props.getProperty(elem, 'checkState')
if check_state:
item.setCheckState(check_state)
return 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 readResources(self, elem):
""" Read a "resources" tag and add the module to import to the parser's list of them. """ |
try:
iterator = getattr(elem, 'iter')
except AttributeError:
iterator = getattr(elem, 'getiterator')
for include in iterator("include"):
loc = include.attrib.get("location")
# Apply the convention for naming the Python files generated by
# pyrcc5.
if loc and loc.endswith('.qrc'):
mname = os.path.basename(loc[:-4] + self._resource_suffix)
if mname not in self.resources:
self.resources.append(mname) |
<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_icon(self, iconset):
"""Return an icon described by the given iconset tag.""" |
# Handle a themed icon.
theme = iconset.attrib.get('theme')
if theme is not None:
return self._object_factory.createQObject("QIcon.fromTheme",
'icon', (self._object_factory.asString(theme), ),
is_attribute=False)
# Handle an empty iconset property.
if iconset.text is None:
return None
iset = _IconSet(iconset, self._base_dir)
try:
idx = self._cache.index(iset)
except ValueError:
idx = -1
if idx >= 0:
# Return the icon from the cache.
iset = self._cache[idx]
else:
# Follow uic's naming convention.
name = 'icon'
idx = len(self._cache)
if idx > 0:
name += str(idx)
icon = self._object_factory.createQObject("QIcon", name, (),
is_attribute=False)
iset.set_icon(icon, self._qtgui_module)
self._cache.append(iset)
return iset.icon |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _file_name(fname, base_dir):
""" Convert a relative filename if we have a base directory. """ |
fname = fname.replace("\\", "\\\\")
if base_dir != '' and fname[0] != ':' and not os.path.isabs(fname):
fname = os.path.join(base_dir, fname)
return fname |
<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_icon(self, icon, qtgui_module):
"""Save the icon and set its attributes.""" |
if self._use_fallback:
icon.addFile(self._fallback)
else:
for role, pixmap in self._roles.items():
if role.endswith("off"):
mode = role[:-3]
state = qtgui_module.QIcon.Off
elif role.endswith("on"):
mode = role[:-2]
state = qtgui_module.QIcon.On
else:
continue
mode = getattr(qtgui_module.QIcon, mode.title())
if pixmap:
icon.addPixmap(qtgui_module.QPixmap(pixmap), mode, state)
else:
icon.addPixmap(qtgui_module.QPixmap(), mode, state)
self.icon = icon |
<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_package_data():
"""Include all files from all sub-directories""" |
package_data = dict()
package_data['PyQt5'] = list()
for subdir in ("doc/", "examples/", "include/",
"mkspecs/", "plugins/", "qml/",
"qsci/", "sip/", "translations/", "uic/"):
abspath = os.path.abspath("PyQt5/" + subdir)
for root, dirs, files in os.walk(abspath):
for f in files:
fpath = os.path.join(root, f)
relpath = os.path.relpath(fpath, abspath)
relpath = relpath.replace("\\", "/")
package_data['PyQt5'].append(subdir + relpath)
package_data['PyQt5'].extend(["*.exe",
"*.dll",
"*.pyd",
"*.conf",
"*.api",
"*.qm",
"*.bat"])
return package_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 _preview(self):
""" Preview the .ui file. Return the exit status to be passed back to the parent process. """ |
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([self._ui_file])
widget = loadUi(self._ui_file)
widget.show()
return app.exec_() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate(self):
""" Generate the Python code. """ |
needs_close = False
if sys.hexversion >= 0x03000000:
if self._opts.output == '-':
from io import TextIOWrapper
pyfile = TextIOWrapper(sys.stdout.buffer, encoding='utf8')
else:
pyfile = open(self._opts.output, 'wt', encoding='utf8')
needs_close = True
else:
if self._opts.output == '-':
pyfile = sys.stdout
else:
pyfile = open(self._opts.output, 'wt')
needs_close = True
import_from = self._opts.import_from
if import_from:
from_imports = True
elif self._opts.from_imports:
from_imports = True
import_from = '.'
else:
from_imports = False
compileUi(self._ui_file, pyfile, self._opts.execute, self._opts.indent,
from_imports, self._opts.resource_suffix, import_from)
if needs_close:
pyfile.close() |
<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_IOError(self, e):
""" Handle an IOError exception. """ |
sys.stderr.write("Error: %s: \"%s\"\n" % (e.strerror, e.filename)) |
<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_plugin(filename, plugin_globals, plugin_locals):
""" Load the plugin from the given file. Return True if the plugin was loaded, or False if it wanted to be ignored. Raise an exception if there was an error. """ |
plugin = open(filename, 'rU')
try:
exec(plugin.read(), plugin_globals, plugin_locals)
except ImportError:
return False
except Exception as e:
raise WidgetPluginError("%s: %s" % (e.__class__, str(e)))
finally:
plugin.close()
return 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 _initSymbols(ptc):
""" Initialize symbols and single character constants. """ |
# build am and pm lists to contain
# original case, lowercase, first-char and dotted
# versions of the meridian text
ptc.am = ['', '']
ptc.pm = ['', '']
for idx, xm in enumerate(ptc.locale.meridian[:2]):
# 0: am
# 1: pm
target = ['am', 'pm'][idx]
setattr(ptc, target, [xm])
target = getattr(ptc, target)
if xm:
lxm = xm.lower()
target.extend((xm[0], '{0}.{1}.'.format(*xm),
lxm, lxm[0], '{0}.{1}.'.format(*lxm))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _convertUnitAsWords(self, unitText):
""" Converts text units into their number value. @type unitText: string @param unitText: number text to convert @rtype: integer @return: numerical value of unitText """ |
word_list, a, b = re.split(r"[,\s-]+", unitText), 0, 0
for word in word_list:
x = self.ptc.small.get(word)
if x is not None:
a += x
elif word == "hundred":
a *= 100
else:
x = self.ptc.magnitude.get(word)
if x is not None:
b += a * x
a = 0
elif word in self.ptc.ignore:
pass
else:
raise Exception("Unknown number: " + word)
return a + b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _quantityToReal(self, quantity):
""" Convert a quantity, either spelled-out or numeric, to a float @type quantity: string @param quantity: quantity to parse to float @rtype: int @return: the quantity as an float, defaulting to 0.0 """ |
if not quantity:
return 1.0
try:
return float(quantity.replace(',', '.'))
except ValueError:
pass
try:
return float(self.ptc.numbers[quantity])
except KeyError:
pass
return 0.0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _evalDT(self, datetimeString, sourceTime):
""" Calculate the datetime from known format like RFC822 or W3CDTF Examples handled:: RFC822, W3CDTF formatted dates HH:MM[:SS][ am/pm] MM/DD/YYYY DD MMMM YYYY @type datetimeString: string @param datetimeString: text to try and parse as more "traditional" date/time text @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base @rtype: datetime @return: calculated C{struct_time} value or current C{struct_time} if not parsed """ |
ctx = self.currentContext
s = datetimeString.strip()
# Given string date is a RFC822 date
if sourceTime is None:
sourceTime = _parse_date_rfc822(s)
debug and log.debug(
'attempt to parse as rfc822 - %s', str(sourceTime))
if sourceTime is not None:
(yr, mth, dy, hr, mn, sec, wd, yd, isdst, _) = sourceTime
ctx.updateAccuracy(ctx.ACU_YEAR, ctx.ACU_MONTH, ctx.ACU_DAY)
if hr != 0 and mn != 0 and sec != 0:
ctx.updateAccuracy(ctx.ACU_HOUR, ctx.ACU_MIN, ctx.ACU_SEC)
sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
# Given string date is a W3CDTF date
if sourceTime is None:
sourceTime = _parse_date_w3dtf(s)
if sourceTime is not None:
ctx.updateAccuracy(ctx.ACU_YEAR, ctx.ACU_MONTH, ctx.ACU_DAY,
ctx.ACU_HOUR, ctx.ACU_MIN, ctx.ACU_SEC)
if sourceTime is None:
sourceTime = time.localtime()
return sourceTime |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updateAccuracy(self, *accuracy):
""" Updates current accuracy flag """ |
for acc in accuracy:
if not isinstance(acc, int):
acc = self._ACCURACY_REVERSE_MAPPING[acc]
self.accuracy |= acc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indent(func):
""" Decorator for allowing to use method as normal method or with context manager for auto-indenting code blocks. """ |
def wrapper(self, *args, **kwds):
func(self, *args, **kwds)
return Indent(self)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_scope(self, scope: str):
"""
Context manager to handle current scope.
""" |
old_scope = self.resolution_scope
self.resolution_scope = urlparse.urljoin(old_scope, scope)
try:
yield
finally:
self.resolution_scope = old_scope |
<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_scope_name(self):
"""
Get current scope and return it as a valid function name.
""" |
name = 'validate_' + unquote(self.resolution_scope).replace('~1', '_').replace('~0', '_')
name = re.sub(r'[:/#\.\-\%]', '_', name)
name = name.lower().rstrip('_')
return 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 generate_type(self):
""" Validation of type. Can be one type or list of types. Since draft 06 a float without fractional part is an integer. .. code-block:: python {'type': 'string'} {'type': ['string', 'number']} """ |
types = enforce_list(self._definition['type'])
try:
python_types = ', '.join(JSON_TYPE_TO_PYTHON_TYPE[t] for t in types)
except KeyError as exc:
raise JsonSchemaDefinitionException('Unknown type: {}'.format(exc))
extra = ''
if 'integer' in types:
extra += ' and not (isinstance({variable}, float) and {variable}.is_integer())'.format(
variable=self._variable,
)
if ('number' in types or 'integer' in types) and 'boolean' not in types:
extra += ' or isinstance({variable}, bool)'.format(variable=self._variable)
with self.l('if not isinstance({variable}, ({})){}:', python_types, extra):
self.l('raise JsonSchemaException("{name} must be {}")', ' or '.join(types)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_property_names(self):
""" Means that keys of object must to follow this definition. .. code-block:: python { 'propertyNames': { 'maxLength': 3, }, } """ |
property_names_definition = self._definition.get('propertyNames', {})
if property_names_definition is True:
pass
elif property_names_definition is False:
self.create_variable_keys()
with self.l('if {variable}_keys:'):
self.l('raise JsonSchemaException("{name} must not be there")')
else:
self.create_variable_is_dict()
with self.l('if {variable}_is_dict:'):
self.create_variable_with_length()
with self.l('if {variable}_len != 0:'):
self.l('{variable}_property_names = True')
with self.l('for {variable}_key in {variable}:'):
with self.l('try:'):
self.generate_func_code_block(
property_names_definition,
'{}_key'.format(self._variable),
self._variable_name,
clear_variables=True,
)
with self.l('except JsonSchemaException:'):
self.l('{variable}_property_names = False')
with self.l('if not {variable}_property_names:'):
self.l('raise JsonSchemaException("{name} must be named by propertyName definition")') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_contains(self):
""" Means that array must contain at least one defined item. .. code-block:: python { 'contains': { 'type': 'number', }, } Valid array is any with at least one number. """ |
self.create_variable_is_list()
with self.l('if {variable}_is_list:'):
contains_definition = self._definition['contains']
if contains_definition is False:
self.l('raise JsonSchemaException("{name} is always invalid")')
elif contains_definition is True:
with self.l('if not {variable}:'):
self.l('raise JsonSchemaException("{name} must not be empty")')
else:
self.l('{variable}_contains = False')
with self.l('for {variable}_key in {variable}:'):
with self.l('try:'):
self.generate_func_code_block(
contains_definition,
'{}_key'.format(self._variable),
self._variable_name,
clear_variables=True,
)
self.l('{variable}_contains = True')
self.l('break')
self.l('except JsonSchemaException: pass')
with self.l('if not {variable}_contains:'):
self.l('raise JsonSchemaException("{name} must contain one of contains definition")') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_const(self):
""" Means that value is valid when is equeal to const definition. .. code-block:: python { 'const': 42, } Only valid value is 42 in this example. """ |
const = self._definition['const']
if isinstance(const, str):
const = '"{}"'.format(const)
with self.l('if {variable} != {}:', const):
self.l('raise JsonSchemaException("{name} must be same as const definition")') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def global_state(self):
""" Returns global variables for generating function from ``func_code``. Includes compiled regular expressions and imports, so it does not have to do it every time when validation function is called. """ |
self._generate_func_code()
return dict(
REGEX_PATTERNS=self._compile_regexps,
re=re,
JsonSchemaException=JsonSchemaException,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def global_state_code(self):
""" Returns global variables for generating function from ``func_code`` as code. Includes compiled regular expressions and imports. """ |
self._generate_func_code()
if not self._compile_regexps:
return '\n'.join(
[
'from fastjsonschema import JsonSchemaException',
'',
'',
]
)
regexs = ['"{}": re.compile(r"{}")'.format(key, value.pattern) for key, value in self._compile_regexps.items()]
return '\n'.join(
[
'import re',
'from fastjsonschema import JsonSchemaException',
'',
'',
'REGEX_PATTERNS = {',
' ' + ',\n '.join(regexs),
'}',
'',
]
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_func_code(self):
""" Creates base code of validation function and calls helper for creating code by definition. """ |
self.l('NoneType = type(None)')
# Generate parts that are referenced and not yet generated
while self._needed_validation_functions:
# During generation of validation function, could be needed to generate
# new one that is added again to `_needed_validation_functions`.
# Therefore usage of while instead of for loop.
uri, name = self._needed_validation_functions.popitem()
self.generate_validation_function(uri, 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 generate_validation_function(self, uri, name):
""" Generate validation function for given uri with given name """ |
self._validation_functions_done.add(uri)
self.l('')
with self._resolver.resolving(uri) as definition:
with self.l('def {}(data):', name):
self.generate_func_code_block(definition, 'data', 'data', clear_variables=True)
self.l('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 generate_func_code_block(self, definition, variable, variable_name, clear_variables=False):
""" Creates validation rules for current definition. """ |
backup = self._definition, self._variable, self._variable_name
self._definition, self._variable, self._variable_name = definition, variable, variable_name
if clear_variables:
backup_variables = self._variables
self._variables = set()
self._generate_func_code_block(definition)
self._definition, self._variable, self._variable_name = backup
if clear_variables:
self._variables = backup_variables |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_ref(self):
""" Ref can be link to remote or local definition. .. code-block:: python {'$ref': 'http://json-schema.org/draft-04/schema#'} { 'properties': { 'foo': {'type': 'integer'}, 'bar': {'$ref': '#/properties/foo'} } } """ |
with self._resolver.in_scope(self._definition['$ref']):
name = self._resolver.get_scope_name()
uri = self._resolver.get_uri()
if uri not in self._validation_functions_done:
self._needed_validation_functions[uri] = name
# call validation function
self.l('{}({variable})', 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 generate_if_then_else(self):
""" Implementation of if-then-else. .. code-block:: python { 'if': { 'exclusiveMaximum': 0, }, 'then': { 'minimum': -10, }, 'else': { 'multipleOf': 2, }, } Valid values are any between -10 and 0 or any multiplication of two. """ |
with self.l('try:'):
self.generate_func_code_block(
self._definition['if'],
self._variable,
self._variable_name,
clear_variables=True
)
with self.l('except JsonSchemaException:'):
if 'else' in self._definition:
self.generate_func_code_block(
self._definition['else'],
self._variable,
self._variable_name,
clear_variables=True
)
else:
self.l('pass')
if 'then' in self._definition:
with self.l('else:'):
self.generate_func_code_block(
self._definition['then'],
self._variable,
self._variable_name,
clear_variables=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 generate_content_encoding(self):
""" Means decoding value when it's encoded by base64. .. code-block:: python { 'contentEncoding': 'base64', } """ |
if self._definition['contentEncoding'] == 'base64':
with self.l('if isinstance({variable}, str):'):
with self.l('try:'):
self.l('import base64')
self.l('{variable} = base64.b64decode({variable})')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must be encoded by base64")')
with self.l('if {variable} == "":'):
self.l('raise JsonSchemaException("contentEncoding must be base64")') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_content_media_type(self):
""" Means loading value when it's specified as JSON. .. code-block:: python { 'contentMediaType': 'application/json', } """ |
if self._definition['contentMediaType'] == 'application/json':
with self.l('if isinstance({variable}, bytes):'):
with self.l('try:'):
self.l('{variable} = {variable}.decode("utf-8")')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must encoded by utf8")')
with self.l('if isinstance({variable}, str):'):
with self.l('try:'):
self.l('import json')
self.l('{variable} = json.loads({variable})')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must be valid JSON")') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_enum(self):
""" Means that only value specified in the enum is valid. .. code-block:: python { 'enum': ['a', 'b'], } """ |
enum = self._definition['enum']
if not isinstance(enum, (list, tuple)):
raise JsonSchemaDefinitionException('enum must be an array')
with self.l('if {variable} not in {enum}:'):
enum = str(enum).replace('"', '\\"')
self.l('raise JsonSchemaException("{name} must be one of {}")', enum) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_all_of(self):
""" Means that value have to be valid by all of those definitions. It's like put it in one big definition. .. code-block:: python { 'allOf': [ {'type': 'number'}, {'minimum': 5}, ], } """ |
for definition_item in self._definition['allOf']:
self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=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 generate_one_of(self):
""" Means that value have to be valid by only one of those definitions. It can't be valid by two or more of them. .. code-block:: python { 'oneOf': [ {'type': 'number', 'multipleOf': 3}, {'type': 'number', 'multipleOf': 5}, ], } """ |
self.l('{variable}_one_of_count = 0')
for definition_item in self._definition['oneOf']:
# When we know it's failing (one of means exactly once), we do not need to do another expensive try-except.
with self.l('if {variable}_one_of_count < 2:'):
with self.l('try:'):
self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True)
self.l('{variable}_one_of_count += 1')
self.l('except JsonSchemaException: pass')
with self.l('if {variable}_one_of_count != 1:'):
self.l('raise JsonSchemaException("{name} must be valid exactly by one of oneOf definition")') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_not(self):
""" Means that value have not to be valid by this definition. .. code-block:: python {'not': {'type': 'null'}} Since draft 06 definition can be boolean. False means nothing, True means everything is invalid. """ |
not_definition = self._definition['not']
if not_definition is True:
self.l('raise JsonSchemaException("{name} must not be there")')
elif not_definition is False:
return
elif not not_definition:
with self.l('if {}:', self._variable):
self.l('raise JsonSchemaException("{name} must not be valid by not definition")')
else:
with self.l('try:'):
self.generate_func_code_block(not_definition, self._variable, self._variable_name)
self.l('except JsonSchemaException: pass')
self.l('else: raise JsonSchemaException("{name} must not be valid by not definition")') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_format(self):
""" Means that value have to be in specified format. For example date, email or other. .. code-block:: python {'format': 'email'} Valid value for this definition is user@example.com but not @username """ |
with self.l('if isinstance({variable}, str):'):
format_ = self._definition['format']
if format_ in self.FORMAT_REGEXS:
format_regex = self.FORMAT_REGEXS[format_]
self._generate_format(format_, format_ + '_re_pattern', format_regex)
# format regex is used only in meta schemas
elif format_ == 'regex':
with self.l('try:'):
self.l('re.compile({variable})')
with self.l('except Exception:'):
self.l('raise JsonSchemaException("{name} must be a valid regex")')
else:
self.l('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 generate_items(self):
""" Means array is valid only when all items are valid by this definition. .. code-block:: python { 'items': [ {'type': 'integer'}, {'type': 'string'}, ], } Valid arrays are those with integers or strings, nothing else. Since draft 06 definition can be also boolean. True means nothing, False means everything is invalid. """ |
items_definition = self._definition['items']
if items_definition is True:
return
self.create_variable_is_list()
with self.l('if {variable}_is_list:'):
self.create_variable_with_length()
if items_definition is False:
with self.l('if {variable}:'):
self.l('raise JsonSchemaException("{name} must not be there")')
elif isinstance(items_definition, list):
for idx, item_definition in enumerate(items_definition):
with self.l('if {variable}_len > {}:', idx):
self.l('{variable}__{0} = {variable}[{0}]', idx)
self.generate_func_code_block(
item_definition,
'{}__{}'.format(self._variable, idx),
'{}[{}]'.format(self._variable_name, idx),
)
if isinstance(item_definition, dict) and 'default' in item_definition:
self.l('else: {variable}.append({})', repr(item_definition['default']))
if 'additionalItems' in self._definition:
if self._definition['additionalItems'] is False:
self.l('if {variable}_len > {}: raise JsonSchemaException("{name} must contain only specified items")', len(items_definition))
else:
with self.l('for {variable}_x, {variable}_item in enumerate({variable}[{0}:], {0}):', len(items_definition)):
self.generate_func_code_block(
self._definition['additionalItems'],
'{}_item'.format(self._variable),
'{}[{{{}_x}}]'.format(self._variable_name, self._variable),
)
else:
if items_definition:
with self.l('for {variable}_x, {variable}_item in enumerate({variable}):'):
self.generate_func_code_block(
items_definition,
'{}_item'.format(self._variable),
'{}[{{{}_x}}]'.format(self._variable_name, self._variable),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_properties(self):
""" Means object with defined keys. .. code-block:: python { 'properties': { 'key': {'type': 'number'}, }, } Valid object is containing key called 'key' and value any number. """ |
self.create_variable_is_dict()
with self.l('if {variable}_is_dict:'):
self.create_variable_keys()
for key, prop_definition in self._definition['properties'].items():
key_name = re.sub(r'($[^a-zA-Z]|[^a-zA-Z0-9])', '', key)
with self.l('if "{}" in {variable}_keys:', key):
self.l('{variable}_keys.remove("{}")', key)
self.l('{variable}__{0} = {variable}["{1}"]', key_name, key)
self.generate_func_code_block(
prop_definition,
'{}__{}'.format(self._variable, key_name),
'{}.{}'.format(self._variable_name, key),
)
if isinstance(prop_definition, dict) and 'default' in prop_definition:
self.l('else: {variable}["{}"] = {}', key, repr(prop_definition['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 generate_pattern_properties(self):
""" Means object with defined keys as patterns. .. code-block:: python { 'patternProperties': { '^x': {'type': 'number'}, }, } Valid object is containing key starting with a 'x' and value any number. """ |
self.create_variable_is_dict()
with self.l('if {variable}_is_dict:'):
self.create_variable_keys()
for pattern, definition in self._definition['patternProperties'].items():
self._compile_regexps[pattern] = re.compile(pattern)
with self.l('for {variable}_key, {variable}_val in {variable}.items():'):
for pattern, definition in self._definition['patternProperties'].items():
with self.l('if REGEX_PATTERNS["{}"].search({variable}_key):', pattern):
with self.l('if {variable}_key in {variable}_keys:'):
self.l('{variable}_keys.remove({variable}_key)')
self.generate_func_code_block(
definition,
'{}_val'.format(self._variable),
'{}.{{{}_key}}'.format(self._variable_name, self._variable),
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_additional_properties(self):
""" Means object with keys with values defined by definition. .. code-block:: python { 'properties': { 'key': {'type': 'number'}, } 'additionalProperties': {'type': 'string'}, } Valid object is containing key called 'key' and it's value any number and any other key with any string. """ |
self.create_variable_is_dict()
with self.l('if {variable}_is_dict:'):
self.create_variable_keys()
add_prop_definition = self._definition["additionalProperties"]
if add_prop_definition:
properties_keys = list(self._definition.get("properties", {}).keys())
with self.l('for {variable}_key in {variable}_keys:'):
with self.l('if {variable}_key not in {}:', properties_keys):
self.l('{variable}_value = {variable}.get({variable}_key)')
self.generate_func_code_block(
add_prop_definition,
'{}_value'.format(self._variable),
'{}.{{{}_key}}'.format(self._variable_name, self._variable),
)
else:
with self.l('if {variable}_keys:'):
self.l('raise JsonSchemaException("{name} must contain only specified properties")') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_dependencies(self):
""" Means when object has property, it needs to have also other property. .. code-block:: python { 'dependencies': { 'bar': ['foo'], }, } Valid object is containing only foo, both bar and foo or none of them, but not object with only bar. Since draft 06 definition can be boolean or empty array. True and empty array means nothing, False means that key cannot be there at all. """ |
self.create_variable_is_dict()
with self.l('if {variable}_is_dict:'):
self.create_variable_keys()
for key, values in self._definition["dependencies"].items():
if values == [] or values is True:
continue
with self.l('if "{}" in {variable}_keys:', key):
if values is False:
self.l('raise JsonSchemaException("{} in {name} must not be there")', key)
elif isinstance(values, list):
for value in values:
with self.l('if "{}" not in {variable}_keys:', value):
self.l('raise JsonSchemaException("{name} missing dependency {} for {}")', value, key)
else:
self.generate_func_code_block(values, self._variable, self._variable_name, clear_variables=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 _read_cmap(self):
""" reads the colormap from a text file given in settings.py. See colormap_cubehelix.txt. File must contain 256 RGB values """ |
try:
i = 0
colormap = {0: (0, 0, 0)}
with open(settings.COLORMAP) as cmap:
lines = cmap.readlines()
for line in lines:
if i == 0 and 'mode = ' in line:
i = 1
maxval = float(line.replace('mode = ', ''))
elif i > 0:
str = line.split()
if str == []: # when there are empty lines at the end of the file
break
colormap.update(
{
i: (int(round(float(str[0]) * 255 / maxval)),
int(round(float(str[1]) * 255 / maxval)),
int(round(float(str[2]) * 255 / maxval)))
}
)
i += 1
except IOError:
pass
self.cmap = {k: v[:4] for k, v in colormap.items()} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Executes NDVI processing """ |
self.output("* NDVI processing started.", normal=True)
bands = self._read_bands()
image_data = self._get_image_data()
new_bands = []
for i in range(0, 2):
new_bands.append(numpy.empty(image_data['shape'], dtype=numpy.float32))
self._warp(image_data, bands, new_bands)
# Bands are no longer needed
del bands
calc_band = numpy.true_divide((new_bands[1] - new_bands[0]), (new_bands[1] + new_bands[0]))
output_band = numpy.rint((calc_band + 1) * 255 / 2).astype(numpy.uint8)
output_file = join(self.dst_path, self._filename(suffix='NDVI'))
return self.write_band(output_band, output_file, image_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 data_collector(iterable, def_buf_size=5242880):
""" Buffers n bytes of data. :param iterable: Could be a list, generator or string :type iterable: List, generator, String :returns: A generator object """ |
buf = b''
for data in iterable:
buf += data
if len(buf) >= def_buf_size:
output = buf[:def_buf_size]
buf = buf[def_buf_size:]
yield output
if len(buf) > 0:
yield buf |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(bucket, aws_access_key, aws_secret_key, iterable, key, progress_cb=None, threads=5, replace=False, secure=True, connection=None):
""" Upload data to s3 using the s3 multipart upload API. :param bucket: Name of the S3 bucket :type bucket: String :param aws_access_key: AWS access key id (optional) :type aws_access_key: String :param aws_secret_key: AWS access secret key (optional) :type aws_secret_key: String :param iterable: The data to upload. Each 'part' in the list. will be uploaded in parallel. Each part must be at least 5242880 bytes (5mb). :type iterable: An iterable object :param key: The name of the key (filename) to create in the s3 bucket :type key: String :param progress_cb: Progress callback, will be called with (part_no, uploaded, total) each time a progress update is available. (optional) :type progress_cb: function :param threads: the number of threads to use while uploading. (Default is 5) :type threads: int :param replace: will replace the key (filename) on S3 if set to true. (Default is false) :type replace: boolean :param secure: Use ssl when talking to s3. (Default is true) :type secure: boolean :param connection: Used for testing (optional) :type connection: S3 connection class :returns: void """ |
if not connection:
from boto.s3.connection import S3Connection as connection
c = connection(aws_access_key, aws_secret_key, is_secure=secure)
else:
c = connection
b = c.get_bucket(bucket)
if not replace and b.lookup(key):
raise Exception('s3 key ' + key + ' already exists')
multipart_obj = b.initiate_multipart_upload(key)
err_queue = queue.Queue()
lock = threading.Lock()
upload.counter = 0
try:
tpool = pool.ThreadPool(processes=threads)
def check_errors():
try:
exc = err_queue.get(block=False)
except queue.Empty:
pass
else:
raise exc
def waiter():
while upload.counter >= threads:
check_errors()
time.sleep(0.1)
def cb(err):
if err:
err_queue.put(err)
with lock:
upload.counter -= 1
args = [multipart_obj.upload_part_from_file, progress_cb]
for part_no, part in enumerate(iterable):
part_no += 1
tpool.apply_async(upload_part, args + [part_no, part], callback=cb)
with lock:
upload.counter += 1
waiter()
tpool.close()
tpool.join()
# Check for thread errors before completing the upload,
# sometimes an error can be left unchecked until we
# get to this point.
check_errors()
multipart_obj.complete_upload()
except:
multipart_obj.cancel_upload()
tpool.terminate()
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, bucket_name, filename, path):
""" Initiate the upload. :param bucket_name: Name of the S3 bucket :type bucket_name: String :param filename: The filname :type filename: String :param path: The path to the file that needs to be uploaded :type path: String :returns: void """ |
f = open(path, 'rb')
self.source_size = os.stat(path).st_size
total_dict = {}
def cb(part_no, uploaded, total):
total_dict[part_no] = uploaded
params = {
'uploaded': round(sum(total_dict.values()) / 1048576, 0),
'size': round(self.source_size / 1048576, 0),
}
p = (self.progress_template + '\r') % params
STREAM.write(p)
STREAM.flush()
self.output('Uploading to S3', normal=True, arrow=True)
upload(bucket_name, self.key, self.secret,
data_collector(iter(f)), filename, cb,
threads=10, replace=True, secure=True, connection=self.conn)
print('\n')
self.output('Upload Completed', normal=True, arrow=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 download(self, scenes, bands=None):
""" Download scenese from Google Storage or Amazon S3 if bands are provided :param scenes: A list of scene IDs :type scenes: List :param bands: A list of bands. Default value is None. :type scenes: List :returns: (List) includes downloaded scenes as key and source as value (aws or google) """ |
if isinstance(scenes, list):
files = []
for scene in scenes:
# for all scenes if bands provided, first check AWS, if the bands exist
# download them, otherwise use Google and then USGS.
try:
# if bands are not provided, directly go to Goodle and then USGS
if not isinstance(bands, list):
raise RemoteFileDoesntExist
files.append(self.amazon_s3(scene, bands))
except RemoteFileDoesntExist:
try:
files.append(self.google_storage(scene, self.download_dir))
except RemoteFileDoesntExist:
files.append(self.usgs_eros(scene, self.download_dir))
return files
else:
raise Exception('Expected sceneIDs list') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def usgs_eros(self, scene, path):
""" Downloads the image from USGS """ |
# download from usgs if login information is provided
if self.usgs_user and self.usgs_pass:
try:
api_key = api.login(self.usgs_user, self.usgs_pass)
except USGSError as e:
error_tree = ElementTree.fromstring(str(e.message))
error_text = error_tree.find("SOAP-ENV:Body/SOAP-ENV:Fault/faultstring", api.NAMESPACES).text
raise USGSInventoryAccessMissing(error_text)
download_url = api.download('LANDSAT_8', 'EE', [scene], api_key=api_key)
if download_url:
self.output('Source: USGS EarthExplorer', normal=True, arrow=True)
return self.fetch(download_url[0], path)
raise RemoteFileDoesntExist('%s is not available on AWS S3, Google or USGS Earth Explorer' % scene)
raise RemoteFileDoesntExist('%s is not available on AWS S3 or Google Storage' % scene) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def google_storage(self, scene, path):
""" Google Storage Downloader. :param scene: The scene id :type scene: String :param path: The directory path to where the image should be stored :type path: String :returns: Boolean """ |
sat = self.scene_interpreter(scene)
url = self.google_storage_url(sat)
self.remote_file_exists(url)
self.output('Source: Google Storage', normal=True, arrow=True)
return self.fetch(url, 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 amazon_s3(self, scene, bands):
""" Amazon S3 downloader """ |
sat = self.scene_interpreter(scene)
# Always grab MTL.txt and QA band if bands are specified
if 'BQA' not in bands:
bands.append('QA')
if 'MTL' not in bands:
bands.append('MTL')
urls = []
for band in bands:
# get url for the band
url = self.amazon_s3_url(sat, band)
# make sure it exist
self.remote_file_exists(url)
urls.append(url)
# create folder
path = check_create_folder(join(self.download_dir, scene))
self.output('Source: AWS S3', normal=True, arrow=True)
for url in urls:
self.fetch(url, path)
return 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 fetch(self, url, path):
""" Downloads the given url. :param url: The url to be downloaded. :type url: String :param path: The directory path to where the image should be stored :type path: String :param filename: The filename that has to be downloaded :type filename: String :returns: Boolean """ |
segments = url.split('/')
filename = segments[-1]
# remove query parameters from the filename
filename = filename.split('?')[0]
self.output('Downloading: %s' % filename, normal=True, arrow=True)
# print(join(path, filename))
# raise Exception
if exists(join(path, filename)):
size = getsize(join(path, filename))
if size == self.get_remote_file_size(url):
self.output('%s already exists on your system' % filename, normal=True, color='green', indent=1)
else:
fetch(url, path)
self.output('stored at %s' % path, normal=True, color='green', indent=1)
return join(path, filename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def google_storage_url(self, sat):
""" Returns a google storage url the contains the scene provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :returns: (String) The URL to a google storage file """ |
filename = sat['scene'] + '.tar.bz'
return url_builder([self.google, sat['sat'], sat['path'], sat['row'], filename]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def amazon_s3_url(self, sat, band):
""" Return an amazon s3 url the contains the scene and band provided. :param sat: Expects an object created by scene_interpreter method :type sat: dict :param filename: The filename that has to be downloaded from Amazon :type filename: String :returns: (String) The URL to a S3 file """ |
if band != 'MTL':
filename = '%s_B%s.TIF' % (sat['scene'], band)
else:
filename = '%s_%s.txt' % (sat['scene'], band)
return url_builder([self.s3, sat['sat'], sat['path'], sat['row'], sat['scene'], filename]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remote_file_exists(self, url):
""" Checks whether the remote file exists. :param url: The url that has to be checked. :type url: String :returns: **True** if remote file exists and **False** if it doesn't exist. """ |
status = requests.head(url).status_code
if status != 200:
raise RemoteFileDoesntExist |
<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_remote_file_size(self, url):
""" Gets the filesize of a remote file. :param url: The url that has to be checked. :type url: String :returns: int """ |
headers = requests.head(url).headers
return int(headers['content-length']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scene_interpreter(self, scene):
""" Conver sceneID to rows, paths and dates. :param scene: The scene ID. :type scene: String :returns: dict :Example output: 'path': None, 'row': None, 'sat': None, 'scene': scene } """ |
anatomy = {
'path': None,
'row': None,
'sat': None,
'scene': scene
}
if isinstance(scene, str) and len(scene) == 21:
anatomy['path'] = scene[3:6]
anatomy['row'] = scene[6:9]
anatomy['sat'] = 'L' + scene[2:3]
return anatomy
else:
raise IncorrectSceneId('Received incorrect scene') |
<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(self, paths_rows=None, lat=None, lon=None, address=None, start_date=None, end_date=None, cloud_min=None, cloud_max=None, limit=1, geojson=False):
""" The main method of Search class. It searches Development Seed's Landsat API. :param paths_rows: A string in this format: "003,003,004,004". Must be in pairs and separated by comma. :type paths_rows: String :param lat: The latitude :type lat: String, float, integer :param lon: The The longitude :type lon: String, float, integer :param address: The address :type address: String :param start_date: Date string. format: YYYY-MM-DD :type start_date: String :param end_date: date string. format: YYYY-MM-DD :type end_date: String :param cloud_min: float specifying the minimum percentage. e.g. 4.3 :type cloud_min: float :param cloud_max: float specifying the maximum percentage. e.g. 78.9 :type cloud_max: float :param limit: integer specigying the maximum results return. :type limit: integer :param geojson: boolean specifying whether to return a geojson object :type geojson: boolean :returns: dict :example: 'status': u'SUCCESS', 'total_returned': 1, 'total': 1, 'limit': 1 'results': [ { 'sat_type': u'L8', 'sceneID': u'LC80030032014142LGN00', 'date': u'2014-05-22', 'path': u'003', 'cloud': 33.36, 'row': u'003 } ] } """ |
search_string = self.query_builder(paths_rows, lat, lon, address, start_date, end_date, cloud_min, cloud_max)
# Have to manually build the URI to bypass requests URI encoding
# The api server doesn't accept encoded URIs
r = requests.get('%s?search=%s&limit=%s' % (self.api_url, search_string, limit))
r_dict = json.loads(r.text)
result = {}
if 'error' in r_dict:
result['status'] = u'error'
result['code'] = r_dict['error']['code']
result['message'] = r_dict['error']['message']
elif 'meta' in r_dict:
if geojson:
result = {
'type': 'FeatureCollection',
'features': []
}
for r in r_dict['results']:
feature = {
'type': 'Feature',
'properties': {
'sceneID': r['sceneID'],
'row': three_digit(r['row']),
'path': three_digit(r['path']),
'thumbnail': r['browseURL'],
'date': r['acquisitionDate'],
'cloud': r['cloud_coverage']
},
'geometry': {
'type': 'Polygon',
'coordinates': [
[
[r['upperLeftCornerLongitude'], r['upperLeftCornerLatitude']],
[r['lowerLeftCornerLongitude'], r['lowerLeftCornerLatitude']],
[r['lowerRightCornerLongitude'], r['lowerRightCornerLatitude']],
[r['upperRightCornerLongitude'], r['upperRightCornerLatitude']],
[r['upperLeftCornerLongitude'], r['upperLeftCornerLatitude']]
]
]
}
}
result['features'].append(feature)
else:
result['status'] = u'SUCCESS'
result['total'] = r_dict['meta']['found']
result['limit'] = r_dict['meta']['limit']
result['total_returned'] = len(r_dict['results'])
result['results'] = [{'sceneID': i['sceneID'],
'sat_type': u'L8',
'path': three_digit(i['path']),
'row': three_digit(i['row']),
'thumbnail': i['browseURL'],
'date': i['acquisitionDate'],
'cloud': i['cloud_coverage']}
for i in r_dict['results']]
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 date_range_builder(self, start='2013-02-11', end=None):
""" Builds date range query. :param start: Date string. format: YYYY-MM-DD :type start: String :param end: date string. format: YYYY-MM-DD :type end: String :returns: String """ |
if not end:
end = time.strftime('%Y-%m-%d')
return 'acquisitionDate:[%s+TO+%s]' % (start, end) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exit(message, code=0):
""" output a message to stdout and terminates the process. :param message: Message to be outputed. :type message: String :param code: The termination code. Default is 0 :type code: int :returns: void """ |
v = VerbosityMixin()
if code == 0:
v.output(message, normal=True, arrow=True)
v.output('Done!', normal=True, arrow=True)
else:
v.output(message, normal=True, error=True)
sys.exit(code) |
<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_paired_list(value):
""" Create a list of paired items from a string. :param value: the format must be 003,003,004,004 (commas with no space) :type value: String :returns: List :example: [['003','003'], ['004', '004']] """ |
if isinstance(value, list):
value = ",".join(value)
array = re.split('\D+', value)
# Make sure the elements in the list are even and pairable
if len(array) % 2 == 0:
new_array = [list(array[i:i + 2]) for i in range(0, len(array), 2)]
return new_array
else:
raise ValueError('The string should include pairs and be formated. '
'The format must be 003,003,004,004 (commas with '
'no space)') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_create_folder(folder_path):
""" Check whether a folder exists, if not the folder is created. :param folder_path: Path to the folder :type folder_path: String :returns: (String) the path to the folder """ |
if not os.path.exists(folder_path):
os.makedirs(folder_path)
return folder_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 three_digit(number):
""" Add 0s to inputs that their length is less than 3. :param number: The number to convert :type number: int :returns: String :example: '001' """ |
number = str(number)
if len(number) == 1:
return u'00%s' % number
elif len(number) == 2:
return u'0%s' % number
else:
return number |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def georgian_day(date):
""" Returns the number of days passed since the start of the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: 121 """ |
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_yday
except (ValueError, TypeError):
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def year(date):
""" Returns the year. :param date: The string date with this format %m/%d/%Y :type date: String :returns: int :example: 2015 """ |
try:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).timetuple().tm_year
except ValueError:
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reformat_date(date, new_fmt='%Y-%m-%d'):
""" Returns reformated date. :param date: The string date with this format %m/%d/%Y :type date: String :param new_fmt: date format string. Default is '%Y-%m-%d' :type date: String :returns: int :example: '1/05/2015' """ |
try:
if isinstance(date, datetime):
return date.strftime(new_fmt)
else:
fmt = '%m/%d/%Y'
return datetime.strptime(date, fmt).strftime(new_fmt)
except ValueError:
return 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 geocode(address, required_precision_km=1.):
""" Identifies the coordinates of an address :param address: the address to be geocoded :type value: String :param required_precision_km: the maximum permissible geographic uncertainty for the geocoding :type required_precision_km: float :returns: dict :example: {'lat': 38.89767579999999, 'lon': -77.0364827} """ |
geocoded = geocoder.google(address)
precision_km = geocode_confidences[geocoded.confidence]
if precision_km <= required_precision_km:
(lon, lat) = geocoded.geometry['coordinates']
return {'lat': lat, 'lon': lon}
else:
raise ValueError("Address could not be precisely located") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adjust_bounding_box(bounds1, bounds2):
""" If the bounds 2 corners are outside of bounds1, they will be adjusted to bounds1 corners @params bounds1 - The source bounding box bounds2 - The target bounding box that has to be within bounds1 @return A bounding box tuple in (y1, x1, y2, x2) format """ |
# out of bound check
# If it is completely outside of target bounds, return target bounds
if ((bounds2[0] > bounds1[0] and bounds2[2] > bounds1[0]) or
(bounds2[2] < bounds1[2] and bounds2[2] < bounds1[0])):
return bounds1
if ((bounds2[1] < bounds1[1] and bounds2[3] < bounds1[1]) or
(bounds2[3] > bounds1[3] and bounds2[1] > bounds1[3])):
return bounds1
new_bounds = list(bounds2)
# Adjust Y axis (Longitude)
if (bounds2[0] > bounds1[0] or bounds2[0] < bounds1[3]):
new_bounds[0] = bounds1[0]
if (bounds2[2] < bounds1[2] or bounds2[2] > bounds1[0]):
new_bounds[2] = bounds1[2]
# Adjust X axis (Latitude)
if (bounds2[1] < bounds1[1] or bounds2[1] > bounds1[3]):
new_bounds[1] = bounds1[1]
if (bounds2[3] > bounds1[3] or bounds2[3] < bounds1[1]):
new_bounds[3] = bounds1[3]
return tuple(new_bounds) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.